text
stringlengths 7
1.01M
|
|---|
// Copyright 2019 Google LLC
//
// 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 com.google.sps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** */
@RunWith(JUnit4.class)
public final class FindMeetingQueryTest {
private static final Collection<Event> NO_EVENTS = Collections.emptySet();
private static final Collection<String> NO_ATTENDEES = Collections.emptySet();
// Some people that we can use in our tests.
private static final String PERSON_A = "Person A";
private static final String PERSON_B = "Person B";
private static final String PERSON_C = "Person C";
// All dates are the first day of the year 2020.
private static final int TIME_0800AM = TimeRange.getTimeInMinutes(8, 0);
private static final int TIME_0830AM = TimeRange.getTimeInMinutes(8, 30);
private static final int TIME_0900AM = TimeRange.getTimeInMinutes(9, 0);
private static final int TIME_0930AM = TimeRange.getTimeInMinutes(9, 30);
private static final int TIME_1000AM = TimeRange.getTimeInMinutes(10, 0);
private static final int TIME_1100AM = TimeRange.getTimeInMinutes(11, 00);
private static final int DURATION_15_MINUTES = 15;
private static final int DURATION_30_MINUTES = 30;
private static final int DURATION_60_MINUTES = 60;
private static final int DURATION_90_MINUTES = 90;
private static final int DURATION_1_HOUR = 60;
private static final int DURATION_2_HOUR = 120;
private FindMeetingQuery query;
@Before
public void setUp() {
query = new FindMeetingQuery();
}
@Test
public void optionsForNoAttendees() {
MeetingRequest request = new MeetingRequest(NO_ATTENDEES, DURATION_1_HOUR);
Collection<TimeRange> actual = query.query(NO_EVENTS, request);
Collection<TimeRange> expected = Arrays.asList(TimeRange.WHOLE_DAY);
Assert.assertEquals(expected, actual);
}
@Test
public void noOptionsForTooLongOfARequest() {
// The duration should be longer than a day. This means there should be no options.
int duration = TimeRange.WHOLE_DAY.duration() + 1;
MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), duration);
Collection<TimeRange> actual = query.query(NO_EVENTS, request);
Collection<TimeRange> expected = Arrays.asList();
Assert.assertEquals(expected, actual);
}
@Test
public void eventSplitsRestriction() {
// The event should split the day into two options (before and after the event).
Collection<Event> events = Arrays.asList(new Event("Event 1",
TimeRange.fromStartDuration(TIME_0830AM, DURATION_30_MINUTES), Arrays.asList(PERSON_A)));
MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
TimeRange.fromStartEnd(TIME_0900AM, TimeRange.END_OF_DAY, true));
Assert.assertEquals(expected, actual);
}
@Test
public void everyAttendeeIsConsidered() {
// Have each person have different events. We should see two options because each person has
// split the restricted times.
//
// Events : |--A--| |--B--|
// Day : |-----------------------------|
// Options : |--1--| |--2--| |--3--|
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartDuration(TIME_0800AM, DURATION_30_MINUTES),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartDuration(TIME_0900AM, DURATION_30_MINUTES),
Arrays.asList(PERSON_B))
);
MeetingRequest request =
new MeetingRequest(Arrays.asList(PERSON_A, PERSON_B), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0800AM, false),
TimeRange.fromStartEnd(TIME_0830AM, TIME_0900AM, false),
TimeRange.fromStartEnd(TIME_0930AM, TimeRange.END_OF_DAY, true));
Assert.assertEquals(expected, actual);
}
@Test
public void everyAttendeeIsConsidered2() {
// Have each person have different events. We should see two options because each person has
// split the restricted times.
//
// Events : |--A--| |--B--|
// Day : |-----------------------------|
// Options : |--1--| |--2--| |--3--|
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartDuration(TIME_0800AM, DURATION_30_MINUTES),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartDuration(TIME_0900AM, DURATION_30_MINUTES),
Arrays.asList(PERSON_B)),
new Event("Event 3", TimeRange.WHOLE_DAY,Arrays.asList(PERSON_C))
);
MeetingRequest request =
new MeetingRequest(Arrays.asList(PERSON_A, PERSON_B), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0800AM, false),
TimeRange.fromStartEnd(TIME_0830AM, TIME_0900AM, false),
TimeRange.fromStartEnd(TIME_0930AM, TimeRange.END_OF_DAY, true));
Assert.assertEquals(expected, actual);
}
@Test
public void overlappingEvents() {
// Have an event for each person, but have their events overlap. We should only see two options.
//
// Events : |--A--|
// |--B--|
// Day : |---------------------|
// Options : |--1--| |--2--|
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartDuration(TIME_0830AM, DURATION_60_MINUTES),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartDuration(TIME_0900AM, DURATION_60_MINUTES),
Arrays.asList(PERSON_B)));
MeetingRequest request =
new MeetingRequest(Arrays.asList(PERSON_A, PERSON_B), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
TimeRange.fromStartEnd(TIME_1000AM, TimeRange.END_OF_DAY, true));
Assert.assertEquals(expected, actual);
}
@Test
public void nestedEvents() {
// Have an event for each person, but have one person's event fully contain another's event. We
// should see two options.
//
// Events : |----A----|
// |--B--|
// Day : |---------------------|
// Options : |--1--| |--2--|
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartDuration(TIME_0830AM, DURATION_90_MINUTES),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartDuration(TIME_0900AM, DURATION_30_MINUTES),
Arrays.asList(PERSON_B)));
MeetingRequest request =
new MeetingRequest(Arrays.asList(PERSON_A, PERSON_B), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
TimeRange.fromStartEnd(TIME_1000AM, TimeRange.END_OF_DAY, true));
Assert.assertEquals(expected, actual);
}
@Test
public void doubleBookedPeople() {
// Have one person, but have them registered to attend two events at the same time.
//
// Events : |----A----|
// |--A--|
// Day : |---------------------|
// Options : |--1--| |--2--|
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartDuration(TIME_0830AM, DURATION_60_MINUTES),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartDuration(TIME_0900AM, DURATION_30_MINUTES),
Arrays.asList(PERSON_A)));
MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
TimeRange.fromStartEnd(TIME_0930AM, TimeRange.END_OF_DAY, true));
Assert.assertEquals(expected, actual);
}
@Test
public void justEnoughRoom() {
// Have one person, but make it so that there is just enough room at one point in the day to
// have the meeting.
//
// Events : |--A--| |----A----|
// Day : |---------------------|
// Options : |-----|
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartEnd(TIME_0900AM, TimeRange.END_OF_DAY, true),
Arrays.asList(PERSON_A))
);
MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartDuration(TIME_0830AM, DURATION_30_MINUTES));
Assert.assertEquals(expected, actual);
}
@Test
public void justEnoughRoom2() {
// Have one person, but make it so that there is just enough room at one point in the day to
// have the meeting.
//
// Events : |--A--| |----A----|
// Day : |---------------------|
// Options : |-----|
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartEnd(TIME_0900AM, TimeRange.END_OF_DAY, true),
Arrays.asList(PERSON_A)),
new Event("Event 3", TimeRange.fromStartDuration(TIME_0830AM, DURATION_15_MINUTES),
Arrays.asList(PERSON_B))
);
MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_30_MINUTES);
request.addOptionalAttendee(PERSON_B);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected =
Arrays.asList(TimeRange.fromStartDuration(TIME_0830AM, DURATION_30_MINUTES));
Assert.assertEquals(expected, actual);
}
@Test
public void ignoresPeopleNotAttending() {
// Add an event, but make the only attendee someone different from the person looking to book
// a meeting. This event should not affect the booking.
Collection<Event> events = Arrays.asList(new Event("Event 1",
TimeRange.fromStartDuration(TIME_0900AM, DURATION_30_MINUTES), Arrays.asList(PERSON_A)));
MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_B), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected = Arrays.asList(TimeRange.WHOLE_DAY);
Assert.assertEquals(expected, actual);
}
@Test
public void noConflicts() {
MeetingRequest request =
new MeetingRequest(Arrays.asList(PERSON_A, PERSON_B), DURATION_30_MINUTES);
Collection<TimeRange> actual = query.query(NO_EVENTS, request);
Collection<TimeRange> expected = Arrays.asList(TimeRange.WHOLE_DAY);
Assert.assertEquals(expected, actual);
}
@Test
public void notEnoughRoom() {
// Have one person, but make it so that there is not enough room at any point in the day to
// have the meeting.
//
// Events : |--A-----| |-----A----|
// Day : |---------------------|
// Options :
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartEnd(TIME_0900AM, TimeRange.END_OF_DAY, true),
Arrays.asList(PERSON_A)));
MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_60_MINUTES);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected = Arrays.asList();
Assert.assertEquals(expected, actual);
}
@Test
public void mandatoryAttendeesWithGaps(){
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.fromStartEnd(TIME_0830AM, TIME_0900AM, false),
Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.fromStartEnd(TIME_1000AM, TIME_1100AM, false),
Arrays.asList(PERSON_B)));
MeetingRequest request = new MeetingRequest(NO_ATTENDEES, DURATION_60_MINUTES);
request.addOptionalAttendee(PERSON_A);
request.addOptionalAttendee(PERSON_B);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected = Arrays.asList(TimeRange.fromStartEnd(TimeRange.START_OF_DAY, TIME_0830AM, false),
TimeRange.fromStartEnd(TIME_0900AM, TIME_1000AM, false),
TimeRange.fromStartEnd(TIME_1100AM, TimeRange.END_OF_DAY, true));
Assert.assertEquals(expected, actual);
}
@Test
public void mandatoryAttendeesWithoutGaps(){
Collection<Event> events = Arrays.asList(
new Event("Event 1", TimeRange.WHOLE_DAY,Arrays.asList(PERSON_A)),
new Event("Event 2", TimeRange.WHOLE_DAY,Arrays.asList(PERSON_B))
);
MeetingRequest request = new MeetingRequest(NO_ATTENDEES, DURATION_60_MINUTES);
request.addOptionalAttendee(PERSON_A);
request.addOptionalAttendee(PERSON_B);
Collection<TimeRange> actual = query.query(events, request);
Collection<TimeRange> expected = Arrays.asList(TimeRange.WHOLE_DAY);
Assert.assertEquals(expected, actual);
}
}
|
package com.rarible.core.mongo.configuration;
import com.rarible.core.mongo.converter.BigDecimalCustomMongoConverter;
import com.rarible.core.mongo.converter.BigIntegerCustomMongoConverter;
import com.rarible.core.mongo.converter.CustomConversionsFactory;
import com.rarible.core.mongo.converter.CustomMongoConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class ConvertersConfiguration {
@Bean
public CustomMongoConverter bigIntegerCustomMongoConverter() {
return new BigIntegerCustomMongoConverter();
}
@Bean
public CustomMongoConverter bigDecimalCustomMongoConverter() {
return new BigDecimalCustomMongoConverter();
}
@Bean
public CustomConversionsFactory customConversionsFactory(List<CustomMongoConverter> customMongoConverters) {
return new CustomConversionsFactory(customMongoConverters);
}
}
|
package cn.estore.domain;
import java.io.Serializable;
/**
* 商品类
*
*
*
*/
public class Product implements Serializable {
private String id; // 商品编号
private String name; // 名称
private double price; // 价格
private String category; // 分类
private int pnum; // 数量
private String imgurl; // 图片路径
private String description; // 描述
private int totalSaleNum; // 总销售数量
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getPnum() {
return pnum;
}
public void setPnum(int pnum) {
this.pnum = pnum;
}
// 原图路径
public String getImgurl() {
return imgurl;
}
// 返回小图路径
public String getImgurl_s() {
String prefix = imgurl.substring(0, imgurl.lastIndexOf("."));
String ext = imgurl.substring(imgurl.lastIndexOf("."));
return prefix + "_s" + ext;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setTotalSaleNum(int totalSaleNum) {
this.totalSaleNum = totalSaleNum;
}
public int getTotalSaleNum() {
return totalSaleNum;
}
}
|
package com.github.seratch.jslack.api.model;
import com.github.seratch.jslack.api.model.block.LayoutBlock;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
/**
* https://api.slack.com/docs/message-attachments
*/
public class Attachment {
private String msgSubtype; // "bot_message"
/**
* A plain-text summary of the attachment. This text will be used in clients that don't show formatted text
* (eg. IRC, mobile notifications) and should not contain any markup.
*/
private String fallback;
/**
* This is optional value that specifies callback id when there are buttons.
*/
private String callbackId;
/**
* Like traffic signals, color-coding messages can quickly communicate intent
* and help separate them from the flow of other messages in the timeline.
* <p>
* An optional value that can either be one of good, warning, danger, or any hex color code (eg. #439FE0).
* This value is used to color the border along the left side of the message attachment.
*/
private String color;
/**
* This is optional text that appears above the message attachment block.
*/
private String pretext;
private String serviceUrl;
private String serviceName;
private String serviceIcon;
// -----------------------------------------
// The author parameters will display a small section at the top of a message attachment that can contain the following fields:
/**
* Small text used to display the author's name.
*/
private String authorName;
/**
* A valid URL that will hyperlink the author_name text mentioned above. Will only work if author_name is present.
*/
private String authorLink;
/**
* A valid URL that displays a small 16x16px image to the left of the author_name text. Will only work if author_name is present.
*/
private String authorIcon;
// -----------------------------------------
// Attributes for reply_broadcast message (showing a posted message as an attachment)
// https://api.slack.com/events/message/reply_broadcast
// "from_url": "https://lost-generation-authors.slack.com/archives/general/p1482960137003543",
private String fromUrl;
private String originalUrl;
// "author_subname": "confused",
private String authorSubname;
// "channel_id": "C061EG9SL",
private String channelId;
// "channel_name": "general",
private String channelName;
//"id": 1,
private Integer id;
private String botId;
private Boolean indent;
public Attachment(String msgSubtype, String fallback, String callbackId, String color, String pretext, String serviceUrl, String serviceName, String serviceIcon, String authorName, String authorLink, String authorIcon, String fromUrl, String originalUrl, String authorSubname, String channelId, String channelName, Integer id, String botId, Boolean indent, Boolean msgUnfurl, Boolean replyUnfurl, Boolean threadRootUnfurl, Boolean appUnfurl, String appUnfurlUrl, String title, String titleLink, String text, List<Field> fields, String imageUrl, Integer imageWidth, Integer imageHeight, Integer imageBytes, String thumbUrl, Integer thumbWidth, Integer thumbHeight, String videoHtml, Integer videoHtmlWidth, Integer videoHtmlHeight, String footer, String footerIcon, String ts, List<String> mrkdwnIn, List<Action> actions, List<LayoutBlock> blocks, String filename, Integer size, String mimetype, String url, AttachmentMetadata metadata) {
this.msgSubtype = msgSubtype;
this.fallback = fallback;
this.callbackId = callbackId;
this.color = color;
this.pretext = pretext;
this.serviceUrl = serviceUrl;
this.serviceName = serviceName;
this.serviceIcon = serviceIcon;
this.authorName = authorName;
this.authorLink = authorLink;
this.authorIcon = authorIcon;
this.fromUrl = fromUrl;
this.originalUrl = originalUrl;
this.authorSubname = authorSubname;
this.channelId = channelId;
this.channelName = channelName;
this.id = id;
this.botId = botId;
this.indent = indent;
this.msgUnfurl = msgUnfurl;
this.replyUnfurl = replyUnfurl;
this.threadRootUnfurl = threadRootUnfurl;
this.appUnfurl = appUnfurl;
this.appUnfurlUrl = appUnfurlUrl;
this.title = title;
this.titleLink = titleLink;
this.text = text;
this.fields = fields;
this.imageUrl = imageUrl;
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
this.imageBytes = imageBytes;
this.thumbUrl = thumbUrl;
this.thumbWidth = thumbWidth;
this.thumbHeight = thumbHeight;
this.videoHtml = videoHtml;
this.videoHtmlWidth = videoHtmlWidth;
this.videoHtmlHeight = videoHtmlHeight;
this.footer = footer;
this.footerIcon = footerIcon;
this.ts = ts;
this.mrkdwnIn = mrkdwnIn;
this.actions = actions;
this.blocks = blocks;
this.filename = filename;
this.size = size;
this.mimetype = mimetype;
this.url = url;
this.metadata = metadata;
}
public Attachment() {
}
public static AttachmentBuilder builder() {
return new AttachmentBuilder();
}
public Boolean isIndent() {
return this.indent;
}
public void setIndent(Boolean indent) {
this.indent = indent;
}
// # already exists > "fallback": "[December 28th, 2016 1:22 PM] confused: what was there?",
// # already exists > "ts": "1482960137.003543",
// # already exists > "author_link": "https://lost-generation-authors.slack.com/team/confused",
// # already exists > "author_icon": "https://...png",
// # already exists > "mrkdwn_in": ["text"],
// # already exists > "text": "island",
// # already exists > "footer": "5 replies"
/**
* NOTE: The the following Booleans (is_msg_unfurl, is_reply_unfurl, is_thread_root_unfurl,
* is_app_unfurl) default to null intentionally to support block attachments.
*/
@SerializedName("is_msg_unfurl")
private Boolean msgUnfurl;
public Boolean isMsgUnfurl() {
return this.msgUnfurl;
}
public void setMsgUnfurl(Boolean msgUnfurl) {
this.msgUnfurl = msgUnfurl;
}
@SerializedName("is_reply_unfurl")
private Boolean replyUnfurl;
public Boolean isReplyUnfurl() {
return this.replyUnfurl;
}
public void setReplyUnfurl(Boolean replyUnfurl) {
this.replyUnfurl = replyUnfurl;
}
@SerializedName("is_thread_root_unfurl")
private Boolean threadRootUnfurl;
public Boolean isThreadRootUnfurl() {
return this.threadRootUnfurl;
}
public void setThreadRootUnfurl(Boolean threadRootUnfurl) {
this.threadRootUnfurl = threadRootUnfurl;
}
@SerializedName("is_app_unfurl")
private Boolean appUnfurl;
public Boolean isAppUnfurl() {
return this.appUnfurl;
}
public void setAppUnfurl(Boolean appUnfurl) {
this.appUnfurl = appUnfurl;
}
private String appUnfurlUrl;
/**
* The title is displayed as larger, bold text near the top of a message attachment.
* By passing a valid URL in the title_link parameter (optional), the title text will be hyperlinked.
*/
private String title;
/**
* The title is displayed as larger, bold text near the top of a message attachment.
* By passing a valid URL in the title_link parameter (optional), the title text will be hyperlinked.
*/
private String titleLink;
/**
* This is the main text in a message attachment, and can contain standard message markup (see details below).
* The content will automatically collapse if it contains 700+ characters or 5+ linebreaks,
* and will display a "Show more..." link to expand the content.
* <p>
* https://api.slack.com/docs/message-attachments#message_formatting
*/
private String text;
/**
* Fields are defined as an array, and hashes contained within it will be displayed in a table inside the message attachment.
*/
private List<Field> fields = new ArrayList<>();
/**
* A valid URL to an image file that will be displayed inside a message attachment.
* We currently support the following formats: GIF, JPEG, PNG, and BMP.
* <p>
* Large images will be resized to a maximum width of 400px or a maximum height of 500px,
* while still maintaining the original aspect ratio.
*/
private String imageUrl;
private Integer imageWidth;
private Integer imageHeight;
private Integer imageBytes;
/**
* A valid URL to an image file that will be displayed as a thumbnail on the right side of a message attachment.
* We currently support the following formats: GIF, JPEG, PNG, and BMP.
* <p>
* The thumbnail's longest dimension will be scaled down to 75px while maintaining the aspect ratio of the image.
* The filesize of the image must also be less than 500 KB.
* <p>
* For best results, please use images that are already 75px by 75px.
*/
private String thumbUrl;
private Integer thumbWidth;
private Integer thumbHeight;
private String videoHtml;
private Integer videoHtmlWidth;
private Integer videoHtmlHeight;
// Your message attachments may also contain a subtle footer,
// which is especially useful when citing content in conjunction with author parameters.
/**
* Add some brief text to help contextualize and identify an attachment.
* Limited to 300 characters, and may be truncated further when displayed to users in environments with limited screen real estate.
*/
private String footer;
/**
* To render a small icon beside your footer text, provide a publicly accessible URL string in the footer_icon field.
* You must also provide a footer for the field to be recognized.
* <p>
* We'll render what you provide at 16px by 16px. It's best to use an image that is similarly sized.
*/
private String footerIcon;
/**
* ts (timestamp)
* Does your attachment relate to something happening at a specific time?
* <p>
* By providing the ts field with an integer value in "epoch time",
* the attachment will display an additional timestamp value as part of the attachment's footer.
* <p>
* Use ts when referencing articles or happenings. Your message will have its own timestamp when published.
*/
private String ts;
/**
* By default,
* <a href="https://api.slack.com/docs/message-formatting#message_formatting">message text
* in attachments</a> are not formatted. To enable formatting on attachment fields, add the
* name of the field (as defined in the API) in this list.
*/
private List<String> mrkdwnIn = new ArrayList<>();
/**
* Actions are defined as an array, and hashes contained within it will be displayed in as buttons in the message attachment.
*/
private List<Action> actions = new ArrayList<>();
private List<LayoutBlock> blocks;
// --------------------------
// Files
private String filename;
private Integer size;
private String mimetype;
private String url;
private AttachmentMetadata metadata;
public String getMsgSubtype() {
return this.msgSubtype;
}
public String getFallback() {
return this.fallback;
}
public String getCallbackId() {
return this.callbackId;
}
public String getColor() {
return this.color;
}
public String getPretext() {
return this.pretext;
}
public String getServiceUrl() {
return this.serviceUrl;
}
public String getServiceName() {
return this.serviceName;
}
public String getServiceIcon() {
return this.serviceIcon;
}
public String getAuthorName() {
return this.authorName;
}
public String getAuthorLink() {
return this.authorLink;
}
public String getAuthorIcon() {
return this.authorIcon;
}
public String getFromUrl() {
return this.fromUrl;
}
public String getOriginalUrl() {
return this.originalUrl;
}
public String getAuthorSubname() {
return this.authorSubname;
}
public String getChannelId() {
return this.channelId;
}
public String getChannelName() {
return this.channelName;
}
public Integer getId() {
return this.id;
}
public String getBotId() {
return this.botId;
}
public String getAppUnfurlUrl() {
return this.appUnfurlUrl;
}
public String getTitle() {
return this.title;
}
public String getTitleLink() {
return this.titleLink;
}
public String getText() {
return this.text;
}
public List<Field> getFields() {
return this.fields;
}
public String getImageUrl() {
return this.imageUrl;
}
public Integer getImageWidth() {
return this.imageWidth;
}
public Integer getImageHeight() {
return this.imageHeight;
}
public Integer getImageBytes() {
return this.imageBytes;
}
public String getThumbUrl() {
return this.thumbUrl;
}
public Integer getThumbWidth() {
return this.thumbWidth;
}
public Integer getThumbHeight() {
return this.thumbHeight;
}
public String getVideoHtml() {
return this.videoHtml;
}
public Integer getVideoHtmlWidth() {
return this.videoHtmlWidth;
}
public Integer getVideoHtmlHeight() {
return this.videoHtmlHeight;
}
public String getFooter() {
return this.footer;
}
public String getFooterIcon() {
return this.footerIcon;
}
public String getTs() {
return this.ts;
}
public List<String> getMrkdwnIn() {
return this.mrkdwnIn;
}
public List<Action> getActions() {
return this.actions;
}
public List<LayoutBlock> getBlocks() {
return this.blocks;
}
public String getFilename() {
return this.filename;
}
public Integer getSize() {
return this.size;
}
public String getMimetype() {
return this.mimetype;
}
public String getUrl() {
return this.url;
}
public AttachmentMetadata getMetadata() {
return this.metadata;
}
public void setMsgSubtype(String msgSubtype) {
this.msgSubtype = msgSubtype;
}
public void setFallback(String fallback) {
this.fallback = fallback;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
public void setColor(String color) {
this.color = color;
}
public void setPretext(String pretext) {
this.pretext = pretext;
}
public void setServiceUrl(String serviceUrl) {
this.serviceUrl = serviceUrl;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setServiceIcon(String serviceIcon) {
this.serviceIcon = serviceIcon;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public void setAuthorLink(String authorLink) {
this.authorLink = authorLink;
}
public void setAuthorIcon(String authorIcon) {
this.authorIcon = authorIcon;
}
public void setFromUrl(String fromUrl) {
this.fromUrl = fromUrl;
}
public void setOriginalUrl(String originalUrl) {
this.originalUrl = originalUrl;
}
public void setAuthorSubname(String authorSubname) {
this.authorSubname = authorSubname;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public void setId(Integer id) {
this.id = id;
}
public void setBotId(String botId) {
this.botId = botId;
}
public void setAppUnfurlUrl(String appUnfurlUrl) {
this.appUnfurlUrl = appUnfurlUrl;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleLink(String titleLink) {
this.titleLink = titleLink;
}
public void setText(String text) {
this.text = text;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public void setImageWidth(Integer imageWidth) {
this.imageWidth = imageWidth;
}
public void setImageHeight(Integer imageHeight) {
this.imageHeight = imageHeight;
}
public void setImageBytes(Integer imageBytes) {
this.imageBytes = imageBytes;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public void setThumbWidth(Integer thumbWidth) {
this.thumbWidth = thumbWidth;
}
public void setThumbHeight(Integer thumbHeight) {
this.thumbHeight = thumbHeight;
}
public void setVideoHtml(String videoHtml) {
this.videoHtml = videoHtml;
}
public void setVideoHtmlWidth(Integer videoHtmlWidth) {
this.videoHtmlWidth = videoHtmlWidth;
}
public void setVideoHtmlHeight(Integer videoHtmlHeight) {
this.videoHtmlHeight = videoHtmlHeight;
}
public void setFooter(String footer) {
this.footer = footer;
}
public void setFooterIcon(String footerIcon) {
this.footerIcon = footerIcon;
}
public void setTs(String ts) {
this.ts = ts;
}
public void setMrkdwnIn(List<String> mrkdwnIn) {
this.mrkdwnIn = mrkdwnIn;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
public void setBlocks(List<LayoutBlock> blocks) {
this.blocks = blocks;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setSize(Integer size) {
this.size = size;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
}
public void setUrl(String url) {
this.url = url;
}
public void setMetadata(AttachmentMetadata metadata) {
this.metadata = metadata;
}
public static class AttachmentMetadata {
@SerializedName("thumb_64")
private Boolean thumb64;
@SerializedName("thumb_80")
private Boolean thumb80;
@SerializedName("thumb_160")
private Boolean thumb160;
@SerializedName("original_w")
private Integer originalWidth;
@SerializedName("original_h")
private Integer originalHeight;
@SerializedName("thumb_360_w")
private Integer thumb360Width;
@SerializedName("thumb_360_h")
private Integer thumb360Height;
private String format;
private String extension;
private Integer rotation;
private String thumbTiny;
public AttachmentMetadata(Boolean thumb64, Boolean thumb80, Boolean thumb160, Integer originalWidth, Integer originalHeight, Integer thumb360Width, Integer thumb360Height, String format, String extension, Integer rotation, String thumbTiny) {
this.thumb64 = thumb64;
this.thumb80 = thumb80;
this.thumb160 = thumb160;
this.originalWidth = originalWidth;
this.originalHeight = originalHeight;
this.thumb360Width = thumb360Width;
this.thumb360Height = thumb360Height;
this.format = format;
this.extension = extension;
this.rotation = rotation;
this.thumbTiny = thumbTiny;
}
public AttachmentMetadata() {
}
public static AttachmentMetadataBuilder builder() {
return new AttachmentMetadataBuilder();
}
public Boolean getThumb64() {
return this.thumb64;
}
public Boolean getThumb80() {
return this.thumb80;
}
public Boolean getThumb160() {
return this.thumb160;
}
public Integer getOriginalWidth() {
return this.originalWidth;
}
public Integer getOriginalHeight() {
return this.originalHeight;
}
public Integer getThumb360Width() {
return this.thumb360Width;
}
public Integer getThumb360Height() {
return this.thumb360Height;
}
public String getFormat() {
return this.format;
}
public String getExtension() {
return this.extension;
}
public Integer getRotation() {
return this.rotation;
}
public String getThumbTiny() {
return this.thumbTiny;
}
public void setThumb64(Boolean thumb64) {
this.thumb64 = thumb64;
}
public void setThumb80(Boolean thumb80) {
this.thumb80 = thumb80;
}
public void setThumb160(Boolean thumb160) {
this.thumb160 = thumb160;
}
public void setOriginalWidth(Integer originalWidth) {
this.originalWidth = originalWidth;
}
public void setOriginalHeight(Integer originalHeight) {
this.originalHeight = originalHeight;
}
public void setThumb360Width(Integer thumb360Width) {
this.thumb360Width = thumb360Width;
}
public void setThumb360Height(Integer thumb360Height) {
this.thumb360Height = thumb360Height;
}
public void setFormat(String format) {
this.format = format;
}
public void setExtension(String extension) {
this.extension = extension;
}
public void setRotation(Integer rotation) {
this.rotation = rotation;
}
public void setThumbTiny(String thumbTiny) {
this.thumbTiny = thumbTiny;
}
public static class AttachmentMetadataBuilder {
private Boolean thumb64;
private Boolean thumb80;
private Boolean thumb160;
private Integer originalWidth;
private Integer originalHeight;
private Integer thumb360Width;
private Integer thumb360Height;
private String format;
private String extension;
private Integer rotation;
private String thumbTiny;
AttachmentMetadataBuilder() {
}
public AttachmentMetadata.AttachmentMetadataBuilder thumb64(Boolean thumb64) {
this.thumb64 = thumb64;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder thumb80(Boolean thumb80) {
this.thumb80 = thumb80;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder thumb160(Boolean thumb160) {
this.thumb160 = thumb160;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder originalWidth(Integer originalWidth) {
this.originalWidth = originalWidth;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder originalHeight(Integer originalHeight) {
this.originalHeight = originalHeight;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder thumb360Width(Integer thumb360Width) {
this.thumb360Width = thumb360Width;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder thumb360Height(Integer thumb360Height) {
this.thumb360Height = thumb360Height;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder format(String format) {
this.format = format;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder extension(String extension) {
this.extension = extension;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder rotation(Integer rotation) {
this.rotation = rotation;
return this;
}
public AttachmentMetadata.AttachmentMetadataBuilder thumbTiny(String thumbTiny) {
this.thumbTiny = thumbTiny;
return this;
}
public AttachmentMetadata build() {
return new AttachmentMetadata(thumb64, thumb80, thumb160, originalWidth, originalHeight, thumb360Width, thumb360Height, format, extension, rotation, thumbTiny);
}
public String toString() {
return "Attachment.AttachmentMetadata.AttachmentMetadataBuilder(thumb64=" + this.thumb64 + ", thumb80=" + this.thumb80 + ", thumb160=" + this.thumb160 + ", originalWidth=" + this.originalWidth + ", originalHeight=" + this.originalHeight + ", thumb360Width=" + this.thumb360Width + ", thumb360Height=" + this.thumb360Height + ", format=" + this.format + ", extension=" + this.extension + ", rotation=" + this.rotation + ", thumbTiny=" + this.thumbTiny + ")";
}
}
}
public static class AttachmentBuilder {
private String msgSubtype;
private String fallback;
private String callbackId;
private String color;
private String pretext;
private String serviceUrl;
private String serviceName;
private String serviceIcon;
private String authorName;
private String authorLink;
private String authorIcon;
private String fromUrl;
private String originalUrl;
private String authorSubname;
private String channelId;
private String channelName;
private Integer id;
private String botId;
private Boolean indent;
private Boolean msgUnfurl;
private Boolean replyUnfurl;
private Boolean threadRootUnfurl;
private Boolean appUnfurl;
private String appUnfurlUrl;
private String title;
private String titleLink;
private String text;
private List<Field> fields;
private String imageUrl;
private Integer imageWidth;
private Integer imageHeight;
private Integer imageBytes;
private String thumbUrl;
private Integer thumbWidth;
private Integer thumbHeight;
private String videoHtml;
private Integer videoHtmlWidth;
private Integer videoHtmlHeight;
private String footer;
private String footerIcon;
private String ts;
private List<String> mrkdwnIn;
private List<Action> actions;
private List<LayoutBlock> blocks;
private String filename;
private Integer size;
private String mimetype;
private String url;
private AttachmentMetadata metadata;
AttachmentBuilder() {
}
public AttachmentBuilder msgSubtype(String msgSubtype) {
this.msgSubtype = msgSubtype;
return this;
}
public AttachmentBuilder fallback(String fallback) {
this.fallback = fallback;
return this;
}
public AttachmentBuilder callbackId(String callbackId) {
this.callbackId = callbackId;
return this;
}
public AttachmentBuilder color(String color) {
this.color = color;
return this;
}
public AttachmentBuilder pretext(String pretext) {
this.pretext = pretext;
return this;
}
public AttachmentBuilder serviceUrl(String serviceUrl) {
this.serviceUrl = serviceUrl;
return this;
}
public AttachmentBuilder serviceName(String serviceName) {
this.serviceName = serviceName;
return this;
}
public AttachmentBuilder serviceIcon(String serviceIcon) {
this.serviceIcon = serviceIcon;
return this;
}
public AttachmentBuilder authorName(String authorName) {
this.authorName = authorName;
return this;
}
public AttachmentBuilder authorLink(String authorLink) {
this.authorLink = authorLink;
return this;
}
public AttachmentBuilder authorIcon(String authorIcon) {
this.authorIcon = authorIcon;
return this;
}
public AttachmentBuilder fromUrl(String fromUrl) {
this.fromUrl = fromUrl;
return this;
}
public AttachmentBuilder originalUrl(String originalUrl) {
this.originalUrl = originalUrl;
return this;
}
public AttachmentBuilder authorSubname(String authorSubname) {
this.authorSubname = authorSubname;
return this;
}
public AttachmentBuilder channelId(String channelId) {
this.channelId = channelId;
return this;
}
public AttachmentBuilder channelName(String channelName) {
this.channelName = channelName;
return this;
}
public AttachmentBuilder id(Integer id) {
this.id = id;
return this;
}
public AttachmentBuilder botId(String botId) {
this.botId = botId;
return this;
}
public AttachmentBuilder indent(Boolean indent) {
this.indent = indent;
return this;
}
public AttachmentBuilder msgUnfurl(Boolean msgUnfurl) {
this.msgUnfurl = msgUnfurl;
return this;
}
public AttachmentBuilder replyUnfurl(Boolean replyUnfurl) {
this.replyUnfurl = replyUnfurl;
return this;
}
public AttachmentBuilder threadRootUnfurl(Boolean threadRootUnfurl) {
this.threadRootUnfurl = threadRootUnfurl;
return this;
}
public AttachmentBuilder appUnfurl(Boolean appUnfurl) {
this.appUnfurl = appUnfurl;
return this;
}
public AttachmentBuilder appUnfurlUrl(String appUnfurlUrl) {
this.appUnfurlUrl = appUnfurlUrl;
return this;
}
public AttachmentBuilder title(String title) {
this.title = title;
return this;
}
public AttachmentBuilder titleLink(String titleLink) {
this.titleLink = titleLink;
return this;
}
public AttachmentBuilder text(String text) {
this.text = text;
return this;
}
public AttachmentBuilder fields(List<Field> fields) {
this.fields = fields;
return this;
}
public AttachmentBuilder imageUrl(String imageUrl) {
this.imageUrl = imageUrl;
return this;
}
public AttachmentBuilder imageWidth(Integer imageWidth) {
this.imageWidth = imageWidth;
return this;
}
public AttachmentBuilder imageHeight(Integer imageHeight) {
this.imageHeight = imageHeight;
return this;
}
public AttachmentBuilder imageBytes(Integer imageBytes) {
this.imageBytes = imageBytes;
return this;
}
public AttachmentBuilder thumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
return this;
}
public AttachmentBuilder thumbWidth(Integer thumbWidth) {
this.thumbWidth = thumbWidth;
return this;
}
public AttachmentBuilder thumbHeight(Integer thumbHeight) {
this.thumbHeight = thumbHeight;
return this;
}
public AttachmentBuilder videoHtml(String videoHtml) {
this.videoHtml = videoHtml;
return this;
}
public AttachmentBuilder videoHtmlWidth(Integer videoHtmlWidth) {
this.videoHtmlWidth = videoHtmlWidth;
return this;
}
public AttachmentBuilder videoHtmlHeight(Integer videoHtmlHeight) {
this.videoHtmlHeight = videoHtmlHeight;
return this;
}
public AttachmentBuilder footer(String footer) {
this.footer = footer;
return this;
}
public AttachmentBuilder footerIcon(String footerIcon) {
this.footerIcon = footerIcon;
return this;
}
public AttachmentBuilder ts(String ts) {
this.ts = ts;
return this;
}
public AttachmentBuilder mrkdwnIn(List<String> mrkdwnIn) {
this.mrkdwnIn = mrkdwnIn;
return this;
}
public AttachmentBuilder actions(List<Action> actions) {
this.actions = actions;
return this;
}
public AttachmentBuilder blocks(List<LayoutBlock> blocks) {
this.blocks = blocks;
return this;
}
public AttachmentBuilder filename(String filename) {
this.filename = filename;
return this;
}
public AttachmentBuilder size(Integer size) {
this.size = size;
return this;
}
public AttachmentBuilder mimetype(String mimetype) {
this.mimetype = mimetype;
return this;
}
public AttachmentBuilder url(String url) {
this.url = url;
return this;
}
public AttachmentBuilder metadata(AttachmentMetadata metadata) {
this.metadata = metadata;
return this;
}
public Attachment build() {
return new Attachment(msgSubtype, fallback, callbackId, color, pretext, serviceUrl, serviceName, serviceIcon, authorName, authorLink, authorIcon, fromUrl, originalUrl, authorSubname, channelId, channelName, id, botId, indent, msgUnfurl, replyUnfurl, threadRootUnfurl, appUnfurl, appUnfurlUrl, title, titleLink, text, fields, imageUrl, imageWidth, imageHeight, imageBytes, thumbUrl, thumbWidth, thumbHeight, videoHtml, videoHtmlWidth, videoHtmlHeight, footer, footerIcon, ts, mrkdwnIn, actions, blocks, filename, size, mimetype, url, metadata);
}
public String toString() {
return "Attachment.AttachmentBuilder(msgSubtype=" + this.msgSubtype + ", fallback=" + this.fallback + ", callbackId=" + this.callbackId + ", color=" + this.color + ", pretext=" + this.pretext + ", serviceUrl=" + this.serviceUrl + ", serviceName=" + this.serviceName + ", serviceIcon=" + this.serviceIcon + ", authorName=" + this.authorName + ", authorLink=" + this.authorLink + ", authorIcon=" + this.authorIcon + ", fromUrl=" + this.fromUrl + ", originalUrl=" + this.originalUrl + ", authorSubname=" + this.authorSubname + ", channelId=" + this.channelId + ", channelName=" + this.channelName + ", id=" + this.id + ", botId=" + this.botId + ", indent=" + this.indent + ", msgUnfurl=" + this.msgUnfurl + ", replyUnfurl=" + this.replyUnfurl + ", threadRootUnfurl=" + this.threadRootUnfurl + ", appUnfurl=" + this.appUnfurl + ", appUnfurlUrl=" + this.appUnfurlUrl + ", title=" + this.title + ", titleLink=" + this.titleLink + ", text=" + this.text + ", fields=" + this.fields + ", imageUrl=" + this.imageUrl + ", imageWidth=" + this.imageWidth + ", imageHeight=" + this.imageHeight + ", imageBytes=" + this.imageBytes + ", thumbUrl=" + this.thumbUrl + ", thumbWidth=" + this.thumbWidth + ", thumbHeight=" + this.thumbHeight + ", videoHtml=" + this.videoHtml + ", videoHtmlWidth=" + this.videoHtmlWidth + ", videoHtmlHeight=" + this.videoHtmlHeight + ", footer=" + this.footer + ", footerIcon=" + this.footerIcon + ", ts=" + this.ts + ", mrkdwnIn=" + this.mrkdwnIn + ", actions=" + this.actions + ", blocks=" + this.blocks + ", filename=" + this.filename + ", size=" + this.size + ", mimetype=" + this.mimetype + ", url=" + this.url + ", metadata=" + this.metadata + ")";
}
}
}
|
package eu.rambox.factorization;
import net.fabricmc.api.ModInitializer;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Factorization implements ModInitializer {
public static final Logger LOGGER = LogManager.getLogger("factorization");
@Override
public void onInitialize() {
LOGGER.info("Initializing Factorization mod!");
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.distributed.replicated;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.internal.processors.cache.distributed.GridDistributedTxPrepareRequest;
import org.apache.ignite.internal.processors.cache.distributed.IgniteTxOriginatingNodeFailureAbstractSelfTest;
/**
* Tests originating node failure in REPLICATED cache.
*/
public class GridCacheReplicatedTxOriginatingNodeFailureSelfTest extends
IgniteTxOriginatingNodeFailureAbstractSelfTest {
/** {@inheritDoc} */
@Override protected CacheMode cacheMode() {
return CacheMode.REPLICATED;
}
/** {@inheritDoc} */
@Override protected Class<?> ignoreMessageClass() {
return GridDistributedTxPrepareRequest.class;
}
}
|
package pregel;
/**
* Global state.
*
* INITIALIZED ---> LOADED ---> CLEANED ---> COMPUTED
* ^ |
* | |
* ------------
*/
public enum State {
INITIALIZED, // the master is just created.
LOADED, // workers loaded data.
CLEANED, // workers did clean up before compute.
COMPUTED // workers finished one superstep.
}
|
/*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI 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 net.sf.farrago.fennel.calc;
import org.eigenbase.rex.*;
/**
* Translates a call to an aggregate function to calculator assembly language.
*
* <p>Implementors are held in a {@link CalcRexImplementorTable}.
*
* @author jhyde
* @version $Id$
* @since June 2nd, 2004
*/
public interface CalcRexAggImplementor
{
//~ Methods ----------------------------------------------------------------
/**
* Generates instructions to initialize an accumulator for a call to this
* aggregate function, and returns the register which holds the accumulator.
*
* <p>For example, for <code>SUM(x)</code>, this method generates <code>O
* s8; V 0; T; MOVE O0, C0;</code> and returns the <code>O0</code> register.
*
* @param call The call to the aggregate function to be implemented
* @param accumulatorRegister The accumulator register to be populated
* @param translator Calculator code generator
*/
void implementInitialize(
RexCall call,
CalcReg accumulatorRegister,
RexToCalcTranslator translator);
/**
* Generates instructions to add a new value to an aggregation.
*
* <p>For example, for <code>SUM(x)</code>, this method generates <code>I
* s8; O s8; T; ADD O0, I0;</code>.
*
* @param call The call to the aggregate function to be implemented
* @param accumulatorRegister The accumulator register
* @param translator Calculator code generator
*/
void implementAdd(
RexCall call,
CalcReg accumulatorRegister,
RexToCalcTranslator translator);
/**
* Generates instructions to initialize and add a new value to an
* aggregation. This could call implementInitialize followed by implementAdd
*
* @param call The call to the aggregate function to be implemented
* @param accumulatorRegister The accumulator register
* @param translator Calculator code generator
*/
void implementInitAdd(
RexCall call,
CalcReg accumulatorRegister,
RexToCalcTranslator translator);
/**
* Generates instructions to implement this call, and returns the register
* which holds the result.
*
* <p>For example, for <code>SUM(x)</code>, this method generates <code>I
* s8; O s8; T; SUB O0, I0;</code>
*
* @param call The call to the aggregate function to be implemented.
* @param accumulatorRegister The accumulator register
* @param translator Calculator code generator
*/
void implementDrop(
RexCall call,
CalcReg accumulatorRegister,
RexToCalcTranslator translator);
/**
* Returns whether this implementor can handle the given call.
*
* @param call The call to the aggregate function to be implemented
*/
boolean canImplement(RexCall call);
}
// End CalcRexAggImplementor.java
|
package net.minecraft.client.particle;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ParticleHeart extends Particle
{
float particleScaleOverTime;
protected ParticleHeart(World worldIn, double p_i1211_2_, double p_i1211_4_, double p_i1211_6_, double p_i1211_8_, double p_i1211_10_, double p_i1211_12_)
{
this(worldIn, p_i1211_2_, p_i1211_4_, p_i1211_6_, p_i1211_8_, p_i1211_10_, p_i1211_12_, 2.0F);
}
protected ParticleHeart(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double p_i46354_8_, double p_i46354_10_, double p_i46354_12_, float scale)
{
super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.0D, 0.0D, 0.0D);
this.motionX *= 0.009999999776482582D;
this.motionY *= 0.009999999776482582D;
this.motionZ *= 0.009999999776482582D;
this.motionY += 0.1D;
this.particleScale *= 0.75F;
this.particleScale *= scale;
this.particleScaleOverTime = this.particleScale;
this.particleMaxAge = 16;
this.setParticleTextureIndex(80);
}
/**
* Renders the particle
*/
public void renderParticle(BufferBuilder buffer, Entity entityIn, float partialTicks, float rotationX, float rotationZ, float rotationYZ, float rotationXY, float rotationXZ)
{
float f = ((float)this.particleAge + partialTicks) / (float)this.particleMaxAge * 32.0F;
f = MathHelper.clamp(f, 0.0F, 1.0F);
this.particleScale = this.particleScaleOverTime * f;
super.renderParticle(buffer, entityIn, partialTicks, rotationX, rotationZ, rotationYZ, rotationXY, rotationXZ);
}
public void onUpdate()
{
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
if (this.particleAge++ >= this.particleMaxAge)
{
this.setExpired();
}
this.move(this.motionX, this.motionY, this.motionZ);
if (this.posY == this.prevPosY)
{
this.motionX *= 1.1D;
this.motionZ *= 1.1D;
}
this.motionX *= 0.8600000143051147D;
this.motionY *= 0.8600000143051147D;
this.motionZ *= 0.8600000143051147D;
if (this.onGround)
{
this.motionX *= 0.699999988079071D;
this.motionZ *= 0.699999988079071D;
}
}
@SideOnly(Side.CLIENT)
public static class AngryVillagerFactory implements IParticleFactory
{
public Particle createParticle(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_)
{
Particle particle = new ParticleHeart(worldIn, xCoordIn, yCoordIn + 0.5D, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn);
particle.setParticleTextureIndex(81);
particle.setRBGColorF(1.0F, 1.0F, 1.0F);
return particle;
}
}
@SideOnly(Side.CLIENT)
public static class Factory implements IParticleFactory
{
public Particle createParticle(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_)
{
return new ParticleHeart(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn);
}
}
}
|
package com.classicmodels.jooq.config;
import org.jooq.codegen.GenerationTool;
import org.jooq.meta.jaxb.Configuration;
import org.jooq.meta.jaxb.Database;
import org.jooq.meta.jaxb.Generate;
import org.jooq.meta.jaxb.Generator;
import org.jooq.meta.jaxb.Jdbc;
import org.jooq.meta.jaxb.MatcherRule;
import org.jooq.meta.jaxb.MatcherTransformType;
import org.jooq.meta.jaxb.Matchers;
import org.jooq.meta.jaxb.MatchersTableType;
import org.jooq.meta.jaxb.Strategy;
import org.jooq.meta.jaxb.Target;
public class JooqConfig {
public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration()
.withJdbc(new Jdbc()
.withDriver("com.mysql.cj.jdbc.Driver")
.withUrl("jdbc:mysql://localhost:3306/classicmodels?createDatabaseIfNotExist=true")
.withUser("root")
.withPassword("root"))
.withGenerator(new Generator()
.withName("org.jooq.codegen.KotlinGenerator")
.withDatabase(new Database()
.withName("org.jooq.meta.mysql.MySQLDatabase")
.withInputSchema("classicmodels")
.withIncludes(".*")
.withExcludes("flyway_schema_history | sequences"
+ " | customer_pgs | refresh_top3_product"
+ " | sale_.* | set_.* | get_.* | .*_master")
.withSchemaVersionProvider("SELECT MAX(`version`) FROM `flyway_schema_history`")
.withLogSlowQueriesAfterSeconds(20)
)
.withGenerate(new Generate()
.withDaos(true)
.withValidationAnnotations(Boolean.TRUE)
.withSpringAnnotations(Boolean.TRUE)
.withDeprecationOnUnknownTypes(Boolean.FALSE)
.withPojosAsKotlinDataClasses(Boolean.TRUE)
)
.withStrategy(new Strategy()
.withMatchers(new Matchers()
.withTables(new MatchersTableType()
.withPojoClass(new MatcherRule()
.withExpression("Jooq_$0")
.withTransform(MatcherTransformType.PASCAL))
.withDaoClass(new MatcherRule()
.withExpression("$0_Repository")
.withTransform(MatcherTransformType.PASCAL))))
)
.withTarget(new Target()
.withPackageName("jooq.generated")
.withDirectory(System.getProperty("user.dir").endsWith("webapp")
? "target/generated-sources"
: "webapp/target/generated-sources")));
GenerationTool.generate(configuration);
}
}
|
package rs.ac.bg.matf.oop_p.p1908.poluLenjoPovezivanje;
public class JavaFXBeanMainExample
{
public static void main(String[] args)
{
JavaFXBeanModelExample model = new JavaFXBeanModelExample();
JavaFXBeanViewExample view = new JavaFXBeanViewExample(model);
JavaFXBeanControllerExample controller = new JavaFXBeanControllerExample(
model, view);
controller.incrementIPropertyOnModel();
controller.changeStrPropertyOnModel();
controller.switchColorPropertyOnModel();
controller.incrementIPropertyOnModel();
controller.changeStrPropertyOnModel();
controller.switchColorPropertyOnModel();
}
}
|
package services.applicant;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* Represents a US currency amount.
*
* <p>Accepts various string formats with a required dollars value with no leading 0, unless the
* value is 0.
*
* <p>Optionally:
*
* <ul>
* <li>May contain commas in the dollars: 12,345
* <li>May contain exactly 2 decimal points for cents: 34.56
*/
public class Currency {
// Currency validation regexs. Note: there are frontend versions that need to stay in sync in
// app/assets/javascripts/validation.ts
// Currency containing only numbers, without leading 0s and optional 2 digit cents.
private static final Pattern CURRENCY_NO_COMMAS = Pattern.compile("^[1-9]\\d*(?:\\.\\d\\d)?$");
// Same as CURRENCY_NO_COMMAS but commas followed by 3 digits are allowed.
private static final Pattern CURRENCY_WITH_COMMAS =
Pattern.compile("^[1-9]\\d{0,2}(?:,\\d\\d\\d)*(?:\\.\\d\\d)?$");
// Currency of 0 dollars with optional 2 digit cents.
private static final Pattern CURRENCY_ZERO_DOLLARS = Pattern.compile("^0(?:\\.\\d\\d)?$");
private Long cents = 0L;
/** Constructs a new Currency of the specified cents. */
public Currency(long cents) {
this.cents = cents;
}
/**
* Validates and creates a new Currency based on a dollars and optional cents string. See class
* comment for more on the valid formats.
*/
public static Currency parse(String currency) {
if (!validate(currency)) {
throw new IllegalArgumentException(String.format("Currency is misformatted: %s", currency));
}
try {
double dollars = NumberFormat.getNumberInstance(Locale.US).parse(currency).doubleValue();
Double cents = dollars * 100;
return new Currency(cents.longValue());
} catch (ParseException e) {
throw new IllegalArgumentException(
String.format("Currency is misformatted: %s", currency), e);
}
}
// Returns if the currency string is a valid format.
public static boolean validate(String currency) {
return CURRENCY_NO_COMMAS.matcher(currency).matches()
|| CURRENCY_WITH_COMMAS.matcher(currency).matches()
|| CURRENCY_ZERO_DOLLARS.matcher(currency).matches();
}
public Long getCents() {
return cents;
}
public Double getDollars() {
return cents.doubleValue() / 100.0;
}
/**
* Returns the currency number as a string of numbers. There will always be at least one dollar
* and exactly 2 cents digits.
*/
public String getDollarsString() {
Double dollars = cents.doubleValue() / 100.0;
// 0 is the format for minimal required digits.
DecimalFormat myFormatter = new DecimalFormat("0.00");
return myFormatter.format(dollars);
}
/**
* Returns the currency number as a US formatted human readable string.
*
* <p>The string will always have 2 decimals, and commas, but not a dollar sign.
*/
public String prettyPrint() {
// Format with commas and 2 decimal cents always.
NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
Double dollars = cents.doubleValue() / 100.0;
return formatter.format(dollars);
}
}
|
package tictactoe.game.engine;
public interface GameState {
String value();
}
|
package com.ysyesilyurt.Rest;
import com.ysyesilyurt.Exception.PotentialPlaylistRuntimeException;
import com.ysyesilyurt.Exception.ResourceNotFoundException;
import com.ysyesilyurt.Rest.Response.RestApiResponseBodyBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class RestApiControllerAdvice {
@Autowired
private RestApiResponseBodyBuilder responseBodyBuilder;
@ExceptionHandler(PotentialPlaylistRuntimeException.class)
public ResponseEntity<?> runtimeException(PotentialPlaylistRuntimeException exception) {
log.error(exception.getMessage(), exception);
RestApiResponseBody<Object> responseBody =
this.responseBodyBuilder.errorBody(exception.getMessage());
return new ResponseEntity<>(responseBody, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> notFound(ResourceNotFoundException exception) {
log.error(exception.getMessage());
RestApiResponseBody<Object> responseBody = this.responseBodyBuilder.errorBody(exception.getMessage());
return new ResponseEntity<>(responseBody, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<?> argumentTypeMismatch(MethodArgumentTypeMismatchException exception) {
log.error(exception.getMessage(), exception);
RestApiResponseBody<Object> responseBody = this.responseBodyBuilder.errorBody(exception);
return new ResponseEntity<>(responseBody, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<?> missingParameter(MissingServletRequestParameterException exception) {
log.error(exception.getMessage(), exception);
RestApiResponseBody<Object> responseBody = this.responseBodyBuilder.errorBody(exception);
return new ResponseEntity<>(responseBody, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<?> unknownException(Exception exception) {
log.error(exception.getMessage(), exception);
RestApiResponseBody<Object> responseBody = this.responseBodyBuilder.errorBody(exception.getMessage());
return new ResponseEntity<>(responseBody, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
package controladores;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class consultarSala
*/
@WebServlet("/consultarSala")
public class ConsultarSala extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ConsultarSala() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
/*
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.svg.css.impl;
import com.itextpdf.svg.SvgConstants;
import com.itextpdf.svg.renderers.ISvgNodeRenderer;
import com.itextpdf.svg.renderers.impl.AbstractBranchSvgNodeRenderer;
import java.util.HashMap;
import java.util.Map;
/**
* Style and attribute inheritance resolver for {@link ISvgNodeRenderer} objects
*/
public class SvgNodeRendererInheritanceResolver {
private StyleResolverUtil sru;
public SvgNodeRendererInheritanceResolver(){
sru = new StyleResolverUtil();
}
/**
* Apply style and attribute inheritance to the tree formed by the root and the subTree
* @param root Renderer to consider as the root of the substree
* @param subTree tree of {@link ISvgNodeRenderer}s
*/
public void applyInheritanceToSubTree(ISvgNodeRenderer root, ISvgNodeRenderer subTree){
//Merge inherited style declarations from parent into child
applyStyles(root,subTree);
//If subtree, iterate over tree
if(subTree instanceof AbstractBranchSvgNodeRenderer) {
AbstractBranchSvgNodeRenderer subTreeAsBranch = (AbstractBranchSvgNodeRenderer) subTree;
for (ISvgNodeRenderer child : subTreeAsBranch.getChildren()) {
applyInheritanceToSubTree(subTreeAsBranch,child);
}
}
}
protected void applyStyles(ISvgNodeRenderer parent, ISvgNodeRenderer child){
if(parent != null && child != null) {
Map<String, String> childStyles = child.getAttributeMapCopy();
if(childStyles == null){
childStyles = new HashMap<String,String>();
}
Map<String, String> parentStyles = parent.getAttributeMapCopy();
String parentFontSize = parent.getAttribute(SvgConstants.Attributes.FONT_SIZE);
if(parentFontSize == null){
parentFontSize = "0";
}
for (Map.Entry<String, String> parentAttribute : parentStyles.entrySet()) {
sru.mergeParentStyleDeclaration(childStyles, parentAttribute.getKey(), parentAttribute.getValue(), parentFontSize);
}
child.setAttributesAndStyles(childStyles);
}
}
}
|
import java.util.Stack;
public class LowerCase {
public static String toLowerCase(String str) {
Stack<Character> stack = new Stack<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) >= 65 && str.charAt(i) <= 90) {
char ch = (char) (str.charAt(i) + 32);
stack.push(ch);
continue;
}
stack.push(str.charAt(i));
}
stack = reverse(stack);
while(!stack.isEmpty()) {
stringBuilder.append(stack.pop());
}
return stringBuilder.toString();
}
public static <T extends Comparable<? super T>> Stack<T> reverse(Stack<T> stacky) {
Stack<T> temp = new Stack<>();
while(!stacky.isEmpty()) {
temp.push(stacky.pop());
}
return temp;
}
}
|
/*
* 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.eventmesh.connector.rocketmq.cloudevent.impl;
import java.util.Map;
import io.cloudevents.core.message.impl.MessageUtils;
import io.cloudevents.core.v1.CloudEventV1;
public class RocketMQHeaders {
public static final String CE_PREFIX = "CE_";
protected static final Map<String, String> ATTRIBUTES_TO_HEADERS =
MessageUtils.generateAttributesToHeadersMapping(v -> v);
public static final String CONTENT_TYPE =
ATTRIBUTES_TO_HEADERS.get(CloudEventV1.DATACONTENTTYPE);
public static final String SPEC_VERSION = ATTRIBUTES_TO_HEADERS.get(CloudEventV1.SPECVERSION);
}
|
import java.util.ArrayList;
public class Deck extends Stack{
private ArrayList<Card> deck;
Deck(){
deck = new ArrayList<>();
}
public ArrayList<Card> getDeck() {
return deck;
}
public void addCardToDeck(Card card){
deck.add(card);
}
//take a card from the deck if you loose the round
public Card drawCardFromDeck(){
Card card = deck.get(0);
deck.remove(0);
return card;
}
//take the card to fight against your opponent
public Card pickCardFromDeck(int pos){
Card card = deck.get(pos);
return card;
}
public int deckSize(){
return deck.size();
}
}
|
package com.cxxy.eta8.model;
import com.cxxy.eta8.model.base.BaseSysUrlRole;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class SysUrlRole extends BaseSysUrlRole<SysUrlRole> {
public static final SysUrlRole dao = new SysUrlRole().dao();
}
|
/*
For step-by-step instructions on connecting your Android application to this backend module,
see "App Engine Java Endpoints Module" template documentation at
https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints
*/
package com.udacity.gradle.backend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.udacity.gradle.jokeprovider.JokeProvider;
import java.util.Random;
/** An endpoint class we are exposing */
@Api(
name = "jokeApi",
version = "v1",
namespace = @ApiNamespace(
ownerDomain = "backend.gradle.udacity.com",
ownerName = "backend.gradle.udacity.com",
packagePath=""
)
)
public class JokesEndpoint {
/** A simple endpoint method that returns a random joke */
@ApiMethod(name = "getJoke")
public JokeBean getJoke() {
JokeBean response = new JokeBean();
Random randomNum = new Random();
int randomJoke = randomNum.nextInt(JokeProvider.getInstance().getNumberOfJokes());
String joke = JokeProvider.getInstance().getJoke(randomJoke);
response.setJoke(joke != null ? joke : "");
return response;
}
}
|
/*
* Copyright 2012, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.times.location;
import java.io.IOException;
/**
* Location exception.
*
* @author Moshe Waisberg
*/
public class LocationException extends IOException {
public LocationException() {
}
public LocationException(String message) {
super(message);
}
public LocationException(String message, Throwable cause) {
super(message, cause);
}
public LocationException(Throwable cause) {
super(cause);
}
}
|
package com.rodrigofujioka.dev.web.repository;
import com.rodrigofujioka.dev.web.domain.Disciplina;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestEntityManager
@Transactional
public class DisciplinaRepositoryTest {
@Autowired
private EntityManager entityManager;
@Autowired
private DisciplinaRepository disciplinaRepository;
@Test
public void whenFindByProfessorJoao_thenReturnDisciplinaPortugues() {
// given
Disciplina portugues = new Disciplina("portugues", "Joao");
entityManager.persist(portugues);
entityManager.flush();
// when
Disciplina found =
disciplinaRepository.findDisciplinaByProfessor("Joao").get(0);
// then
assertThat(found.getNome(), equalTo(portugues.getNome()));
}
@Test
public void whenFindByProfessorMila_thenReturnDisciplina() {
String prof = "Mila";
// given
Disciplina ginastica1 = new Disciplina("Bases Fisiologicas", prof);
Disciplina ginastica2 = new Disciplina("Educaçao Fisica", prof);
Disciplina anatomia = new Disciplina("Anatomia Humana", prof);
entityManager.persist(ginastica1);
entityManager.persist(ginastica2);
entityManager.persist(anatomia);
entityManager.flush();
// when
List<Disciplina> disciplinas =
disciplinaRepository
.findDisciplinaByProfessor(prof);
// then
assertThat(disciplinas.size(), equalTo(3));
//assertThat(disciplinas.stream().map(d -> d.getProfessor()).collect(Collectors.toList()),
// containsInAnyOrder(prof));
}
@Test
public void whenFindByAnoDisciplinaBetween_thenReturnDuasDisciplina() {
//findDisciplinaByAnoDisciplinaBetween
String prof = "Bozena";
// given
Disciplina ginastica1 = new Disciplina("Bases Fisiologicas", prof, 2020);
Disciplina ginastica2 = new Disciplina("Educaçao Fisica", prof, 2019);
Disciplina anatomia = new Disciplina("Anatomia Humana", prof, 2018);
entityManager.persist(ginastica1);
entityManager.persist(ginastica2);
entityManager.persist(anatomia);
entityManager.flush();
// when
List<Disciplina> disciplinas =
disciplinaRepository
.findDisciplinaByAnoDisciplinaBetween(1991,2019);
// then
assertThat(disciplinas.size(), equalTo(2));
//assertThat(disciplinas.stream().map(d -> d.getProfessor()).collect(Collectors.toList()),
// containsInAnyOrder(prof));
}
@Test
public void whenFindByNomeAndProfessor_thenReturnDisciplina() {
// given
Disciplina matematica1 = new Disciplina("geometria", "Suely");
Disciplina matematica2 = new Disciplina("trigonometria", "Andrea");
entityManager.persist(matematica1);
entityManager.persist(matematica2);
entityManager.flush();
// when
List<Disciplina> disciplinas =
disciplinaRepository
.findDisciplinaByNomeAndProfessor("geometria","Suely");
Disciplina found =
disciplinas.stream()
.filter(d -> d.getProfessor().equalsIgnoreCase("Suely"))
.collect(Collectors.toList())
.get(0);
// then
assertThat(found.getNome(), equalTo(matematica1.getNome()));
}
}
|
/**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.util.timeseries.fudge;
import org.fudgemsg.mapping.FudgeBuilderFor;
import com.opengamma.util.timeseries.DateTimeConverter;
import com.opengamma.util.timeseries.fast.FastTimeSeries;
import com.opengamma.util.timeseries.fast.longint.FastLongDoubleTimeSeries;
import com.opengamma.util.timeseries.yearoffset.ArrayYearOffsetDoubleTimeSeries;
/**
* Fudge message encoder/decoder (builder) for ArrayYearOffsetDoubleTimeSeries
*/
@FudgeBuilderFor(ArrayYearOffsetDoubleTimeSeries.class)
public class ArrayYearOffsetDoubleTimeSeriesFudgeBuilder extends FastBackedDoubleTimeSeriesFudgeBuilder<Double, ArrayYearOffsetDoubleTimeSeries> {
@Override
public ArrayYearOffsetDoubleTimeSeries makeSeries(DateTimeConverter<Double> converter, FastTimeSeries<?> dts) {
return new ArrayYearOffsetDoubleTimeSeries(converter, (FastLongDoubleTimeSeries) dts);
}
}
|
/**
*
*/
package com.example.rest.security;
import static com.example.util.Constant.AUTH_HEADER;
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.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import com.example.util.Constant;
import com.example.util.JwtToken;
/**
* @author mindfire
*
*/
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Autowired
private JwtToken jwtToken;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, AuthenticationException{
HttpServletResponse resp = (HttpServletResponse) response;
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
resp.setHeader("Access-Control-Max-Age", "3600");
resp.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, " + AUTH_HEADER);
HttpServletRequest httpRequest = (HttpServletRequest) request;
// Get the header value from the request
String authToken = httpRequest.getHeader(Constant.AUTH_HEADER);
// Get the username from the token if exists
String username = this.jwtToken.getUsernameFromToken(authToken);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (this.jwtToken.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
}
|
package com.example.lambda;
import java.time.LocalDate;
import java.util.List;
import java.util.function.Supplier;
/**
*
* @author oracle
*/
public class SupplierTest {
public static void main(String[] args) {
List<Employee> eList = Employee.createShortList();
Employee first = eList.get(0);
Supplier<Employee> eSupp; // Write your Supplier lambda here
System.out.println("=== Print employee list before");
eList.stream().forEach(Employee::printSummary);
// Add new employee here
System.out.println("\n=== Print employee list after");
eList.stream().forEach(Employee::printSummary);
}
}
|
package com.cannolicatfish.rankine.util.elements;
import com.cannolicatfish.rankine.util.PeriodicTableUtils;
import net.minecraft.enchantment.Enchantment;
public class PlatinumElement implements ElementInterface{
@Override
public PeriodicTableUtils.Element getReference() {
return PeriodicTableUtils.Element.PLATINUM;
}
@Override
public int getDurabilityFromPercent(int x) {
if (x >= 80)
{
return (int) Math.round(Math.pow(2,x/10f - 4) - 10);
}
return 0;
}
@Override
public float getDamageFromPercent(int x) {
return 0;
}
@Override
public float getAttackSpeedFromPercent(int x) {
return 0;
}
@Override
public float getMiningSpeedFromPercent(int x) {
return x/20f * 3/2f;
}
@Override
public int getMiningLevelFromPercent(int x) {
return 0;
}
@Override
public int getEnchantabilityFromPercent(int x) {
if (x >= 50)
{
return Math.round(3 * x/10f + 10);
} else
{
return Math.round(x/2f);
}
}
@Override
public float getCorrResistFromPercent(int x) {
return x/100f;
}
@Override
public float getHeatResistFromPercent(int x) {
return 0;
}
@Override
public float getToughnessFromPercent(int x) {
return 0;
}
@Override
public float getElectrodePotentialFromPercent(int x) {
return 1.188f;
}
@Override
public Enchantment getEnchantments(int x) {
return null;
}
}
|
// Copyright 2016 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.windows;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.windows.WindowsFileSystem.SHORT_NAME_MATCHER;
import static org.junit.Assert.fail;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Symlinks;
import com.google.devtools.build.lib.windows.WindowsFileSystem.WindowsPath;
import com.google.devtools.build.lib.windows.jni.WindowsFileOperations;
import com.google.devtools.build.lib.windows.util.WindowsTestUtil;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link WindowsFileSystem}. */
@RunWith(JUnit4.class)
@TestSpec(localOnly = true, supportedOs = OS.WINDOWS)
public class WindowsFileSystemTest {
private String scratchRoot;
private WindowsTestUtil testUtil;
private WindowsFileSystem fs;
@Before
public void loadJni() throws Exception {
scratchRoot = new File(System.getenv("TEST_TMPDIR")).getAbsolutePath() + "/x";
testUtil = new WindowsTestUtil(scratchRoot);
fs = new WindowsFileSystem();
cleanupScratchDir();
}
@After
public void cleanupScratchDir() throws Exception {
testUtil.deleteAllUnder("");
}
@Test
public void testShortNameMatcher() {
assertThat(SHORT_NAME_MATCHER.apply("abc")).isFalse(); // no ~ in the name
assertThat(SHORT_NAME_MATCHER.apply("abc~")).isFalse(); // no number after the ~
assertThat(SHORT_NAME_MATCHER.apply("~abc")).isFalse(); // no ~ followed by number
assertThat(SHORT_NAME_MATCHER.apply("too_long_path")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("too_long_path~1")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("abcd~1234")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("h~1")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("h~12")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("h~12.")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("h~12.a")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("h~12.abc")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("h~123456")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hellow~1")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hellow~1.")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hellow~1.a")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hellow~1.abc")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hello~1.abcd")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("hellow~1.abcd")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("hello~12")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hello~12.")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hello~12.a")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hello~12.abc")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("hello~12.abcd")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("hellow~12")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("hellow~12.")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("hellow~12.a")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("hellow~12.ab")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("~h~1")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~1.")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~1.a")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~1.abc")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~1.abcd")).isFalse(); // too long for 8dot3
assertThat(SHORT_NAME_MATCHER.apply("~h~12")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~12~1")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~12~1.")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~12~1.a")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~12~1.abc")).isTrue();
assertThat(SHORT_NAME_MATCHER.apply("~h~12~1.abcd")).isFalse(); // too long for 8dot3
}
@Test
public void testCanWorkWithJunctionSymlinks() throws Exception {
testUtil.scratchFile("dir\\hello.txt", "hello");
testUtil.scratchDir("non_existent");
testUtil.createJunctions(ImmutableMap.of("junc", "dir", "junc_bad", "non_existent"));
Path juncPath = testUtil.createVfsPath(fs, "junc");
Path dirPath = testUtil.createVfsPath(fs, "dir");
Path juncBadPath = testUtil.createVfsPath(fs, "junc_bad");
Path nonExistentPath = testUtil.createVfsPath(fs, "non_existent");
// Test junction creation.
assertThat(juncPath.exists(Symlinks.NOFOLLOW)).isTrue();
assertThat(dirPath.exists(Symlinks.NOFOLLOW)).isTrue();
assertThat(juncBadPath.exists(Symlinks.NOFOLLOW)).isTrue();
assertThat(nonExistentPath.exists(Symlinks.NOFOLLOW)).isTrue();
// Test recognizing and dereferencing a directory junction.
assertThat(juncPath.isSymbolicLink()).isTrue();
assertThat(juncPath.isDirectory(Symlinks.FOLLOW)).isTrue();
assertThat(juncPath.isDirectory(Symlinks.NOFOLLOW)).isFalse();
assertThat(juncPath.getDirectoryEntries())
.containsExactly(testUtil.createVfsPath(fs, "junc\\hello.txt"));
// Test deleting a directory junction.
assertThat(juncPath.delete()).isTrue();
assertThat(juncPath.exists(Symlinks.NOFOLLOW)).isFalse();
// Test recognizing a dangling directory junction.
assertThat(nonExistentPath.delete()).isTrue();
assertThat(nonExistentPath.exists(Symlinks.NOFOLLOW)).isFalse();
assertThat(juncBadPath.exists(Symlinks.NOFOLLOW)).isTrue();
// TODO(bazel-team): fix https://github.com/bazelbuild/bazel/issues/1690 and uncomment the
// assertion below.
//assertThat(fs.isSymbolicLink(juncBadPath)).isTrue();
assertThat(fs.isDirectory(juncBadPath, /* followSymlinks */ true)).isFalse();
assertThat(fs.isDirectory(juncBadPath, /* followSymlinks */ false)).isFalse();
// Test deleting a dangling junction.
assertThat(juncBadPath.delete()).isTrue();
assertThat(juncBadPath.exists(Symlinks.NOFOLLOW)).isFalse();
}
@Test
public void testMockJunctionCreation() throws Exception {
String root = testUtil.scratchDir("dir").getParent().toString();
testUtil.scratchFile("dir/file.txt", "hello");
testUtil.createJunctions(ImmutableMap.of("junc", "dir"));
String[] children = new File(root + "/junc").list();
assertThat(children).isNotNull();
assertThat(children).hasLength(1);
assertThat(Arrays.asList(children)).containsExactly("file.txt");
}
@Test
public void testIsJunction() throws Exception {
final Map<String, String> junctions = new HashMap<>();
junctions.put("shrtpath/a", "shrttrgt");
junctions.put("shrtpath/b", "longtargetpath");
junctions.put("shrtpath/c", "longta~1");
junctions.put("longlinkpath/a", "shrttrgt");
junctions.put("longlinkpath/b", "longtargetpath");
junctions.put("longlinkpath/c", "longta~1");
junctions.put("abbrev~1/a", "shrttrgt");
junctions.put("abbrev~1/b", "longtargetpath");
junctions.put("abbrev~1/c", "longta~1");
String root = testUtil.scratchDir("shrtpath").getParent().toAbsolutePath().toString();
testUtil.scratchDir("longlinkpath");
testUtil.scratchDir("abbreviated");
testUtil.scratchDir("control/a");
testUtil.scratchDir("control/b");
testUtil.scratchDir("control/c");
testUtil.scratchFile("shrttrgt/file1.txt", "hello");
testUtil.scratchFile("longtargetpath/file2.txt", "hello");
testUtil.createJunctions(junctions);
assertThat(WindowsFileSystem.isJunction(new File(root, "shrtpath/a"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "shrtpath/b"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "shrtpath/c"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "longlinkpath/a"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "longlinkpath/b"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "longlinkpath/c"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "longli~1/a"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "longli~1/b"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "longli~1/c"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "abbreviated/a"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "abbreviated/b"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "abbreviated/c"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "abbrev~1/a"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "abbrev~1/b"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "abbrev~1/c"))).isTrue();
assertThat(WindowsFileSystem.isJunction(new File(root, "control/a"))).isFalse();
assertThat(WindowsFileSystem.isJunction(new File(root, "control/b"))).isFalse();
assertThat(WindowsFileSystem.isJunction(new File(root, "control/c"))).isFalse();
assertThat(WindowsFileSystem.isJunction(new File(root, "shrttrgt/file1.txt")))
.isFalse();
assertThat(WindowsFileSystem.isJunction(new File(root, "longtargetpath/file2.txt")))
.isFalse();
assertThat(WindowsFileSystem.isJunction(new File(root, "longta~1/file2.txt")))
.isFalse();
try {
WindowsFileSystem.isJunction(new File(root, "non-existent"));
fail("expected failure");
} catch (IOException e) {
assertThat(e.getMessage()).contains("cannot find");
}
assertThat(Arrays.asList(new File(root + "/shrtpath/a").list())).containsExactly("file1.txt");
assertThat(Arrays.asList(new File(root + "/shrtpath/b").list())).containsExactly("file2.txt");
assertThat(Arrays.asList(new File(root + "/shrtpath/c").list())).containsExactly("file2.txt");
assertThat(Arrays.asList(new File(root + "/longlinkpath/a").list()))
.containsExactly("file1.txt");
assertThat(Arrays.asList(new File(root + "/longlinkpath/b").list()))
.containsExactly("file2.txt");
assertThat(Arrays.asList(new File(root + "/longlinkpath/c").list()))
.containsExactly("file2.txt");
assertThat(Arrays.asList(new File(root + "/abbreviated/a").list()))
.containsExactly("file1.txt");
assertThat(Arrays.asList(new File(root + "/abbreviated/b").list()))
.containsExactly("file2.txt");
assertThat(Arrays.asList(new File(root + "/abbreviated/c").list()))
.containsExactly("file2.txt");
}
@Test
public void testIsJunctionIsTrueForDanglingJunction() throws Exception {
java.nio.file.Path helloPath = testUtil.scratchFile("target\\hello.txt", "hello");
testUtil.createJunctions(ImmutableMap.of("link", "target"));
File linkPath = new File(helloPath.getParent().getParent().toFile(), "link");
assertThat(Arrays.asList(linkPath.list())).containsExactly("hello.txt");
assertThat(WindowsFileSystem.isJunction(linkPath)).isTrue();
assertThat(helloPath.toFile().delete()).isTrue();
assertThat(helloPath.getParent().toFile().delete()).isTrue();
assertThat(helloPath.getParent().toFile().exists()).isFalse();
assertThat(Arrays.asList(linkPath.getParentFile().list())).containsExactly("link");
assertThat(WindowsFileSystem.isJunction(linkPath)).isTrue();
assertThat(
Files.exists(
linkPath.toPath(), WindowsFileSystem.symlinkOpts(/* followSymlinks */ false)))
.isTrue();
assertThat(
Files.exists(
linkPath.toPath(), WindowsFileSystem.symlinkOpts(/* followSymlinks */ true)))
.isFalse();
}
@Test
public void testIsJunctionHandlesFilesystemChangesCorrectly() throws Exception {
File longPath =
testUtil.scratchFile("target\\helloworld.txt", "hello").toAbsolutePath().toFile();
File shortPath = new File(longPath.getParentFile(), "hellow~1.txt");
assertThat(WindowsFileSystem.isJunction(longPath)).isFalse();
assertThat(WindowsFileSystem.isJunction(shortPath)).isFalse();
assertThat(longPath.delete()).isTrue();
testUtil.createJunctions(ImmutableMap.of("target\\helloworld.txt", "target"));
assertThat(WindowsFileSystem.isJunction(longPath)).isTrue();
assertThat(WindowsFileSystem.isJunction(shortPath)).isTrue();
assertThat(longPath.delete()).isTrue();
assertThat(longPath.mkdir()).isTrue();
assertThat(WindowsFileSystem.isJunction(longPath)).isFalse();
assertThat(WindowsFileSystem.isJunction(shortPath)).isFalse();
}
@Test
public void testShortPathResolution() throws Exception {
String shortPath = "shortp~1.res/foo/withsp~1/bar/~witht~1/hello.txt";
String longPath = "shortpath.resolution/foo/with spaces/bar/~with tilde/hello.txt";
testUtil.scratchFile(longPath, "hello");
Path p = fs.getPath(scratchRoot).getRelative(shortPath);
assertThat(p.getPathString()).endsWith(longPath);
assertThat(p).isEqualTo(fs.getPath(scratchRoot).getRelative(shortPath));
assertThat(p).isEqualTo(fs.getPath(scratchRoot).getRelative(longPath));
assertThat(fs.getPath(scratchRoot).getRelative(shortPath)).isSameAs(p);
assertThat(fs.getPath(scratchRoot).getRelative(longPath)).isSameAs(p);
}
@Test
public void testUnresolvableShortPathWhichIsThenCreated() throws Exception {
String shortPath = "unreso~1.sho/foo/will~1.exi/bar/hello.txt";
String longPrefix = "unresolvable.shortpath/foo/";
String longPath = longPrefix + "will.exist/bar/hello.txt";
testUtil.scratchDir(longPrefix);
final WindowsPath foo = (WindowsPath) fs.getPath(scratchRoot).getRelative(longPrefix);
// Assert that we can create an unresolvable path.
Path p = fs.getPath(scratchRoot).getRelative(shortPath);
assertThat(p.getPathString()).endsWith(longPrefix + "will~1.exi/bar/hello.txt");
// Assert that said path is not cached in its parent's `children` cache.
final List<String> children = new ArrayList<>();
Predicate<Path> collector =
new Predicate<Path>() {
@Override
public boolean apply(Path child) {
children.add(child.relativeTo(foo).getPathString());
return true;
}
};
foo.applyToChildren(collector);
assertThat(children).isEmpty();
// Assert that we can then create the whole path, and can now resolve the short form.
testUtil.scratchFile(longPath, "hello");
Path q = fs.getPath(scratchRoot).getRelative(shortPath);
assertThat(q.getPathString()).endsWith(longPath);
// Assert however that the unresolved and resolved Path objects are different, and only the
// resolved one is cached.
assertThat(p).isNotEqualTo(q);
foo.applyToChildren(collector);
assertThat(children).containsExactly("will.exist");
}
/**
* Test the scenario when a short path resolves to different long ones over time.
*
* <p>This can happen if the user deletes a directory during the bazel server's lifetime, then
* recreates it with the same name prefix such that the resulting directory's 8dot3 name is the
* same as the old one's.
*/
@Test
public void testShortPathResolvesToDifferentPathsOverTime() throws Exception {
Path p1 = fs.getPath(scratchRoot).getRelative("longpa~1");
Path p2 = fs.getPath(scratchRoot).getRelative("longpa~1");
assertThat(p1.exists()).isFalse();
assertThat(p1).isEqualTo(p2);
assertThat(p1).isNotSameAs(p2);
testUtil.scratchDir("longpathnow");
Path q1 = fs.getPath(scratchRoot).getRelative("longpa~1");
Path q2 = fs.getPath(scratchRoot).getRelative("longpa~1");
assertThat(q1.exists()).isTrue();
assertThat(q1).isEqualTo(q2);
// Assert q1 == q2, because we could successfully resolve the short path to a long name and we
// cache them by the long name, so it's irrelevant they were created from a 8dot3 name, or what
// that name resolves to later in time.
assertThat(q1).isSameAs(q2);
assertThat(q1).isSameAs(fs.getPath(scratchRoot).getRelative("longpathnow"));
// Delete the original resolution of "longpa~1" ("longpathnow").
assertThat(q1.delete()).isTrue();
assertThat(q1.exists()).isFalse();
// Create a directory whose 8dot3 name is also "longpa~1" but its long name is different.
testUtil.scratchDir("longpaththen");
Path r1 = fs.getPath(scratchRoot).getRelative("longpa~1");
Path r2 = fs.getPath(scratchRoot).getRelative("longpa~1");
assertThat(r1.exists()).isTrue();
assertThat(r1).isEqualTo(r2);
assertThat(r1).isSameAs(r2);
assertThat(r1).isSameAs(fs.getPath(scratchRoot).getRelative("longpaththen"));
// r1 == r2 and q1 == q2, but r1 != q1, because the resolution of "longpa~1" changed over time.
assertThat(r1).isNotEqualTo(q1);
assertThat(r1).isNotSameAs(q1);
}
@Test
public void testCreateSymbolicLink() throws Exception {
// Create the `scratchRoot` directory.
assertThat(fs.getPath(scratchRoot).createDirectory()).isTrue();
// Create symlink with directory target, relative path.
Path link1 = fs.getPath(scratchRoot).getRelative("link1");
fs.createSymbolicLink(link1, PathFragment.create(".."));
// Create symlink with directory target, absolute path.
Path link2 = fs.getPath(scratchRoot).getRelative("link2");
fs.createSymbolicLink(link2, fs.getPath(scratchRoot).getRelative("link1").asFragment());
// Create scratch files that'll be symlink targets.
testUtil.scratchFile("foo.txt", "hello");
testUtil.scratchFile("bar.txt", "hello");
// Create symlink with file target, relative path.
Path link3 = fs.getPath(scratchRoot).getRelative("link3");
fs.createSymbolicLink(link3, PathFragment.create("foo.txt"));
// Create symlink with file target, absolute path.
Path link4 = fs.getPath(scratchRoot).getRelative("link4");
fs.createSymbolicLink(link4, fs.getPath(scratchRoot).getRelative("bar.txt").asFragment());
// Assert that link1 and link2 are true junctions and have the right contents.
for (Path p : ImmutableList.of(link1, link2)) {
assertThat(WindowsFileOperations.isJunction(p.getPathString())).isTrue();
assertThat(p.isSymbolicLink()).isTrue();
assertThat(
Iterables.transform(
Arrays.asList(new File(p.getPathString()).listFiles()),
new Function<File, String>() {
@Override
public String apply(File input) {
return input.getName();
}
}))
.containsExactly("x");
}
// Assert that link3 and link4 are copies of files.
for (Path p : ImmutableList.of(link3, link4)) {
assertThat(WindowsFileOperations.isJunction(p.getPathString())).isFalse();
assertThat(p.isSymbolicLink()).isFalse();
assertThat(p.isFile()).isTrue();
}
}
}
|
package com.example.instagramclone.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.instagramclone.Post;
import com.example.instagramclone.PostsAdapter;
import com.example.instagramclone.R;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
import static com.example.instagramclone.Post.KEY_CREATED_KEY;
/**
* A simple {@link Fragment} subclass.
* *
* *
*/
public class PostsFragment extends Fragment {
public static final String TAG = "PostsFragment";
private RecyclerView rvPosts;
protected PostsAdapter adapter;
protected List<Post> allPosts;
private SwipeRefreshLayout swipeContainer;
public PostsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_posts, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
rvPosts = view.findViewById(R.id.rvPosts);
allPosts = new ArrayList<>();
adapter = new PostsAdapter(getContext(), allPosts);
// Steps to use the recycler view:
// 0. create layout for one row in the list
// 1. create tje adaptor
// 2. create the data source
// 3. set the adaptor on the recycler view
rvPosts.setAdapter(adapter);
// 4. set the layout manger on the recycler view
rvPosts.setLayoutManager(new LinearLayoutManager(getContext()));
queryPosts();
swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
allPosts = new ArrayList<>();
adapter = new PostsAdapter(getContext(), allPosts);
rvPosts.setAdapter(adapter);
rvPosts.setLayoutManager(new LinearLayoutManager(getContext()));
queryPosts();
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
protected void queryPosts() {
ParseQuery<Post> query = ParseQuery.getQuery(Post.class);
query.include(Post.KEY_USER);
query.setLimit(20);
query.addDescendingOrder(KEY_CREATED_KEY);
query.findInBackground(new FindCallback<Post>() {
@Override
public void done(List<Post> posts, ParseException e) {
if (e != null){
Log.e(TAG, "Issue with getting posts", e);
return;
}
for (Post post : posts){
Log.i(TAG, "Post: " + post.getDescription() + ", username: " + post.getUser());
}
allPosts.addAll(posts);
adapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
}
});
}
}
|
package src.assignment.entity;
import java.util.*;
import java.lang.*;
public interface InterfaceScore {
public int getScore();
public void setScore(int score);
public void incrementScore();
}
|
package fundamentals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class FlipListSides {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String firstNumsInput = scan.nextLine();
String[] firstNumsInputToArr = firstNumsInput.split(" ");
List<Integer> firstNums = new ArrayList<Integer>();
for (int i = 0; i < firstNumsInputToArr.length; i++) {
firstNums.add(Integer.parseInt(firstNumsInputToArr[i]));
}
if (firstNums.size() % 2 == 0) {
int limit = firstNums.size() / 2;
for (int i = 1; i < limit; i++) {
Collections.swap(firstNums, i, (firstNums.size() - 1) - i);
}
} else {
int middleElement = (firstNums.size() - 1) / 2;
for (int i = 1; i < middleElement; i++) {
Collections.swap(firstNums, i, (firstNums.size() - 1) - i);
}
}
// Collections.swap(firstNums, 0, 5);
// Collections.swap(firstNums, 3, 4);
for (int el : firstNums) {
System.out.print(el + " ");
}
}
}
|
// Copyright (c) 2002 Graz University of Technology. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. The end-user documentation included with the redistribution, if any, must
// include the following acknowledgment:
//
// "This product includes software developed by IAIK of Graz University of
// Technology."
//
// Alternately, this acknowledgment may appear in the software itself, if and
// wherever such third-party acknowledgments normally appear.
//
// 4. The names "Graz University of Technology" and "IAIK of Graz University of
// Technology" must not be used to endorse or promote products derived from this
// software without prior written permission.
//
// 5. Products derived from this software may not be called "IAIK PKCS Wrapper",
// nor may "IAIK" appear in their name, without prior written permission of
// Graz University of Technology.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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 LICENSOR 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 demo.pkcs.pkcs11.wrapper.maintenance;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import iaik.pkcs.pkcs11.Info;
import iaik.pkcs.pkcs11.InitializeArgs;
import iaik.pkcs.pkcs11.Module;
import iaik.pkcs.pkcs11.MutexHandler;
import iaik.pkcs.pkcs11.TokenException;
/**
* This demo program tries to call initialize with some arguments.
*/
public class InitArgs implements InitializeArgs {
static PrintWriter output_;
static {
try {
// output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
output_ = new PrintWriter(System.out, true);
} catch (Throwable thr) {
thr.printStackTrace();
output_ = new PrintWriter(System.out, true);
}
}
public static void main(String[] args) throws TokenException, IOException {
if ((args.length == 1) || (args.length == 2)) {
output_
.println("################################################################################");
output_.println("load and initialize module \"" + args[0]
+ "\" using InitializeArgs");
output_.flush();
Module pkcs11Module = Module.getInstance(args[0]);
byte[] reservedParameter = (args.length >= 2) ? readStream(new FileInputStream(
args[1])) : null;
InitializeArgs initArgs = new InitArgs(reservedParameter);
pkcs11Module.initialize(initArgs);
Info info = pkcs11Module.getInfo();
output_.println(info);
output_
.println("################################################################################");
} else {
printUsage();
}
System.gc(); // to finalize and disconnect the pkcs11Module
}
protected static void printUsage() {
output_
.println("InitArgs <PKCS#11 module name> [<file providing reserved parameter>]");
output_.println("e.g.: InitArgs slbck.dll");
}
/**
* Read the contents of the stream into a byte array. The stream is read until it returns EOF.
*/
protected static byte[] readStream(InputStream in) throws IOException {
ByteArrayOutputStream bufferStream = new ByteArrayOutputStream(256); // initial size
int bytesRead;
byte[] buffer = new byte[256];
while ((bytesRead = in.read(buffer)) >= 0) {
bufferStream.write(buffer, 0, bytesRead);
}
return bufferStream.toByteArray();
}
protected byte[] reservedParameter_;
public InitArgs(byte[] reservedParameter) {
reservedParameter_ = reservedParameter;
}
/**
* Get the handler object that handes mutex objects.
*
* @return The mutex handler object or null, if there is none set.
*/
public MutexHandler getMutexHandler() {
output_.println("getMutexHandler() called");
return null;
}
/**
* Checks, if the library is not allowed to create operating system threads.
*
* @return True, if the library is not allowed to create operating system threads; false,
* otherwise.
*/
public boolean isLibraryCantCreateOsThreads() {
output_.println("isLibraryCantCreateOsThreads() called");
return false;
}
/**
* Checks, if the library is allowed to use locking mechanisms of the operating system.
*
* @return True, if the library is allowed to use locking mechanisms of the operating system.
*/
public boolean isOsLockingOk() {
output_.println("isOsLockingOk() called");
return true;
}
/**
* Get the reserved parameter. This is always null as of version 2.11 of PKCS#11.
*
* @return null as of version 2.11 of PKCS#11.
*
* @postconditions (result == null)
*/
public java.lang.Object getReserved() {
output_.println("getReserved() called");
return reservedParameter_;
}
}
|
package ui.models;
import javafx.beans.property.*;
public class StudentWithAVG implements Comparable<StudentWithAVG> {
private IntegerProperty id;
private ObjectProperty<Diploma> diploma;
private SimpleDoubleProperty avg;
private LongProperty numberOfFive;
private LongProperty numberOfFour;
private LongProperty numberOfThree;
private LongProperty numberOfEducationalComponent;
public StudentWithAVG() {
this.id = new SimpleIntegerProperty();
this.diploma = new SimpleObjectProperty<>();
this.avg = new SimpleDoubleProperty();
this.numberOfFive = new SimpleLongProperty();
this.numberOfFour = new SimpleLongProperty();
this.numberOfThree = new SimpleLongProperty();
this.numberOfEducationalComponent = new SimpleLongProperty();
}
public StudentWithAVG(Diploma diploma, double avg, long numberOfFive, long numberOfFour, long numberOfThree,
long numberOfEducationalComponent) {
this.id = new SimpleIntegerProperty();
this.diploma = new SimpleObjectProperty<>(diploma);
this.avg = new SimpleDoubleProperty(avg);
this.numberOfFive = new SimpleLongProperty(numberOfFive);
this.numberOfFour = new SimpleLongProperty(numberOfFour);
this.numberOfThree = new SimpleLongProperty(numberOfThree);
this.numberOfEducationalComponent = new SimpleLongProperty(numberOfEducationalComponent);
}
public int getId() {
return id.get();
}
public void setId(int id) {
this.id.set(id);
}
public IntegerProperty idProperty() {
return id;
}
public Diploma getDiploma() {
return diploma.get();
}
public void setDiploma(Diploma diploma) {
this.diploma.set(diploma);
}
public ObjectProperty<Diploma> diplomaProperty() {
return diploma;
}
public double getAvg() {
return avg.get();
}
public void setAvg(double avg) {
this.avg.set(avg);
}
public SimpleDoubleProperty avgProperty() {
return avg;
}
public long getNumberOfFive() {
return numberOfFive.get();
}
public void setNumberOfFive(long numberOfFive) {
this.numberOfFive.set(numberOfFive);
}
public LongProperty numberOfFiveProperty() {
return numberOfFive;
}
public long getNumberOfFour() {
return numberOfFour.get();
}
public void setNumberOfFour(long numberOfFour) {
this.numberOfFour.set(numberOfFour);
}
public LongProperty numberOfFourProperty() {
return numberOfFour;
}
public long getNumberOfThree() {
return numberOfThree.get();
}
public void setNumberOfThree(long numberOfThree) {
this.numberOfThree.set(numberOfThree);
}
public LongProperty numberOfThreeProperty() {
return numberOfThree;
}
public long getNumberOfEducationalComponent() {
return numberOfEducationalComponent.get();
}
public void setNumberOfEducationalComponent(long numberOfEducationalComponent) {
this.numberOfEducationalComponent.set(numberOfEducationalComponent);
}
public LongProperty numberOfEducationalComponentProperty() {
return numberOfEducationalComponent;
}
@Override
public int compareTo(StudentWithAVG o) {
return ((this.getAvg() == o.getAvg()) ?
(((this.getNumberOfThree() - o.getNumberOfThree() == 0) ?
(this.getNumberOfFour() > o.getNumberOfFour() ? -1 : 1) :
(this.getNumberOfFour() > o.getNumberOfFour() ? -1 : 1)))
: (this.getAvg() > o.getAvg() ? -1 : 1));
}
}
|
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DTMException.java,v 1.8 2004/08/17 16:17:42 mcnamara Exp $
*/
package org.apache.xml.dtm;
import org.apache.xml.res.XMLErrorResources;
import org.apache.xml.res.XMLMessages;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.xml.transform.SourceLocator;
/**
* This class specifies an exceptional condition that occured
* in the DTM module.
*/
public class DTMException extends RuntimeException {
static final long serialVersionUID = -775576419181334734L;
/** Field locator specifies where the error occured.
* @serial */
SourceLocator locator;
/**
* Method getLocator retrieves an instance of a SourceLocator
* object that specifies where an error occured.
*
* @return A SourceLocator object, or null if none was specified.
*/
public SourceLocator getLocator() {
return locator;
}
/**
* Method setLocator sets an instance of a SourceLocator
* object that specifies where an error occured.
*
* @param location A SourceLocator object, or null to clear the location.
*/
public void setLocator(SourceLocator location) {
locator = location;
}
/** Field containedException specifies a wrapped exception. May be null.
* @serial */
Throwable containedException;
/**
* This method retrieves an exception that this exception wraps.
*
* @return An Throwable object, or null.
* @see #getCause
*/
public Throwable getException() {
return containedException;
}
/**
* Returns the cause of this throwable or <code>null</code> if the
* cause is nonexistent or unknown. (The cause is the throwable that
* caused this throwable to get thrown.)
*/
public Throwable getCause() {
return ((containedException == this)
? null
: containedException);
}
/**
* Initializes the <i>cause</i> of this throwable to the specified value.
* (The cause is the throwable that caused this throwable to get thrown.)
*
* <p>This method can be called at most once. It is generally called from
* within the constructor, or immediately after creating the
* throwable. If this throwable was created
* with {@link #DTMException(Throwable)} or
* {@link #DTMException(String,Throwable)}, this method cannot be called
* even once.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <tt>null</tt> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @return a reference to this <code>Throwable</code> instance.
* @throws IllegalArgumentException if <code>cause</code> is this
* throwable. (A throwable cannot
* be its own cause.)
* @throws IllegalStateException if this throwable was
* created with {@link #DTMException(Throwable)} or
* {@link #DTMException(String,Throwable)}, or this method has already
* been called on this throwable.
*/
public synchronized Throwable initCause(Throwable cause) {
if ((this.containedException == null) && (cause != null)) {
throw new IllegalStateException(XMLMessages.createXMLMessage(XMLErrorResources.ER_CANNOT_OVERWRITE_CAUSE, null)); //"Can't overwrite cause");
}
if (cause == this) {
throw new IllegalArgumentException(
XMLMessages.createXMLMessage(XMLErrorResources.ER_SELF_CAUSATION_NOT_PERMITTED, null)); //"Self-causation not permitted");
}
this.containedException = cause;
return this;
}
/**
* Create a new DTMException.
*
* @param message The error or warning message.
*/
public DTMException(String message) {
super(message);
this.containedException = null;
this.locator = null;
}
/**
* Create a new DTMException wrapping an existing exception.
*
* @param e The exception to be wrapped.
*/
public DTMException(Throwable e) {
super(e.getMessage());
this.containedException = e;
this.locator = null;
}
/**
* Wrap an existing exception in a DTMException.
*
* <p>This is used for throwing processor exceptions before
* the processing has started.</p>
*
* @param message The error or warning message, or null to
* use the message from the embedded exception.
* @param e Any exception
*/
public DTMException(String message, Throwable e) {
super(((message == null) || (message.length() == 0))
? e.getMessage()
: message);
this.containedException = e;
this.locator = null;
}
/**
* Create a new DTMException from a message and a Locator.
*
* <p>This constructor is especially useful when an application is
* creating its own exception from within a DocumentHandler
* callback.</p>
*
* @param message The error or warning message.
* @param locator The locator object for the error or warning.
*/
public DTMException(String message, SourceLocator locator) {
super(message);
this.containedException = null;
this.locator = locator;
}
/**
* Wrap an existing exception in a DTMException.
*
* @param message The error or warning message, or null to
* use the message from the embedded exception.
* @param locator The locator object for the error or warning.
* @param e Any exception
*/
public DTMException(String message, SourceLocator locator,
Throwable e) {
super(message);
this.containedException = e;
this.locator = locator;
}
/**
* Get the error message with location information
* appended.
*/
public String getMessageAndLocation() {
StringBuffer sbuffer = new StringBuffer();
String message = super.getMessage();
if (null != message) {
sbuffer.append(message);
}
if (null != locator) {
String systemID = locator.getSystemId();
int line = locator.getLineNumber();
int column = locator.getColumnNumber();
if (null != systemID) {
sbuffer.append("; SystemID: ");
sbuffer.append(systemID);
}
if (0 != line) {
sbuffer.append("; Line#: ");
sbuffer.append(line);
}
if (0 != column) {
sbuffer.append("; Column#: ");
sbuffer.append(column);
}
}
return sbuffer.toString();
}
/**
* Get the location information as a string.
*
* @return A string with location info, or null
* if there is no location information.
*/
public String getLocationAsString() {
if (null != locator) {
StringBuffer sbuffer = new StringBuffer();
String systemID = locator.getSystemId();
int line = locator.getLineNumber();
int column = locator.getColumnNumber();
if (null != systemID) {
sbuffer.append("; SystemID: ");
sbuffer.append(systemID);
}
if (0 != line) {
sbuffer.append("; Line#: ");
sbuffer.append(line);
}
if (0 != column) {
sbuffer.append("; Column#: ");
sbuffer.append(column);
}
return sbuffer.toString();
} else {
return null;
}
}
/**
* Print the the trace of methods from where the error
* originated. This will trace all nested exception
* objects, as well as this object.
*/
public void printStackTrace() {
printStackTrace(new java.io.PrintWriter(System.err, true));
}
/**
* Print the the trace of methods from where the error
* originated. This will trace all nested exception
* objects, as well as this object.
* @param s The stream where the dump will be sent to.
*/
public void printStackTrace(java.io.PrintStream s) {
printStackTrace(new java.io.PrintWriter(s));
}
/**
* Print the the trace of methods from where the error
* originated. This will trace all nested exception
* objects, as well as this object.
* @param s The writer where the dump will be sent to.
*/
public void printStackTrace(java.io.PrintWriter s) {
if (s == null) {
s = new java.io.PrintWriter(System.err, true);
}
try {
String locInfo = getLocationAsString();
if (null != locInfo) {
s.println(locInfo);
}
super.printStackTrace(s);
} catch (Throwable e) {}
boolean isJdk14OrHigher = false;
try {
Throwable.class.getMethod("getCause");
isJdk14OrHigher = true;
} catch (NoSuchMethodException nsme) {
// do nothing
}
// The printStackTrace method of the Throwable class in jdk 1.4
// and higher will include the cause when printing the backtrace.
// The following code is only required when using jdk 1.3 or lower
if (!isJdk14OrHigher) {
Throwable exception = getException();
for (int i = 0; (i < 10) && (null != exception); i++) {
s.println("---------");
try {
if (exception instanceof DTMException) {
String locInfo =
((DTMException) exception)
.getLocationAsString();
if (null != locInfo) {
s.println(locInfo);
}
}
exception.printStackTrace(s);
} catch (Throwable e) {
s.println("Could not print stack trace...");
}
try {
Method meth =
((Object) exception).getClass().getMethod("getException");
if (null != meth) {
Throwable prev = exception;
exception = (Throwable) meth.invoke(exception);
if (prev == exception) {
break;
}
} else {
exception = null;
}
} catch (InvocationTargetException ite) {
exception = null;
} catch (IllegalAccessException iae) {
exception = null;
} catch (NoSuchMethodException nsme) {
exception = null;
}
}
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.windows;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.EventArgs;
/**
* The base .NET class managing System.Windows.StartupEventArgs, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.StartupEventArgs" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.StartupEventArgs</a>
*/
public class StartupEventArgs extends EventArgs {
/**
* Fully assembly qualified name: PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
*/
public static final String assemblyFullName = "PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
/**
* Assembly name: PresentationFramework
*/
public static final String assemblyShortName = "PresentationFramework";
/**
* Qualified class name: System.Windows.StartupEventArgs
*/
public static final String className = "System.Windows.StartupEventArgs";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public StartupEventArgs(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link StartupEventArgs}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link StartupEventArgs} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static StartupEventArgs cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new StartupEventArgs(from.getJCOInstance());
}
// Constructors section
public StartupEventArgs() throws Throwable {
}
// Methods section
// Properties section
public java.lang.String[] getArgs() throws Throwable, system.ArgumentException, system.ArgumentNullException, system.NotImplementedException, system.globalization.CultureNotFoundException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.resources.MissingManifestResourceException, system.ObjectDisposedException, system.InvalidOperationException, system.deployment.application.InvalidDeploymentException, system.PlatformNotSupportedException, system.io.FileNotFoundException, system.io.DirectoryNotFoundException, system.UnauthorizedAccessException, system.io.IOException, system.io.PathTooLongException, system.io.DriveNotFoundException, system.OperationCanceledException, system.NotSupportedException, system.MissingMethodException, system.security.SecurityException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
ArrayList<java.lang.Object> resultingArrayList = new ArrayList<java.lang.Object>();
JCObject resultingObjects = (JCObject)classInstance.Get("Args");
for (java.lang.Object resultingObject : resultingObjects) {
resultingArrayList.add(resultingObject);
}
java.lang.String[] resultingArray = new java.lang.String[resultingArrayList.size()];
for(int indexArgs = 0; indexArgs < resultingArrayList.size(); indexArgs++ ) {
resultingArray[indexArgs] = (java.lang.String)resultingArrayList.get(indexArgs);
}
return resultingArray;
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Instance Events section
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.test;
import com.yahoo.document.Document;
import com.yahoo.document.DocumentId;
import com.yahoo.document.DocumentPut;
import com.yahoo.document.DocumentRemove;
import com.yahoo.document.DocumentType;
import com.yahoo.documentapi.AsyncParameters;
import com.yahoo.documentapi.AsyncSession;
import com.yahoo.documentapi.DocumentAccess;
import com.yahoo.documentapi.DocumentResponse;
import com.yahoo.documentapi.Response;
import com.yahoo.documentapi.ResponseHandler;
import com.yahoo.documentapi.Result;
import com.yahoo.documentapi.SyncParameters;
import com.yahoo.documentapi.SyncSession;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* These tests should work with all implementations (who choose to implement these features) To test a certain
* implementation subclass this test and make the subclass setup assign the implementation class to the
* <code>access</code> member variable (make sure it also calls super.setUp()). Override tests of nonsupported features
* to do nothing.
*
* @author bratseth
*/
public abstract class AbstractDocumentApiTestCase {
protected abstract DocumentAccess access();
@Test
public void requireThatSyncSessionWorks() {
SyncSession session = access().createSyncSession(new SyncParameters.Builder().build());
DocumentType type = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(type, new DocumentId("id:ns:music::1"));
Document doc2 = new Document(type, new DocumentId("id:ns:music::2"));
session.put(new DocumentPut(doc1));
session.put(new DocumentPut(doc2));
assertEquals(doc1, session.get(new DocumentId("id:ns:music::1")));
assertEquals(doc2, session.get(new DocumentId("id:ns:music::2")));
session.remove(new DocumentRemove(new DocumentId("id:ns:music::1")));
assertNull(session.get(new DocumentId("id:ns:music::1")));
assertEquals(doc2, session.get(new DocumentId("id:ns:music::2")));
session.remove(new DocumentRemove(new DocumentId("id:ns:music::2")));
assertNull(session.get(new DocumentId("id:ns:music::1")));
assertNull(session.get(new DocumentId("id:ns:music::2")));
session.destroy();
}
@Test
public void requireThatAsyncSessionWorks() throws InterruptedException {
AsyncSession session = access().createAsyncSession(new AsyncParameters());
HashMap<Long, Response> results = new LinkedHashMap<>();
Result result;
DocumentType type = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(type, new DocumentId("id:ns:music::1"));
Document doc2 = new Document(type, new DocumentId("id:ns:music::2"));
result = session.put(doc1);
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new Response(result.getRequestId()));
result = session.put(doc2);
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new Response(result.getRequestId()));
List<Response> responses = new ArrayList<>();
waitForAcks(session, 2, responses);
result = session.get(new DocumentId("id:ns:music::1"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new DocumentResponse(result.getRequestId(), doc1));
result = session.get(new DocumentId("id:ns:music::2"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new DocumentResponse(result.getRequestId(), doc2));
// These Gets shall observe the ACKed Puts sent for the same document IDs.
waitForAcks(session, 2, responses);
result = session.remove(new DocumentId("id:ns:music::1"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new Response(result.getRequestId()));
waitForAcks(session, 1, responses);
result = session.get(new DocumentId("id:ns:music::1"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new DocumentResponse(result.getRequestId()));
result = session.get(new DocumentId("id:ns:music::2"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new DocumentResponse(result.getRequestId(), doc2));
waitForAcks(session, 2, responses);
result = session.remove(new DocumentId("id:ns:music::2"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new Response(result.getRequestId()));
waitForAcks(session, 1, responses);
result = session.get(new DocumentId("id:ns:music::1"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new DocumentResponse(result.getRequestId()));
result = session.get(new DocumentId("id:ns:music::2"));
assertTrue(result.isSuccess());
results.put(result.getRequestId(), new DocumentResponse(result.getRequestId()));
waitForAcks(session, 2, responses);
for (Response response : responses) {
assertTrue(response.isSuccess());
assertEquals(results.get(response.getRequestId()), response);
}
session.destroy();
}
@Test
public void requireThatAsyncHandlerWorks() throws InterruptedException {
MyHandler handler = new MyHandler();
AsyncSession session = access().createAsyncSession(new AsyncParameters().setResponseHandler(handler));
DocumentType type = access().getDocumentTypeManager().getDocumentType("music");
Document doc1 = new Document(type, new DocumentId("id:ns:music::1"));
assertTrue(session.put(doc1).isSuccess());
assertTrue(handler.latch.await(60, TimeUnit.SECONDS));
assertNotNull(handler.response);
session.destroy();
}
private static void waitForAcks(AsyncSession session, int n, List<Response> responsesOut) throws InterruptedException {
for (int i = 0; i < n; ++i) {
Response response;
if (i % 2 == 0) {
response = pollNext(session);
} else {
response = session.getNext(60000);
}
responsesOut.add(response);
}
}
private static Response pollNext(AsyncSession session) throws InterruptedException {
for (int i = 0; i < 600; ++i) {
Response response = session.getNext();
if (response != null) {
return response;
}
Thread.sleep(100);
}
return null;
}
private static class MyHandler implements ResponseHandler {
final CountDownLatch latch = new CountDownLatch(1);
Response response = null;
@Override
public void handleResponse(Response response) {
this.response = response;
latch.countDown();
}
}
}
|
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.util.ArrayList;
import static java.lang.System.*;
public class PhoneBookServerImpl extends UnicastRemoteObject implements PhoneBookServer {
private ArrayList<PhoneBookEntry> contacts = new ArrayList<PhoneBookEntry>();
private MongoClient connection;
private MongoDatabase database;
public PhoneBookServerImpl(MongoClient connection, MongoDatabase database) throws RemoteException {
super();
setConnection(connection);
setDatabase(database);
}
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase mongoDB = mongoClient.getDatabase("mongoContacts");
PhoneBookServerImpl server = new PhoneBookServerImpl(mongoClient, mongoDB);
Registry registry = LocateRegistry.createRegistry(3333);
registry.bind("Contacts", server);
out.println("Servidor inicializado");
} catch (RemoteException | AlreadyBoundException ex) {
err.println(ex);
}
}
public ArrayList<PhoneBookEntry> getPhoneBook() throws RemoteException {
out.println("Executando getPhoneBook()... Obtendo todos os contatos cadastrados");
return this.contacts;
}
public void addEntry(PhoneBookEntry entry) throws RemoteException {
out.printf("Executando addEntry()... Adicionando um novo contato na lista e na base de dados: %s%n",
entry.toString());
this.contacts.add(entry);
Document document = new Document();
document.put("firstname", entry.getFisrtname());
document.put("lastname", entry.getLastname());
document.put("phone", entry.getPhone());
this.database.getCollection("contacts").insertOne(document);
}
public MongoClient getConnection() { return this.connection; }
public void setConnection(MongoClient connection) {
this.connection = connection;
}
public MongoDatabase getDatabase() { return this.database; }
public void setDatabase(MongoDatabase database) {
this.database = database;
}
@Override
public String toString() {
return "PhoneBookServerImpl{" +
"contacts=" + contacts +
", connection=" + connection +
", database=" + database +
'}';
}
}
|
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.impl.operations;
import com.hazelcast.client.ClientEndpoint;
import com.hazelcast.client.ClientEndpointManager;
import com.hazelcast.client.impl.ClientEngineImpl;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.spi.AbstractOperation;
import com.hazelcast.spi.ClientAwareService;
import com.hazelcast.spi.UrgentSystemOperation;
import com.hazelcast.spi.impl.NodeEngineImpl;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
public class ClientDisconnectionOperation extends AbstractOperation implements UrgentSystemOperation {
private String clientUuid;
public ClientDisconnectionOperation() {
}
public ClientDisconnectionOperation(String clientUuid) {
this.clientUuid = clientUuid;
}
@Override
public void run() throws Exception {
ClientEngineImpl engine = getService();
final ClientEndpointManager endpointManager = engine.getEndpointManager();
Set<ClientEndpoint> endpoints = endpointManager.getEndpoints(clientUuid);
for (ClientEndpoint endpoint : endpoints) {
endpointManager.removeEndpoint(endpoint, true);
}
engine.removeOwnershipMapping(clientUuid);
NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine();
nodeEngine.onClientDisconnected(clientUuid);
Collection<ClientAwareService> services = nodeEngine.getServices(ClientAwareService.class);
for (ClientAwareService service : services) {
service.clientDisconnected(clientUuid);
}
}
@Override
public boolean returnsResponse() {
return false;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(clientUuid);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
clientUuid = in.readUTF();
}
}
|
/*
* Copyright 2016 Elvis Hew
*
* 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.toan_itc.core.library.logtracking.printer;
/**
* Represents a group of Printers that should used to print logs in the same time, each printer
* may probably print the log to different place.
*/
public class PrinterSet implements Printer {
private Printer[] printers;
/**
* Constructor, pass printers in and will use all these printers to print the same logs.
*
* @param printers the printers used to print the same logs
*/
public PrinterSet(Printer... printers) {
this.printers = printers;
}
@Override
public void println(int logLevel, String tag, String msg) {
for (Printer printer : printers) {
printer.println(logLevel, tag, msg);
}
}
}
|
/*
* 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.isis.testing.fakedata.applib.services;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.value.Password;
/**
* @since 2.0 {@index}
*/
public class IsisPasswords extends AbstractRandomValueGenerator {
public IsisPasswords(final FakeDataService fakeDataService) {
super(fakeDataService);
}
@Programmatic
public Password any() {
return new Password(fake.strings().fixed(12));
}
}
|
package org.mimosaframework.orm.platform.postgresql;
import org.mimosaframework.core.utils.StringTools;
import org.mimosaframework.orm.mapping.MappingGlobalWrapper;
import org.mimosaframework.orm.platform.ExecuteImmediate;
import org.mimosaframework.orm.platform.PlatformStampShare;
import org.mimosaframework.orm.sql.stamp.StampAction;
import org.mimosaframework.orm.sql.stamp.StampAlter;
import org.mimosaframework.orm.sql.stamp.StampColumn;
import org.mimosaframework.orm.sql.stamp.StampCreate;
public class PostgreSQLStampShare extends PlatformStampShare {
public void addCommentSQL(MappingGlobalWrapper wrapper,
StampAction action,
Object param,
String commentStr,
int type) {
Class table = null;
String tableStr = null;
if (action instanceof StampAlter) {
table = ((StampAlter) action).tableClass;
tableStr = ((StampAlter) action).tableName;
}
if (action instanceof StampCreate) {
table = ((StampCreate) action).tableClass;
tableStr = ((StampCreate) action).tableName;
}
StringBuilder comment = new StringBuilder();
if (type == 1) {
StampColumn column = (StampColumn) param;
comment.append("COMMENT ON COLUMN ");
if (table != null) {
column.table = table;
} else if (StringTools.isNotEmpty(tableStr)) {
column.tableAliasName = tableStr;
}
comment.append(this.commonality.getReference().getColumnName(wrapper, action, column));
}
if (type == 2) {
String tableName = this.commonality.getReference().getTableName(wrapper, table, tableStr);
comment.append("COMMENT ON TABLE " + tableName);
}
comment.append(" IS ");
comment.append("'" + commentStr + "'");
this.commonality.getSection().getBuilders().add(new ExecuteImmediate(comment));
}
}
|
package com.alipay.api.response;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: koubei.catering.merchant.tmall.sync response.
*
* @author auto create
* @since 1.0, 2020-11-26 21:10:13
*/
public class KoubeiCateringMerchantTmallSyncResponse extends AlipayResponse {
private static final long serialVersionUID = 1829139441432172669L;
}
|
/*
* The MIT License
*
* Copyright 2015 Konrad Nowakowski https://github.com/konrad92.
*
* 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 vault.clockwork.editor.props;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import vault.clockwork.actors.HillActor;
import vault.clockwork.editor.PropActor;
import vault.clockwork.editor.PropSerialized;
/**
* General hill editor prop.
* @author Agnieszka Makowska https://github.com/Migemiley
*/
public class HillProp extends PropSerialized {
public float radius = 27.f;
/**
* Ctor.
*/
public HillProp() {
this.layer = 2;
}
/**
* @param gizmo
*/
@Override
public void draw(ShapeRenderer gizmo) {
gizmo.setColor(Color.BLUE);
gizmo.circle(position.x, position.y, radius);
}
/**
* HillActor class.
* @return
*/
@Override
public Class<? extends PropActor> getActorClass() {
return HillActor.class;
}
}
|
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticache.model;
/**
* <p>
* An endpoint completely specifies enough information to connect to a
* Cache Node.
* </p>
*/
public class Endpoint {
/**
* Specifies the DNS address of the Cache Node.
*/
private String address;
/**
* Specifies the port that the cache engine is listening on.
*/
private Integer port;
/**
* Default constructor for a new Endpoint object. Callers should use the
* setter or fluent setter (with...) methods to initialize this object after creating it.
*/
public Endpoint() {}
/**
* Specifies the DNS address of the Cache Node.
*
* @return Specifies the DNS address of the Cache Node.
*/
public String getAddress() {
return address;
}
/**
* Specifies the DNS address of the Cache Node.
*
* @param address Specifies the DNS address of the Cache Node.
*/
public void setAddress(String address) {
this.address = address;
}
/**
* Specifies the DNS address of the Cache Node.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param address Specifies the DNS address of the Cache Node.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public Endpoint withAddress(String address) {
this.address = address;
return this;
}
/**
* Specifies the port that the cache engine is listening on.
*
* @return Specifies the port that the cache engine is listening on.
*/
public Integer getPort() {
return port;
}
/**
* Specifies the port that the cache engine is listening on.
*
* @param port Specifies the port that the cache engine is listening on.
*/
public void setPort(Integer port) {
this.port = port;
}
/**
* Specifies the port that the cache engine is listening on.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param port Specifies the port that the cache engine is listening on.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public Endpoint withPort(Integer port) {
this.port = port;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("Address: " + address + ", ");
sb.append("Port: " + port + ", ");
sb.append("}");
return sb.toString();
}
}
|
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.core.module;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.terasology.gestalt.module.Module;
import org.terasology.gestalt.module.ModuleFactory;
import org.terasology.gestalt.module.ModuleMetadata;
import org.terasology.gestalt.module.sandbox.API;
import org.terasology.gestalt.naming.Name;
import org.terasology.gestalt.naming.Version;
import org.terasology.unittest.ExampleClass;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClasspathCompromisingModuleFactoryTest {
final static Class<?> someClassOutsideTheModule = ClasspathCompromisingModuleFactory.class;
@Test
public void directoryModuleContainsClass() {
ModuleFactory factory = new ClasspathCompromisingModuleFactory();
// This test assumes that the unittest module is under the current working directory (`engine-test/`)
File engineTestDirectory = new File(System.getProperty("user.dir", "."));
ModuleMetadata metadata = new ModuleMetadata(new Name("unittest"), new Version("1.0.0"));
Module module = factory.createDirectoryModule(metadata, engineTestDirectory);
// and that ExampleClass is inside that directory
assertTrue(module.getClassPredicate().test(ExampleClass.class));
// and that this other class (in engine, not engine-test) is outside that directory.
assertFalse(module.getClassPredicate().test(someClassOutsideTheModule));
// These assumptions could break if things get moved around enough.
}
@Test
@Disabled("TODO: need a jar module containing classes")
public void archiveModuleContainsClass() throws IOException {
ModuleFactory factory = new ClasspathCompromisingModuleFactory();
Module module = factory.createArchiveModule(new File("FIXME.jar"));
Class<?> someClassInTheModule = module.getModuleManifest().getTypesAnnotatedWith(API.class).iterator().next();
assertTrue(module.getClassPredicate().test(someClassInTheModule));
assertFalse(module.getClassPredicate().test(someClassOutsideTheModule));
}
@Test
@Disabled("TODO: need a jar module alongside a classes directory")
public void directoryModuleContainsClassLoadedFromJar() {
// Example:
// - m/build/classes/org/t/Foo.class
// - m/build/libs/foo.jar
// load m as directory module while foo.jar is on classpath
}
}
|
package io.github.intellij.dlanguage.module;
import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.ProjectBuilder;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.projectImport.ProjectFormatPanel;
import io.github.intellij.dlanguage.DlangBundle;
import io.github.intellij.dlanguage.icons.DlangIcons;
import io.github.intellij.dlanguage.project.DubProjectImportBuilder;
import io.github.intellij.dlanguage.settings.DLanguageToolsConfigurable;
import io.github.intellij.dlanguage.settings.ToolKey;
import io.github.intellij.dlanguage.utils.GuiUtil;
import javax.swing.*;
import java.awt.*;
public class DubBinaryForModuleStep extends ModuleWizardStep {
private final WizardContext myWizardContext;
private final JPanel myPanel;
private final ProjectFormatPanel myFormatPanel = new ProjectFormatPanel();
private final TextFieldWithBrowseButton dubBinary;
public DubBinaryForModuleStep(final WizardContext wizardContext) {
this.myWizardContext = wizardContext;
this.myPanel = new JPanel(new GridBagLayout());
this.myPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// Title label
final JLabel titletextLabel = new JLabel(DlangBundle.INSTANCE.message("d.ui.dub.config.label.choosedublocation"));
this.myPanel.add(titletextLabel, new GridBagConstraints(0, -1, 1, 1, 1.0D, 0.0D, 18, 2, new Insets(8, 10, 8, 10), 0, 0));
this.dubBinary = new TextFieldWithBrowseButton();
if(StringUtil.isNotEmpty(ToolKey.DUB_KEY.getPath())) {
this.dubBinary.setText(ToolKey.DUB_KEY.getPath());
}
final JButton autoFindButton = new JButton(DlangBundle.INSTANCE.message("d.ui.dub.config.label.autofind"), DlangIcons.SDK);
final JLabel dubFormatLabel = new JLabel(DlangBundle.INSTANCE.message("d.ui.dub.config.label.dubbinarylocation"));
dubFormatLabel.setLabelFor(dubBinary);
GuiUtil.addFolderListener(dubBinary, "dub");
GuiUtil.addApplyPathAction(autoFindButton, dubBinary, "dub");
this.myPanel.add(dubFormatLabel, new GridBagConstraints(0, -1, 1, 1, 0.0D, 0.0D, 17, 0, new Insets(0, 0, 5, 4), 0, 0));
this.myPanel.add(dubBinary, new GridBagConstraints(0, -1, 1, 1, 1.0D, 0.0D, 18, 2, new Insets(10, 0, 20, 0), 0, 0));
this.myPanel.add(autoFindButton, new GridBagConstraints(0, -1, 1, 1, 1.0D, 0.0D, 18, 2, new Insets(10, 0, 20, 0), 0, 0));
}
@Override
public JComponent getPreferredFocusedComponent() {
return dubBinary;
}
@Override
public JComponent getComponent() {
return this.myPanel;
}
@Override
public boolean isStepVisible() {
return this.myWizardContext.getProject() == null;
}
@Override
public void updateDataModel() {
final ProjectBuilder moduleBuilder = this.myWizardContext.getProjectBuilder();
final String dubBinaryPath = this.dubBinary.getText();
if(StringUtil.isEmpty(ToolKey.DUB_KEY.getPath()) && StringUtil.isNotEmpty(dubBinaryPath)) {
ToolKey.DUB_KEY.setPath(dubBinaryPath);
}
if (moduleBuilder != null && !dubBinaryPath.isEmpty()) {
this.myWizardContext.setProjectBuilder(moduleBuilder);
if (moduleBuilder instanceof ModuleBuilder) {
final ModuleBuilder builder = (ModuleBuilder) moduleBuilder;
if (builder.getBuilderId() != null && DlangDubModuleBuilder.BUILDER_ID.equals(builder.getBuilderId())) {
final DlangDubModuleBuilder dubBuilder = (DlangDubModuleBuilder) builder;
dubBuilder.setDubBinary(dubBinaryPath);
}
} else if (moduleBuilder instanceof DubProjectImportBuilder) {
((DubProjectImportBuilder) moduleBuilder).getParameters().dubBinary = dubBinaryPath;
}
}
this.myFormatPanel.updateData(this.myWizardContext);
}
@Override
public boolean validate() throws ConfigurationException {
if(StringUtil.isEmpty(this.dubBinary.getText())) {
throw new ConfigurationException(
DlangBundle.INSTANCE.message("d.ui.dub.config.error.path-not-set"),
DlangBundle.INSTANCE.message("d.ui.dub.config.error.title")
);
} else if(StringUtil.isEmpty(DLanguageToolsConfigurable.getVersion(this.dubBinary.getText()))) {
throw new ConfigurationException(
DlangBundle.INSTANCE.message("d.ui.dub.config.error.path-not-valid"),
DlangBundle.INSTANCE.message("d.ui.dub.config.error.title")
);
}
return true;
}
public Icon getIcon() {
return this.myWizardContext.getStepIcon();
}
}
|
package no.rustelefonen.hap.main.tabs.trigger;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import no.rustelefonen.hap.R;
import no.rustelefonen.hap.entities.Trigger;
import no.rustelefonen.hap.entities.User;
import no.rustelefonen.hap.entities.UserTrigger;
import no.rustelefonen.hap.main.tabs.program.ProgramTab;
import no.rustelefonen.hap.persistence.OrmLiteActivity;
import no.rustelefonen.hap.persistence.dao.TriggerDao;
import no.rustelefonen.hap.persistence.dao.UserDao;
import no.rustelefonen.hap.util.SizeAnimator;
import static no.rustelefonen.hap.util.DialogHelper.showDiscardChangesAndFinishDialog;
import static no.rustelefonen.hap.util.DialogHelper.showInfoDialog;
import static no.rustelefonen.hap.util.Dimensions.toDP;
/**
* Created by martinnikolaisorlie on 23/02/16.
*/
public class TriggerActivity extends OrmLiteActivity {
public static final String USER_INFO_EXTRA = "user_info_extra";
private User user;
private List<CheckableTrigger> checkableTriggers;
@BindView(R.id.situation_list_recyclerview) RecyclerView recyclerView;
@BindView(R.id.trigger_results) LinearLayout triggerResults;
@BindView(R.id.triggers) LinearLayout triggersLayout;
@BindView(R.id.passed_situation_btn) ImageView passedSituationBtn;
@BindView(R.id.failed_situation_btn) ImageView failedSituationBtn;
@BindView(R.id.passed_situation_checkmark) ImageView passedSituationCheckmark;
@BindView(R.id.failed_situation_checkmark) ImageView failedSituationCheckmark;
@BindView(R.id.situation_header) TextView situationHeader;
private Unbinder unbinder;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.trigger_activity);
super.onCreate(savedInstanceState);
unbinder = ButterKnife.bind(this);
initDataObjects();
initSituationsList();
}
private void initDataObjects() {
checkableTriggers = new ArrayList<>();
user = getIntent().getExtras().getParcelable(USER_INFO_EXTRA);
List<Trigger> triggers = new TriggerDao(this).getAll();
for (Trigger trigger : triggers) {
checkableTriggers.add(new CheckableTrigger(trigger));
}
}
private void initSituationsList() {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
TriggerAdapter triggerAdapter = new TriggerAdapter(checkableTriggers, new View.OnClickListener() {
@Override public void onClick(View v) {
int i = recyclerView.getChildAdapterPosition(v);
boolean newCheckedState = !checkableTriggers.get(i).isChecked;
checkableTriggers.get(i).isChecked = newCheckedState;
v.findViewById(R.id.passed_situation_checkmark).setAlpha(newCheckedState ? 1f : 0f);
}
});
recyclerView.setAdapter(triggerAdapter);
}
@Override
public void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.save_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.save) {
if (noTriggersChecked()) showInfoDialog(this, getString(R.string.no_triggers_selected_dialog_title), getString(R.string.no_triggers_selected_dialog_text));
else if (getSelectetTriggerType() == null) showInfoDialog(this, getString(R.string.no_trigger_type_selected_dialog_title), getString(R.string.no_trigger_type_selected_dialog_text));
else {
saveTriggers();
Intent intent = new Intent();
intent.putExtra(USER_INFO_EXTRA, user);
setResult(RESULT_OK, intent);
finish();
EventBus.getDefault().post(new ProgramTab.TriggerAddedEvent());
}
}
return super.onOptionsItemSelected(item);
}
@OnClick(R.id.passed_situation_btn)
public void setPassedSituationCheckmark() {
situationHeader.setText(R.string.positive_trigger_title);
invertAlpha(passedSituationCheckmark);
failedSituationCheckmark.setAlpha(0f);
if (triggerResults.getY() > 0) showTriggerListWithAnimation();
}
@OnClick(R.id.failed_situation_btn)
public void setFailedSituationCheckmark() {
situationHeader.setText(R.string.negative_trigger_title);
invertAlpha(failedSituationCheckmark);
passedSituationCheckmark.setAlpha(0f);
if (triggerResults.getY() > 0) showTriggerListWithAnimation();
}
private void invertAlpha(View view) {
float alpha = view.getAlpha() == 1f ? 0f : 1f;
view.setAlpha(alpha);
}
private void showTriggerListWithAnimation() {
float triggerResultY = -toDP(50);
float distance = Math.abs(triggerResultY - triggerResults.getTop() - toDP(25));
triggerResults.animate().y(triggerResultY).setDuration(300).start();
SizeAnimator.size(passedSituationBtn, (int) toDP(75), (int) toDP(75), 300);
SizeAnimator.size(failedSituationBtn, (int) toDP(75), (int) toDP(75), 300);
//because it's clipped by default..
triggersLayout.getLayoutParams().height = (int) (triggersLayout.getHeight() + distance + toDP(2));
triggersLayout.requestLayout();
triggersLayout.animate().yBy(-distance).setDuration(300).start();
triggersLayout.animate().alpha(1).setDuration(500).start();
}
private void saveTriggers() {
UserTrigger.Type type = getSelectetTriggerType();
//no trigger type selected
if (type == null) return;
for (CheckableTrigger checkableTrigger : checkableTriggers) {
if (!checkableTrigger.isChecked) continue;
user.addTrigger(checkableTrigger.trigger, type);
}
//save
new UserDao(this).batchPersistUnsavedTriggers(user);
}
class CheckableTrigger {
Trigger trigger;
boolean isChecked;
public CheckableTrigger(Trigger trigger) {
this.trigger = trigger;
}
}
@Override
public void onBackPressed() {
if (noTriggersChecked()) super.onBackPressed();
else showDiscardChangesAndFinishDialog(this, getString(R.string.not_saved_title), getString(R.string.not_saved_text));
}
private boolean noTriggersChecked() {
for (CheckableTrigger trigger : checkableTriggers) {
if (trigger.isChecked) return false;
}
return true;
}
private UserTrigger.Type getSelectetTriggerType() {
UserTrigger.Type type = null;
if (passedSituationCheckmark.getAlpha() == 1f) type = UserTrigger.Type.RESISTED;
else if (failedSituationCheckmark.getAlpha() == 1f) type = UserTrigger.Type.SMOKED;
return type;
}
}
|
package com.noleme.crawl;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.noleme.crawl.data.Page;
import com.noleme.crawl.etl.PageLinkExtractor;
import com.noleme.crawl.etl.PageLoader;
import com.noleme.flow.Flow;
import com.noleme.flow.FlowOut;
import com.noleme.flow.compiler.FlowCompiler;
import com.noleme.flow.connect.commons.generator.IterableGenerator;
import com.noleme.flow.connect.commons.loader.file.FileWriteJson;
import com.noleme.flow.connect.commons.transformer.filesystem.CreateDirectory;
import com.noleme.flow.connect.etl.ETL;
import com.noleme.flow.connect.http.transformer.HttpTransformers;
import com.noleme.flow.connect.jsoup.transformer.JsoupURLParser;
import com.noleme.flow.impl.parallel.ParallelCompiler;
import com.noleme.flow.node.Node;
import com.noleme.flow.stream.StreamOut;
import com.noleme.json.Json;
import org.jsoup.nodes.Document;
import java.util.Collection;
import java.util.List;
import static com.noleme.flow.Flow.nonFatal;
/**
* @author Pierre Lecerf (plecerf@lumiomedical.com)
* Created on 2020/12/24
*/
public class SampleCrawl extends ETL
{
private final String outputDir;
private final int parallelism;
public SampleCrawl(String outputDir, int parallelism)
{
this.outputDir = outputDir;
this.parallelism = parallelism;
}
@Override
protected Collection<Node> provideFlows()
{
/* We extract the root page, then we extract all its links */
var rootFlow = extractRootPage();
var crawlFlow = crawlPage(rootFlow);
/* From these flows, we produce some stats */
FlowOut<ObjectNode> statsFlow;
statsFlow = createStats(rootFlow);
statsFlow = updateStats(crawlFlow, statsFlow);
statsFlow.sink(new FileWriteJson<>(outputDir+"stats.json"));
return List.of(rootFlow);
}
@Override
protected FlowCompiler<?> provideCompiler()
{
return new ParallelCompiler(this.parallelism, true);
}
/**
*
* @return The root page flow
*/
private FlowOut<Page> extractRootPage()
{
FlowOut<String> urlFlow = Flow.from("url");
return urlFlow
.pipe(new CreateDirectory<>(this.outputDir))
/* We produce a Page entity and extract links in the document */
.pipe(HttpTransformers::asURL)
.pipe(new JsoupURLParser())
.pipe(SampleCrawl::createPage)
.pipe(new PageLinkExtractor())
.driftSink(new PageLoader(this.outputDir))
;
}
/**
*
* @param rootFlow The root page flow
* @return A stream of Pages found in the root page
*/
private StreamOut<Page> crawlPage(FlowOut<Page> rootFlow)
{
return rootFlow
.pipe(Page::getLinks)
.stream(IterableGenerator::new).setMaxParallelism(this.parallelism)
/* For each link, we query the page and stop the stream flow if it isn't successful */
.pipe(nonFatal(HttpTransformers::asURL))
.pipe(nonFatal(new JsoupURLParser()))
.pipe(SampleCrawl::createPage)
.driftSink(new PageLoader(this.outputDir))
;
}
/**
* From the root flow, we produce an array of links found in the root page.
*
* @param rootFlow The root page flow
* @return The stats flow as a JSON object
*/
private FlowOut<ObjectNode> createStats(FlowOut<Page> rootFlow)
{
/* We initialize a "stats" file with some metadata */
return rootFlow
.pipe(page -> {
var json = Json.newObject();
var links = Json.newArray();
for (String link : page.getLinks())
links.add(link);
json.set("found_links", links);
return json;
})
;
}
/**
* From the child page stream, we make an accumulation for counting how many pages we could download (remember that failed downloads result in a flow interruption).
*
* @param pageFlow The root page flow
* @param statsFlow The stats flow
* @return The stats flow as a JSON object
*/
private FlowOut<ObjectNode> updateStats(StreamOut<Page> pageFlow, FlowOut<ObjectNode> statsFlow)
{
return pageFlow
/* We accumulate all processed links and update the "stats" file */
.accumulate(Collection::size)
.join(statsFlow, (pageCount, stats) -> stats.put("downloaded_pages", pageCount))
;
}
/**
*
* @param document
* @return
*/
private static Page createPage(Document document)
{
return new Page(document.baseUri())
.setDocument(document)
;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.28 at 05:34:43 PM CEST
//
package ch.ehi.oereb.schemas.gml._3_2;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for GridLengthType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GridLengthType">
* <simpleContent>
* <extension base="<http://www.opengis.net/gml/3.2>MeasureType">
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GridLengthType")
public class GridLengthTypeType
extends MeasureTypeType
implements Serializable
{
private final static long serialVersionUID = 1L;
}
|
import java.util.Scanner;
public class GameManager {
Scanner myScanner = new Scanner(System.in);
private void chooseGame() {
int gameNumber;
System.out.println("\nWelcome to Greg's game room");
System.out.println("Choose a game:");
System.out.println("1. Hangman");
System.out.println("2. Tic Tac Toe");
gameNumber = myScanner.nextInt();
if (gameNumber == 1) {
Hangman hangmanGame = new Hangman(Hangman.chooseDifficultyLevel());
hangmanGame.playGame();
}
else if (gameNumber == 2) {
TicTacToe theGame = new TicTacToe();
theGame.playTicTacToe();
}
else {
System.out.println("That is not a valid game, try again");
chooseGame();
}
}
public static void main (String[] args) {
GameManager myGames = new GameManager();
myGames.chooseGame();
}
}
// TODO: MAKE A GAME MANAGER CLASS THAT ALLOWS
// YOU TO CHOOSE BETWEEN TICTACTOE AND HANGMAN
|
package org.swtk.commons.dict.wordnet.indexbyid.instance.p1.p3; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance1363 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("13630031", "{\"term\":\"weight\", \"synsetCount\":8, \"upperType\":\"NOUN\", \"ids\":[\"13610524\", \"13630031\", \"13737860\", \"07554200\", \"04578374\", \"05179849\", \"04578578\", \"05034009\"]}");
add("13630031", "{\"term\":\"weight unit\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13630031\", \"13739260\"]}");
add("13630457", "{\"term\":\"mass unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13630457\"]}");
add("13630633", "{\"term\":\"unit of viscosity\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13630633\"]}");
add("13630750", "{\"term\":\"energy unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13630750\"]}");
add("13630750", "{\"term\":\"heat unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13630750\"]}");
add("13630750", "{\"term\":\"work unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13630750\"]}");
add("13631114", "{\"term\":\"langley\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"11136632\", \"13631114\"]}");
add("13631191", "{\"term\":\"brinell number\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13631191\"]}");
add("13631289", "{\"term\":\"brix scale\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13631289\"]}");
add("13631405", "{\"term\":\"point\", \"synsetCount\":26, \"upperType\":\"NOUN\", \"ids\":[\"03218529\", \"03981029\", \"03981127\", \"04739307\", \"05078725\", \"06825147\", \"06834918\", \"06856570\", \"13421323\", \"13734391\", \"13852504\", \"03980573\", \"04739165\", \"13817097\", \"06494090\", \"09419340\", \"13631405\", \"13934887\", \"13925175\", \"05992951\", \"15205381\", \"13962925\", \"05825971\", \"06619161\", \"08637636\", \"05874582\"]}");
add("13631669", "{\"term\":\"advantage\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05150110\", \"13631669\", \"05163204\"]}");
add("13631783", "{\"term\":\"set point\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13631783\"]}");
add("13631912", "{\"term\":\"match point\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13631912\"]}");
add("13632058", "{\"term\":\"sabin\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"11297269\", \"13632058\"]}");
add("13632230", "{\"term\":\"circular measure\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13632230\"]}");
add("13632325", "{\"term\":\"mil\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"13632325\", \"13644955\", \"13676707\", \"13676880\", \"13715886\"]}");
add("13632450", "{\"term\":\"arcdegree\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13632450\"]}");
add("13632450", "{\"term\":\"degree\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"05101827\", \"13736289\", \"05869901\", \"13632450\", \"06710094\", \"13962925\", \"05101152\"]}");
add("13632638", "{\"term\":\"arcsecond\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13632638\"]}");
add("13632638", "{\"term\":\"second\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"03592219\", \"04171590\", \"07195032\", \"10587511\", \"13632638\", \"13868743\", \"15269461\", \"00725034\", \"15271664\", \"15259923\"]}");
add("13632810", "{\"term\":\"arcminute\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13632810\"]}");
add("13632810", "{\"term\":\"minute\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"05138288\", \"06518306\", \"13632810\", \"15269461\", \"15271664\", \"15259561\"]}");
add("13632810", "{\"term\":\"minute of arc\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13632810\"]}");
add("13632983", "{\"term\":\"microradian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13632983\"]}");
add("13633127", "{\"term\":\"milliradian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13633127\"]}");
add("13633285", "{\"term\":\"rad\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13633285\", \"13668175\"]}");
add("13633285", "{\"term\":\"radian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13633285\"]}");
add("13633562", "{\"term\":\"grad\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"09805779\", \"13633562\"]}");
add("13633562", "{\"term\":\"grade\", \"synsetCount\":9, \"upperType\":\"NOUN\", \"ids\":[\"02409604\", \"05101152\", \"05139310\", \"05745098\", \"07126990\", \"13633562\", \"05075885\", \"14451564\", \"08255384\"]}");
add("13633670", "{\"term\":\"oxtant\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13633670\"]}");
add("13633793", "{\"term\":\"sextant\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"04187949\", \"13633793\"]}");
add("13633931", "{\"term\":\"straight angle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13633931\"]}");
add("13634034", "{\"term\":\"sr\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13634034\", \"14679910\"]}");
add("13634034", "{\"term\":\"steradian\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634034\"]}");
add("13634186", "{\"term\":\"sq in\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634186\"]}");
add("13634186", "{\"term\":\"square inch\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634186\"]}");
add("13634303", "{\"term\":\"sq ft\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634303\"]}");
add("13634303", "{\"term\":\"square foot\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634303\"]}");
add("13634420", "{\"term\":\"sq yd\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634420\"]}");
add("13634420", "{\"term\":\"square yard\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634420\"]}");
add("13634537", "{\"term\":\"centare\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634537\"]}");
add("13634537", "{\"term\":\"square meter\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634537\"]}");
add("13634537", "{\"term\":\"square metre\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634537\"]}");
add("13634689", "{\"term\":\"square mile\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634689\"]}");
add("13634785", "{\"term\":\"section\", \"synsetCount\":14, \"upperType\":\"NOUN\", \"ids\":[\"00679253\", \"07763431\", \"08131836\", \"08233716\", \"08233821\", \"08256073\", \"08665728\", \"13634785\", \"05876035\", \"08231753\", \"04172050\", \"08665897\", \"09451645\", \"06403644\"]}");
add("13634873", "{\"term\":\"quarter section\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13634873\"]}");
add("13635023", "{\"term\":\"acre\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"08811162\", \"08873717\", \"13635023\"]}");
add("13635143", "{\"term\":\"ar\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"09081737\", \"13635143\", \"14653098\"]}");
add("13635143", "{\"term\":\"are\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13635143\"]}");
add("13635266", "{\"term\":\"hectare\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13635266\"]}");
add("13635424", "{\"term\":\"arpent\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13635424\"]}");
add("13635537", "{\"term\":\"b\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"05408321\", \"06844334\", \"13635537\", \"13735626\", \"14656049\", \"15115309\", \"01352589\"]}");
add("13635537", "{\"term\":\"barn\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13635537\", \"02796518\"]}");
add("13635748", "{\"term\":\"dessiatine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13635748\"]}");
add("13635853", "{\"term\":\"morgen\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13635853\"]}");
add("13635960", "{\"term\":\"perch\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"02558494\", \"02559477\", \"07796149\", \"08644333\", \"13635960\", \"13672539\", \"03921038\"]}");
add("13635960", "{\"term\":\"pole\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"03983318\", \"03983516\", \"04420286\", \"08638456\", \"08638674\", \"13635960\", \"13672539\", \"05959426\", \"09746969\", \"03983015\"]}");
add("13635960", "{\"term\":\"rod\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"03432112\", \"05464032\", \"13635960\", \"13672539\", \"01380243\", \"04107268\"]}");
add("13636045", "{\"term\":\"liquid measure\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13636045\"]}");
add("13636045", "{\"term\":\"liquid unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13636045\"]}");
add("13636317", "{\"term\":\"dry measure\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13636317\"]}");
add("13636317", "{\"term\":\"dry unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13636317\"]}");
add("13636516", "{\"term\":\"united states liquid unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13636516\"]}");
add("13636838", "{\"term\":\"british capacity unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13636838\"]}");
add("13636838", "{\"term\":\"imperial capacity unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13636838\"]}");
add("13637335", "{\"term\":\"metric capacity unit\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13637335\"]}");
add("13637621", "{\"term\":\"ardeb\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13637621\"]}");
add("13637708", "{\"term\":\"arroba\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13637708\", \"13739724\"]}");
add("13637841", "{\"term\":\"bath\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"08898429\", \"13637841\", \"00258637\", \"02809715\"]}");
add("13637969", "{\"term\":\"cran\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13637969\"]}");
add("13638068", "{\"term\":\"epha\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638068\"]}");
add("13638068", "{\"term\":\"ephah\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638068\"]}");
add("13638207", "{\"term\":\"field capacity\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638207\"]}");
add("13638327", "{\"term\":\"homer\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"01817562\", \"11077543\", \"13638327\", \"11077376\", \"00133175\"]}");
add("13638327", "{\"term\":\"kor\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638327\"]}");
add("13638488", "{\"term\":\"hin\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638488\"]}");
add("13638589", "{\"term\":\"fathom\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13638589\", \"13682290\"]}");
add("13638589", "{\"term\":\"fthm\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13638589\", \"13682290\"]}");
add("13638749", "{\"term\":\"acre-foot\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638749\"]}");
add("13638911", "{\"term\":\"acre inch\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638911\"]}");
add("13638994", "{\"term\":\"board measure\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13638994\"]}");
add("13639116", "{\"term\":\"board foot\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13639116\"]}");
add("13639233", "{\"term\":\"standard\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"04308278\", \"04308380\", \"13394387\", \"13639233\", \"05933552\", \"07275291\"]}");
add("13639357", "{\"term\":\"cubic yard\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13639357\"]}");
add("13639357", "{\"term\":\"yard\", \"synsetCount\":9, \"upperType\":\"NOUN\", \"ids\":[\"04617860\", \"04618033\", \"04618511\", \"08702414\", \"13639357\", \"13772984\", \"08702032\", \"04618236\", \"13672065\"]}");
add("13639461", "{\"term\":\"last\", \"synsetCount\":8, \"upperType\":\"NOUN\", \"ids\":[\"03649846\", \"07306517\", \"13639461\", \"13740283\", \"15168236\", \"01267160\", \"13872345\", \"15292365\"]}");
add("13639579", "{\"term\":\"mutchkin\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13639579\"]}");
add("13639699", "{\"term\":\"oka\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"12724801\", \"13639699\", \"13740679\"]}");
add("13639789", "{\"term\":\"minim\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"06883894\", \"13639789\", \"13642292\"]}");
add("13639910", "{\"term\":\"drachm\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"13639910\", \"13642471\", \"13744445\"]}");
add("13639910", "{\"term\":\"fluid drachm\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13639910\", \"13642471\"]}");
add("13639910", "{\"term\":\"fluid dram\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13639910\", \"13642471\"]}");
add("13639910", "{\"term\":\"fluidram\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"13639910\", \"13642471\"]}");
} private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } }
|
package com.o19s.solr.swan;
/**
* Copyright 2012 OpenSource Connections, LLC.
*
* 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.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.common.params.SolrParams;
import com.google.common.collect.ListMultimap;
import com.o19s.solr.swan.nodes.SwanAdjNode;
import com.o19s.solr.swan.nodes.SwanNode;
import com.o19s.solr.swan.nodes.SwanOperatorNode;
import com.o19s.solr.swan.nodes.SwanPhraseNode;
import com.o19s.solr.swan.nodes.SwanRangeNode;
import com.o19s.solr.swan.nodes.SwanTermNode;
import brs.parser.nodes.SwanCOMNode;
import brs.parser.nodes.SwanEOperationNode;
import brs.parser.nodes.SwanMesmoNode;
import brs.parser.nodes.SwanNAONode;
import brs.parser.nodes.SwanOUOperationNode;
import brs.parser.nodes.SwanPROXNode;
import brs.parser.nodes.SwanXOUOperationNode;
public class LuceneSwanSearcher implements ISwanSearcher<SwanNode> {
private static String defaultOp = "adj";
private static String stemSuffix = "_stem";
private ListMultimap<String, String> _fieldAliases;
public LuceneSwanSearcher(SolrParams params, ListMultimap<String, String> fieldAliases) {
_fieldAliases = fieldAliases;
SwanNode.setParams(params);
String defOpStr = params.get("q.op");
if (defOpStr != null) {
defaultOp = defOpStr.toLowerCase();
}
}
/*@Override
public SwanNode or(SwanNode left, SwanNode right) {
// This clause says if left is an OR condition, add right as an additional
// OR in the same scope.
// example if left = (X OR Y), and right = (Z), we will return (X OR Y OR Z)
// If left or right have different fields, they should fall out of this and
// result in (X OR Y) OR (Z) so the different fields can be used
if (left instanceof SwanOrOperationNode
&& nodesAreUnfieldedOrHaveSameFields(left.getField(), right.getField())) {
((SwanOrOperationNode) left).add(right);
return left;
}
return new SwanOrOperationNode(left, right);
}
@Override
public SwanNode xor(SwanNode left, SwanNode right) {
if (left instanceof SwanXOrOperationNode && !left.isWrapped()) {
((SwanXOrOperationNode) left).add(right);
return left;
}
return new SwanXOrOperationNode(left, right);
}
@Override
public SwanNode and(SwanNode left, SwanNode right) {
if (left instanceof SwanAndOperationNode) {
((SwanAndOperationNode) left).add(right);
return left;
}
return new SwanAndOperationNode(left, right);
}
@Override
public SwanNode same(SwanNode left, SwanNode right, int n) {
return new SwanSameNode(left, right, n);
}
@Override
public SwanNode with(SwanNode left, SwanNode right, int n) {
return new SwanWithNode(left, right, n);
}
@Override
public SwanNode near(SwanNode left, SwanNode right, int n) {
return new SwanNearNode(left, right, n);
}
*/
@Override
public SwanNode adj(SwanNode left, SwanNode right, int n) {
return new SwanAdjNode(left, right, n);
}
@Override
public SwanNode defaultOp(SwanNode left, SwanNode right) {
Class[] unamenableToSwan = new Class[] { SwanRangeNode.class };
boolean swanSafe = true;
for (Class c : unamenableToSwan) {
if ((c == left.getClass()) || (c == right.getClass())) {
swanSafe = false;
break;
}
}
// TODO: Figure out what this is for
// System.out.println("In LSS.dO, "+ left.getClass() +" --- "+ right.getClass() );
//if (defaultOp.equals("same") && swanSafe) {
//return same(left, right, 1);
//} else
if (defaultOp.equals("mesmo") && swanSafe) {
return mesmo(left, right, 1);
}
//else if (defaultOp.equals("with") && swanSafe) {
//return with(left, right, 1);
//}
else if (defaultOp.equals("com") && swanSafe) {
return com(left, right, 1);
} else if (defaultOp.equals("adj") && swanSafe) {
return adj(left, right, 1);
}
//else if (defaultOp.equals("near") && swanSafe) {
//return near(left, right, 1);
//}
else if (defaultOp.equals("prox") && swanSafe) {
return prox(left, right, 1);
}
//else if (defaultOp.equals("and") || !swanSafe) { // <-- defaults to AND if not swanSafe
//return and(left, right);
//}
else if (defaultOp.equals("e") || !swanSafe) {
return e(left, right);
}
//else if (defaultOp.equals("or")) {
//return or(left, right);
//}
else if (defaultOp.equals("ou")) {
return ou(left, right);
} else {
throw new UnsupportedOperationException(
"Default operator may only be on of MESMO, COM, ADJ, PROX, E, OU. Was suplied with " + defaultOp);
}
}
@Override
public SwanNode term(String match) {
return new SwanTermNode(match);
}
@Override
public SwanNode phrase(String match) {
return new SwanPhraseNode(match);
}
@Override
public SwanNode range(String field, String op1, String val1) {
if (_fieldAliases.containsKey(field.toLowerCase())) {
return new SwanRangeNode(_fieldAliases.get(field.toLowerCase()).get(0), op1, val1);
}
return new SwanRangeNode(field, op1, val1);
}
@Override
public SwanNode classRange(String field, String mainClassification, String subClassification1,
String subClassification2) {
return new SwanRangeNode(field, ">=", mainClassification + "/" + subClassification1, "<=",
mainClassification + "/" + subClassification2);
}
@Override
public SwanNode boundRange(String field, String op1, String val1, String op2, String val2) {
if (_fieldAliases.containsKey(field.toLowerCase())) {
return new SwanRangeNode(_fieldAliases.get(field.toLowerCase()).get(0), op1, val1, op2, val2);
}
return new SwanRangeNode(field, op1, val1, op2, val2);
}
@Override
public SwanNode fieldedSubExpressions(String field, SwanNode expression) {
if (expression instanceof SwanOperatorNode) {
for (SwanNode node : ((SwanOperatorNode) expression).getNodes()) {
fieldedSubExpressions(field, node);
}
} else {
fieldedExpression(field, expression);
}
return expression;
}
@Override
public SwanNode fieldedExpression(String field, SwanNode expression) {
field = field.toLowerCase();
if (SwanNode.isFieldStemming()) {
field = field.concat(stemSuffix);
}
if (_fieldAliases.containsKey(field)) {
try {
return getFieldAliasExpression(_fieldAliases.get(field), expression);
} catch (Exception ex) {
// need to do something here. Log? pass the exception on?
}
}
expression.setField(field);
return expression;
}
private SwanNode getFieldAliasExpression(List<String> fields, SwanNode originalExpression)
throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
if (fields.size() == 1) {
originalExpression.setField(fields.get(0));
return originalExpression;
}
// set up 'or' conditions between all of the fields if there are more than one
SwanNode aggregatedExpression = null;
for (String field : fields) {
if (field != null) {
// use copy constructor to make a copy of the original expression
SwanNode newExpression = originalExpression.getClass().getConstructor(originalExpression.getClass())
.newInstance(originalExpression);
newExpression.setField(field);
if (aggregatedExpression != null) {
//TODO: verificar ou / or
aggregatedExpression = ou(aggregatedExpression, newExpression);
} else {
aggregatedExpression = newExpression;
}
}
}
return aggregatedExpression;
}
private boolean nodesAreUnfieldedOrHaveSameFields(String firstField, String secondField) {
return ((StringUtils.isBlank(firstField) || StringUtils.isBlank(secondField))
|| (StringUtils.equals(firstField, secondField)));
}
@Override
public SwanNode wrap(SwanNode peek) {
peek.setWrapped();
return peek;
}
@Override
public SwanNode mesmo(SwanNode left, SwanNode right, int n) {
return new SwanMesmoNode(left, right, n);
}
@Override
public SwanNode prox(SwanNode left, SwanNode right, int n) {
return new SwanPROXNode(left, right, n);
}
@Override
public SwanNode e(SwanNode left, SwanNode right) {
if (left instanceof SwanEOperationNode) {
((SwanEOperationNode) left).add(right);
return left;
}
return new SwanEOperationNode(left, right);
}
@Override
public SwanNode xou(SwanNode left, SwanNode right) {
if (left instanceof SwanXOUOperationNode && !left.isWrapped()) {
((SwanXOUOperationNode) left).add(right);
return left;
}
return new SwanXOUOperationNode(left, right);
}
@Override
public SwanNode com(SwanNode left, SwanNode right, int n) {
return new SwanCOMNode(left, right, n);
}
@Override
public SwanNode nao(SwanNode left, SwanNode right) {
return new SwanNAONode(left, right);
}
@Override
public SwanNode ou(SwanNode left, SwanNode right) {
if (left instanceof SwanOUOperationNode
&& nodesAreUnfieldedOrHaveSameFields(left.getField(), right.getField())) {
((SwanOUOperationNode) left).add(right);
return left;
}
return new SwanOUOperationNode(left, right);
}
}
|
package com.suda.jzapp.manager.domain;
import java.util.Calendar;
import java.util.Date;
/**
* Created by suda on 2016/8/13.
*/
public class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public Date getDate() {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
//Log.d("@@@@@getDate", c.getTimeInMillis() + "");
return c.getTime();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.loader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.tomcat.util.http.fileupload.FileUtils;
public class TestWebappClassLoaderWeaving extends TomcatBaseTest {
private static final String PACKAGE_PREFIX = "org/apache/catalina/loader";
private static String WEBAPP_DOC_BASE;
@BeforeClass
public static void setUpClass() throws Exception {
WEBAPP_DOC_BASE = System.getProperty("java.io.tmpdir") + "/TestWebappClassLoaderWeaving";
File classes = new File(WEBAPP_DOC_BASE + "/WEB-INF/classes/" + PACKAGE_PREFIX);
classes.mkdirs();
copyResource(PACKAGE_PREFIX + "/TesterNeverWeavedClass.class", new File(classes, "TesterNeverWeavedClass.class"));
copyResource(PACKAGE_PREFIX + "/TesterUnweavedClass.class", new File(classes, "TesterUnweavedClass.class"));
}
@AfterClass
public static void tearDownClass() throws Exception {
FileUtils.deleteDirectory(new File(WEBAPP_DOC_BASE));
}
private Tomcat tomcat;
private Context context;
private WebappClassLoader loader;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
this.tomcat = getTomcatInstance();
this.context = this.tomcat.addContext("/weaving", WEBAPP_DOC_BASE);
this.tomcat.start();
ClassLoader loader = this.context.getLoader().getClassLoader();
assertNotNull("The class loader should not be null.", loader);
assertSame("The class loader is not correct.", WebappClassLoader.class, loader.getClass());
this.loader = (WebappClassLoader) loader;
}
@After
@Override
public void tearDown() throws Exception {
try {
this.loader = null;
this.context.stop();
this.tomcat.getHost().removeChild(this.context);
this.context = null;
} finally {
super.tearDown();
}
}
@Test
public void testNoWeaving() throws Exception {
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Unweaved World!", result);
}
@Test
public void testAddingNullTransformerThrowsException() throws Exception {
try {
this.loader.addTransformer(null);
fail("Expected exception IllegalArgumentException, got no exception.");
} catch (IllegalArgumentException ignore) {
}
// class loading should still work, no weaving
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Unweaved World!", result);
}
@Test
public void testAddedTransformerInstrumentsClass1() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #1!", result);
}
@Test
public void testAddedTransformerInstrumentsClass2() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
}
@Test
public void testTransformersExecuteInOrderAdded1() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
}
@Test
public void testTransformersExecuteInOrderAdded2() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #1!", result);
}
@Test
public void testRemovedTransformerNoLongerInstruments1() throws Exception {
ReplacementTransformer removed = new ReplacementTransformer(WEAVED_REPLACEMENT_1);
this.loader.addTransformer(removed);
this.loader.removeTransformer(removed);
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Unweaved World!", result);
}
@Test
public void testRemovedTransformerNoLongerInstruments2() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
ReplacementTransformer removed = new ReplacementTransformer(WEAVED_REPLACEMENT_2);
this.loader.addTransformer(removed);
this.loader.removeTransformer(removed);
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #1!", result);
}
@Test
public void testRemovedTransformerNoLongerInstruments3() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
ReplacementTransformer removed = new ReplacementTransformer(WEAVED_REPLACEMENT_1);
this.loader.addTransformer(removed);
this.loader.removeTransformer(removed);
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
}
@SuppressWarnings("deprecation")
@Test
public void testCopiedClassLoaderExcludesResourcesAndTransformers() throws Exception {
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_1));
this.loader.addTransformer(new ReplacementTransformer(WEAVED_REPLACEMENT_2));
String result = invokeDoMethodOnClass(this.loader, "TesterNeverWeavedClass");
assertEquals("The first result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(this.loader, "TesterUnweavedClass");
assertEquals("The second result is not correct.", "Hello, Weaver #2!", result);
WebappClassLoader copiedLoader = this.loader.copyWithoutTransformers();
result = invokeDoMethodOnClass(copiedLoader, "TesterNeverWeavedClass");
assertEquals("The third result is not correct.", "This will never be weaved.", result);
result = invokeDoMethodOnClass(copiedLoader, "TesterUnweavedClass");
assertEquals("The fourth result is not correct.", "Hello, Unweaved World!", result);
assertEquals("getAntiJARLocking did not match.", Boolean.valueOf(this.loader.getAntiJARLocking()), Boolean.valueOf(copiedLoader.getAntiJARLocking()));
assertEquals("getClearReferencesHttpClientKeepAliveThread did not match.", Boolean.valueOf(this.loader.getClearReferencesHttpClientKeepAliveThread()), Boolean.valueOf(copiedLoader.getClearReferencesHttpClientKeepAliveThread()));
assertEquals("getClearReferencesLogFactoryRelease did not match.", Boolean.valueOf(this.loader.getClearReferencesLogFactoryRelease()), Boolean.valueOf(copiedLoader.getClearReferencesLogFactoryRelease()));
assertEquals("getClearReferencesStatic did not match.", Boolean.valueOf(this.loader.getClearReferencesStatic()), Boolean.valueOf(copiedLoader.getClearReferencesStatic()));
assertEquals("getClearReferencesStopThreads did not match.", Boolean.valueOf(this.loader.getClearReferencesStopThreads()), Boolean.valueOf(copiedLoader.getClearReferencesStopThreads()));
assertEquals("getClearReferencesStopTimerThreads did not match.", Boolean.valueOf(this.loader.getClearReferencesStopTimerThreads()), Boolean.valueOf(copiedLoader.getClearReferencesStopTimerThreads()));
assertEquals("getContextName did not match.", this.loader.getContextName(), copiedLoader.getContextName());
assertEquals("getDelegate did not match.", Boolean.valueOf(this.loader.getDelegate()), Boolean.valueOf(copiedLoader.getDelegate()));
assertEquals("getJarPath did not match.", this.loader.getJarPath(), copiedLoader.getJarPath());
assertEquals("getURLs did not match.", this.loader.getURLs().length, copiedLoader.getURLs().length);
assertSame("getParent did not match.", this.loader.getParent(), copiedLoader.getParent());
}
private static void copyResource(String name, File file) throws Exception {
InputStream is = TestWebappClassLoaderWeaving.class.getClassLoader().getResourceAsStream(name);
if (is == null) {
throw new IOException("Resource " + name + " not found on classpath.");
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
for (int b = is.read(); b >= 0; b = is.read()) {
os.write(b);
}
} finally {
try {
is.close();
} catch (IOException e1) {
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
}
private static String invokeDoMethodOnClass(WebappClassLoaderBase loader, String className) throws Exception {
Class<?> c = loader.findClass("org.apache.catalina.loader." + className);
assertNotNull("The loaded class should not be null.", c);
Method m = c.getMethod("doMethod");
Object o = c.newInstance();
return (String) m.invoke(o);
}
private static class ReplacementTransformer implements ClassFileTransformer {
private static final String CLASS_TO_WEAVE = PACKAGE_PREFIX + "/TesterUnweavedClass";
private final byte[] replacement;
ReplacementTransformer(byte[] replacement) {
this.replacement = replacement;
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> x, ProtectionDomain y, byte[] b) {
if (CLASS_TO_WEAVE.equals(className)) {
return this.replacement;
}
return null;
}
}
/**
* Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that
* the doMethod method returns "Hello, Weaver #1!". Compiled with Oracle Java 1.6.0_51.
*/
private static final byte[] WEAVED_REPLACEMENT_1 = new byte[] { -54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100, 111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1, 0, 24, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, 0, 5, 0, 6, 1, 0, 17, 72, 101, 108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 49, 33, 1, 0, 46, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108, 111, 97, 100, 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0, 0, 3, 18, 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0, 2, 0, 12 };
/**
* Compiled version of org.apache.catalina.loader.TesterUnweavedClass, except that
* the doMethod method returns "Hello, Weaver #2!". Compiled with Oracle Java 1.6.0_51.
*/
private static final byte[] WEAVED_REPLACEMENT_2 = new byte[] { -54, -2, -70, -66, 0, 0, 0, 50, 0, 17, 10, 0, 4, 0, 13, 8, 0, 14, 7, 0, 15, 7, 0, 16, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 8, 100, 111, 77, 101, 116, 104, 111, 100, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1, 0, 24, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 46, 106, 97, 118, 97, 12, 0, 5, 0, 6, 1, 0, 17, 72, 101, 108, 108, 111, 44, 32, 87, 101, 97, 118, 101, 114, 32, 35, 50, 33, 1, 0, 46, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47, 99, 97, 116, 97, 108, 105, 110, 97, 47, 108, 111, 97, 100, 101, 114, 47, 84, 101, 115, 116, 101, 114, 85, 110, 119, 101, 97, 118, 101, 100, 67, 108, 97, 115, 115, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 0, 33, 0, 3, 0, 4, 0, 0, 0, 0, 0, 2, 0, 1, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 1, -79, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 19, 0, 1, 0, 9, 0, 10, 0, 1, 0, 7, 0, 0, 0, 27, 0, 1, 0, 1, 0, 0, 0, 3, 18, 2, -80, 0, 0, 0, 1, 0, 8, 0, 0, 0, 6, 0, 1, 0, 0, 0, 22, 0, 1, 0, 11, 0, 0, 0, 2, 0, 12 };
/*
* The WEAVED_REPLACEMENT_1 and WEAVED_REPLACEMENT_2 field contents are generated using the
* following code. To regenerate them, alter the TesterUnweavedClass code as desired, recompile,
* and run this main method.
*/
public static void main(String... arguments) throws Exception {
InputStream input = TestWebappClassLoaderWeaving.class.getClassLoader().getResourceAsStream("org/apache/catalina/loader/TesterUnweavedClass.class");
StringBuilder builder = new StringBuilder();
builder.append(" ");
System.out.println(" private static final byte[] WEAVED_REPLACEMENT_1 = new byte[] {");
try {
for (int i = 0, b = input.read(); b >= 0; i++, b = input.read()) {
String value = "" + ((byte) b);
if (builder.length() + value.length() > 97) {
builder.append(",");
System.out.println(builder.toString());
builder = new StringBuilder();
builder.append(" ").append(value);
} else {
if (i > 0) {
builder.append(", ");
}
builder.append(value);
}
}
System.out.println(builder.toString());
} finally {
input.close();
}
System.out.println(" }");
}
}
|
package com.termux.shared.crash;
import android.content.Context;
import androidx.annotation.NonNull;
import com.termux.shared.file.FileUtils;
import com.termux.shared.logger.Logger;
import com.termux.shared.markdown.MarkdownUtils;
import com.termux.shared.errors.Error;
import com.termux.shared.android.AndroidUtils;
import java.nio.charset.Charset;
/**
* Catches uncaught exceptions and logs them.
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private final Context mContext;
private final CrashHandlerClient mCrashHandlerClient;
private final Thread.UncaughtExceptionHandler defaultUEH;
private static final String LOG_TAG = "CrashUtils";
private CrashHandler(@NonNull final Context context, @NonNull final CrashHandlerClient crashHandlerClient) {
this.mContext = context;
this.mCrashHandlerClient = crashHandlerClient;
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
Logger.logInfo(LOG_TAG, "uncaughtException() for " + thread + ": " + throwable.getMessage());
logCrash(thread, throwable);
defaultUEH.uncaughtException(thread, throwable);
}
/**
* Set default uncaught crash handler of current thread to {@link CrashHandler}.
*/
public static void setCrashHandler(@NonNull final Context context, @NonNull final CrashHandlerClient crashHandlerClient) {
if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CrashHandler)) {
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(context, crashHandlerClient));
}
}
/**
* Log a crash in the crash log file at path returned by {@link CrashHandlerClient#getCrashLogFilePath(Context)}.
*
* @param context The {@link Context} for operations.
* @param crashHandlerClient The {@link CrashHandlerClient} implementation.
* @param thread The {@link Thread} in which the crash happened.
* @param throwable The {@link Throwable} thrown for the crash.
*/
public static void logCrash(@NonNull Context context,
@NonNull CrashHandlerClient crashHandlerClient,
@NonNull Thread thread, @NonNull Throwable throwable) {
Logger.logInfo(LOG_TAG, "logCrash() for " + thread + ": " + throwable.getMessage());
new CrashHandler(context, crashHandlerClient).logCrash(thread, throwable);
}
public void logCrash(@NonNull Thread thread, @NonNull Throwable throwable) {
if (!mCrashHandlerClient.onPreLogCrash(mContext, thread, throwable)) {
logCrashToFile(mContext, mCrashHandlerClient, thread, throwable);
mCrashHandlerClient.onPostLogCrash(mContext, thread, throwable);
}
}
public void logCrashToFile(@NonNull Context context,
@NonNull CrashHandlerClient crashHandlerClient,
@NonNull Thread thread, @NonNull Throwable throwable) {
StringBuilder reportString = new StringBuilder();
reportString.append("## Crash Details\n");
reportString.append("\n").append(MarkdownUtils.getSingleLineMarkdownStringEntry("Crash Thread", thread.toString(), "-"));
reportString.append("\n").append(MarkdownUtils.getSingleLineMarkdownStringEntry("Crash Timestamp", AndroidUtils.getCurrentMilliSecondUTCTimeStamp(), "-"));
reportString.append("\n\n").append(MarkdownUtils.getMultiLineMarkdownStringEntry("Crash Message", throwable.getMessage(), "-"));
reportString.append("\n\n").append(Logger.getStackTracesMarkdownString("Stacktrace", Logger.getStackTracesStringArray(throwable)));
String appInfoMarkdownString = crashHandlerClient.getAppInfoMarkdownString(context);
if (appInfoMarkdownString != null && !appInfoMarkdownString.isEmpty())
reportString.append("\n\n").append(appInfoMarkdownString);
reportString.append("\n\n").append(AndroidUtils.getDeviceInfoMarkdownString(context));
// Log report string to logcat
Logger.logError(reportString.toString());
// Write report string to crash log file
Error error = FileUtils.writeTextToFile("crash log", crashHandlerClient.getCrashLogFilePath(context),
Charset.defaultCharset(), reportString.toString(), false);
if (error != null) {
Logger.logErrorExtended(LOG_TAG, error.toString());
}
}
public interface CrashHandlerClient {
/**
* Called before {@link #logCrashToFile(Context, CrashHandlerClient, Thread, Throwable)} is called.
*
* @param context The {@link Context} passed to {@link CrashHandler#CrashHandler(Context, CrashHandlerClient)}.
* @param thread The {@link Thread} in which the crash happened.
* @param throwable The {@link Throwable} thrown for the crash.
* @return Should return {@code true} if crash has been handled and should not be logged,
* otherwise {@code false}.
*/
boolean onPreLogCrash(Context context, Thread thread, Throwable throwable);
/**
* Called after {@link #logCrashToFile(Context, CrashHandlerClient, Thread, Throwable)} is called.
*
* @param context The {@link Context} passed to {@link CrashHandler#CrashHandler(Context, CrashHandlerClient)}.
* @param thread The {@link Thread} in which the crash happened.
* @param throwable The {@link Throwable} thrown for the crash.
*/
void onPostLogCrash(Context context, Thread thread, Throwable throwable);
/**
* Get crash log file path.
*
* @param context The {@link Context} passed to {@link CrashHandler#CrashHandler(Context, CrashHandlerClient)}.
* @return Should return the crash log file path.
*/
@NonNull
String getCrashLogFilePath(Context context);
/**
* Get app info markdown string to add to crash log.
*
* @param context The {@link Context} passed to {@link CrashHandler#CrashHandler(Context, CrashHandlerClient)}.
* @return Should return app info markdown string.
*/
String getAppInfoMarkdownString(Context context);
}
}
|
/**
* Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.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.stylefeng.guns.core.util;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
public class DateUtil {
public static final long ONE_DAY_TIME = 24 * 3600 * 1000L;
public static long getCurrTime2OneDayEnd() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis() - System.currentTimeMillis();
}
public static Date getOneDayBegin(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
public static Date getOneDayEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 获取YYYY格式
*
* @return
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 获取YYYY格式
*
* @return
*/
public static String getYear(Date date) {
return formatDate(date, "yyyy");
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDay() {
return formatDate(new Date(), "yyyy-MM-dd");
}
public static int getDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
public static String getDayStrOfWeek(Date date) {
int day = getDayOfWeek(date);
switch (day) {
case 1:
return "星期天";
case 2:
return "星期一";
case 3:
return "星期二";
case 4:
return "星期三";
case 5:
return "星期四";
case 6:
return "星期五";
case 7:
return "星期六";
default:
return "";
}
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDayAndTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDay(Date date) {
return formatDate(date, "yyyy-MM-dd");
}
/**
* 获取YYYYMMDD格式
*
* @return
*/
public static String getDays() {
return formatDate(new Date(), "yyyyMMdd");
}
/**
* 获取YYYYMMDD格式
*
* @return
*/
public static String getDays(Date date) {
return formatDate(date, "yyyyMMdd");
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
*
* @return
*/
public static String getTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 获取YYYY-MM-DD HH:mm:ss.SSS格式
*
* @return
*/
public static String getMsTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
}
/**
* 获取YYYYMMDDHHmmss格式
*
* @return
*/
public static String getAllTime() {
return formatDate(new Date(), "yyyyMMddHHmmss");
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
*
* @return
*/
public static String getTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
public static String formatDate(Date date, String pattern) {
String formatDate = null;
if (StringUtils.isNotBlank(pattern)) {
formatDate = DateFormatUtils.format(date, pattern);
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* @Title: compareDate
* @Description:(日期比较,如果s>=e 返回true 否则返回false)
* @param s
* @param e
* @return boolean
* @throws @author
* luguosui
*/
public static boolean compareDate(String s, String e) {
if (parseDate(s) == null || parseDate(e) == null) {
return false;
}
return parseDate(s).getTime() >= parseDate(e).getTime();
}
/**
* 格式化日期
*
* @return
*/
public static Date parseDate(String date) {
return parse(date, "yyyy-MM-dd");
}
/**
* 格式化日期
*
* @return
*/
public static Date parseTime(String date) {
return parse(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 格式化日期
*
* @return
*/
public static Date parse(String date, String pattern) {
try {
return DateUtils.parseDate(date, pattern);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 格式化日期
*
* @return
*/
public static String format(Date date, String pattern) {
return DateFormatUtils.format(date, pattern);
}
/**
* 把日期转换为Timestamp
*
* @param date
* @return
*/
public static Timestamp format(Date date) {
return new Timestamp(date.getTime());
}
/**
* 校验日期是否合法
*
* @return
*/
public static boolean isValidDate(String s) {
return parse(s, "yyyy-MM-dd HH:mm:ss") != null;
}
/**
* 校验日期是否合法
*
* @return
*/
public static boolean isValidDate(String s, String pattern) {
return parse(s, pattern) != null;
}
public static int getDiffYear(String startTime, String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(startTime).getTime()) / ONE_DAY_TIME) / 365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return 0;
}
}
/**
* <li>功能描述:时间相减得到天数
*
* @param beginDateStr
* @param endDateStr
* @return long
* @author Administrator
*/
public static long getDaySub(String beginDateStr, String endDateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate = format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return getDaySub(beginDate, endDate);
}
/**
* <li>功能描述:时间相减得到天数
*
* @param beginDateStr
* @param endDateStr
* @return long
* @author Administrator
*/
public static long getDaySub(Date beginDate, Date endDate) {
return (endDate.getTime() - beginDate.getTime()) / ONE_DAY_TIME;
}
public static Date[] getQueryDate(Date date) {
Date[] result = new Date[2];
long time = date.getTime() / ONE_DAY_TIME * ONE_DAY_TIME - 8 * 3600 * 1000L;
result[0] = new Date(time);
result[1] = new Date(time + ONE_DAY_TIME);
return result;
}
/**
* 得到n天之后的日期
*
* @param days
* @return
*/
public static String getAfterDayDate(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后的日期
*
* @param days
* @return
*/
public static Date getAfterDayDate(Date date, int day) {
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, day); // 日期减 如果不够减会将月变动
return canlendar.getTime();
}
/**
* 得到n天之后是周几
*
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
public static java.sql.Date[] getCurrMonthDay(int month) {
java.sql.Date[] result = new java.sql.Date[2];
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
result[0] = new java.sql.Date(calendar.getTimeInMillis() / ONE_DAY_TIME * ONE_DAY_TIME - 8 * 3600 * 1000L);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
result[1] = new java.sql.Date(calendar.getTimeInMillis() / ONE_DAY_TIME * ONE_DAY_TIME - 8 * 3600 * 1000L);
return result;
}
/**
* 获取最近n个月的起止时间
* @param n
* @return
*/
public static java.sql.Date[] getRecentlyMonthDay(int n) {
java.sql.Date[] result = new java.sql.Date[2];
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
result[1] = new java.sql.Date(calendar.getTimeInMillis());
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1 - n);
result[0] = new java.sql.Date(calendar.getTimeInMillis());
return result;
}
/**
* 获取最近n个月的起止时间
* @param n
* @return
*/
public static List<String> getRecentlyMonthDayStr(int n, String pattern) {
pattern = StringUtil.isNullEmpty(pattern) ? "yyyy-MM" : pattern;
java.sql.Date[] result = getRecentlyMonthDay(n);
return Arrays.asList(format(result[0], "yyyy-MM"), format(result[1], "yyyy-MM"));
}
}
|
package ru.job4j.jchess;
public class OccupiedWayException extends Exception {
}
|
/*
* Copyright 2020 Google LLC
*
* 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 com.google.ads.googleads.v6.services.stub;
import com.google.ads.googleads.v6.resources.ExtensionFeedItem;
import com.google.ads.googleads.v6.services.GetExtensionFeedItemRequest;
import com.google.ads.googleads.v6.services.MutateExtensionFeedItemsRequest;
import com.google.ads.googleads.v6.services.MutateExtensionFeedItemsResponse;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.RequestParamsExtractor;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.common.collect.ImmutableMap;
import com.google.longrunning.stub.GrpcOperationsStub;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the ExtensionFeedItemService service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class GrpcExtensionFeedItemServiceStub extends ExtensionFeedItemServiceStub {
private static final MethodDescriptor<GetExtensionFeedItemRequest, ExtensionFeedItem>
getExtensionFeedItemMethodDescriptor =
MethodDescriptor.<GetExtensionFeedItemRequest, ExtensionFeedItem>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.ads.googleads.v6.services.ExtensionFeedItemService/GetExtensionFeedItem")
.setRequestMarshaller(
ProtoUtils.marshaller(GetExtensionFeedItemRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(ExtensionFeedItem.getDefaultInstance()))
.build();
private static final MethodDescriptor<
MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse>
mutateExtensionFeedItemsMethodDescriptor =
MethodDescriptor
.<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.ads.googleads.v6.services.ExtensionFeedItemService/MutateExtensionFeedItems")
.setRequestMarshaller(
ProtoUtils.marshaller(MutateExtensionFeedItemsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(MutateExtensionFeedItemsResponse.getDefaultInstance()))
.build();
private final UnaryCallable<GetExtensionFeedItemRequest, ExtensionFeedItem>
getExtensionFeedItemCallable;
private final UnaryCallable<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse>
mutateExtensionFeedItemsCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcExtensionFeedItemServiceStub create(
ExtensionFeedItemServiceStubSettings settings) throws IOException {
return new GrpcExtensionFeedItemServiceStub(settings, ClientContext.create(settings));
}
public static final GrpcExtensionFeedItemServiceStub create(ClientContext clientContext)
throws IOException {
return new GrpcExtensionFeedItemServiceStub(
ExtensionFeedItemServiceStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcExtensionFeedItemServiceStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcExtensionFeedItemServiceStub(
ExtensionFeedItemServiceStubSettings.newBuilder().build(), clientContext, callableFactory);
}
protected GrpcExtensionFeedItemServiceStub(
ExtensionFeedItemServiceStubSettings settings, ClientContext clientContext)
throws IOException {
this(settings, clientContext, new GrpcExtensionFeedItemServiceCallableFactory());
}
protected GrpcExtensionFeedItemServiceStub(
ExtensionFeedItemServiceStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<GetExtensionFeedItemRequest, ExtensionFeedItem>
getExtensionFeedItemTransportSettings =
GrpcCallSettings.<GetExtensionFeedItemRequest, ExtensionFeedItem>newBuilder()
.setMethodDescriptor(getExtensionFeedItemMethodDescriptor)
.setParamsExtractor(
new RequestParamsExtractor<GetExtensionFeedItemRequest>() {
@Override
public Map<String, String> extract(GetExtensionFeedItemRequest request) {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("resource_name", String.valueOf(request.getResourceName()));
return params.build();
}
})
.build();
GrpcCallSettings<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse>
mutateExtensionFeedItemsTransportSettings =
GrpcCallSettings
.<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse>newBuilder()
.setMethodDescriptor(mutateExtensionFeedItemsMethodDescriptor)
.setParamsExtractor(
new RequestParamsExtractor<MutateExtensionFeedItemsRequest>() {
@Override
public Map<String, String> extract(MutateExtensionFeedItemsRequest request) {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("customer_id", String.valueOf(request.getCustomerId()));
return params.build();
}
})
.build();
this.getExtensionFeedItemCallable =
callableFactory.createUnaryCallable(
getExtensionFeedItemTransportSettings,
settings.getExtensionFeedItemSettings(),
clientContext);
this.mutateExtensionFeedItemsCallable =
callableFactory.createUnaryCallable(
mutateExtensionFeedItemsTransportSettings,
settings.mutateExtensionFeedItemsSettings(),
clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
public UnaryCallable<GetExtensionFeedItemRequest, ExtensionFeedItem>
getExtensionFeedItemCallable() {
return getExtensionFeedItemCallable;
}
public UnaryCallable<MutateExtensionFeedItemsRequest, MutateExtensionFeedItemsResponse>
mutateExtensionFeedItemsCallable() {
return mutateExtensionFeedItemsCallable;
}
@Override
public final void close() {
shutdown();
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
|
/*
* Copyright 2017 Danish Maritime Authority.
*
* 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.niord.core.category.vo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.ArrayList;
import java.util.List;
/**
* Value object for the {@code CompositeParamType} model entity
*/
@JsonTypeName("COMPOSITE")
@SuppressWarnings("unused")
public class CompositeParamTypeVo extends ParamTypeVo {
List<TemplateParamVo> templateParams = new ArrayList<>();
/**
* Returns or creates the list of template parameters
* @return the list of template parameters
*/
public List<TemplateParamVo> checkCreateTemplateParams() {
if (templateParams == null) {
templateParams = new ArrayList<>();
}
return templateParams;
}
/*************************/
/** Getters and Setters **/
/*************************/
public List<TemplateParamVo> getTemplateParams() {
return templateParams;
}
public void setTemplateParams(List<TemplateParamVo> templateParams) {
this.templateParams = templateParams;
}
}
|
package com.jkds.dialog.util;
import android.graphics.drawable.Drawable;
/**
* Author: @Kongzue
* Github: https://github.com/kongzue/
* Homepage: http://kongzue.com/
* Mail: myzcxhh@live.cn
* CreateTime: 2019/3/22 16:03
*/
public class DialogSettings {
public enum STYLE {
STYLE_MATERIAL, STYLE_KONGZUE, STYLE_IOS, STYLE_MIUI
}
public enum THEME {
LIGHT, DARK
}
//开启模态化队列启动方式
public static boolean modalDialog = false;
//全局主题风格
public static STYLE style = STYLE.STYLE_IOS;
//全局对话框明暗风格
public static THEME theme = THEME.LIGHT;
//全局提示框明暗风格
public static THEME tipTheme = THEME.DARK;
//全局标题文字样式
public static TextInfo titleTextInfo;
//全局正文文字样式
public static TextInfo contentTextInfo;
//全局提示文字样式
public static TextInfo tipTextInfo;
//全局默认按钮文字样式
public static TextInfo buttonTextInfo;
//全局焦点按钮文字样式
public static TextInfo buttonPositiveTextInfo;
//全局输入框文本样式
public static InputInfo inputInfo;
//全局菜单标题样式
public static TextInfo menuTitleInfo;
//全局菜单文字样式
public static TextInfo menuTextInfo;
//全局对话框背景颜色,值0时不生效
public static int backgroundColor = 0;
//全局对话框默认是否可以点击外围遮罩区域或返回键关闭,此开关不影响提示框(TipDialog)以及等待框(TipDialog)
public static boolean cancelable = true;
//全局提示框及等待框(WaitDialog、TipDialog)默认是否可以关闭
public static boolean cancelableTipDialog = false;
//是否允许显示日志
public static boolean DEBUGMODE = true;
//模糊透明度(0~255)
public static int blurAlpha = 210;
//允许自定义系统对话框style,注意设置此功能会导致原对话框风格和动画失效
public static int systemDialogStyle;
//默认取消按钮文本文字,影响BottomDialog、ShareDialog
public static String defaultCancelButtonText;
// //全局Dialog生命周期监听器
//全局提示框背景资源,值0时不生效
public static int tipBackgroundResId = 0;
//对话框,全局按钮资源
public static Drawable okButtonDrawable;
public static Drawable cancelButtonDrawable;
public static Drawable otherButtonDrawable;
//输入对话框,是否自动弹出输入键盘
public static boolean autoShowInputKeyboard = true;
public static void init() {
BaseDialog.reset();
}
}
|
package com.tinmegali.getlocation;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
package com.gulimail.gulimail.order.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gulimail.gulimail.order.entity.PaymentInfoEntity;
import com.gulimail.gulimail.order.service.PaymentInfoService;
import com.gulimail.common.utils.PageUtils;
import com.gulimail.common.utils.R;
/**
* 支付信息表
*
* @author binyu
* @email 1017834057@qq.com
* @date 2020-05-14 22:50:18
*/
@RestController
@RequestMapping("order/paymentinfo")
public class PaymentInfoController {
@Autowired
private PaymentInfoService paymentInfoService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("order:paymentinfo:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = paymentInfoService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("order:paymentinfo:info")
public R info(@PathVariable("id") Long id){
PaymentInfoEntity paymentInfo = paymentInfoService.getById(id);
return R.ok().put("paymentInfo", paymentInfo);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("order:paymentinfo:save")
public R save(@RequestBody PaymentInfoEntity paymentInfo){
paymentInfoService.save(paymentInfo);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("order:paymentinfo:update")
public R update(@RequestBody PaymentInfoEntity paymentInfo){
paymentInfoService.updateById(paymentInfo);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("order:paymentinfo:delete")
public R delete(@RequestBody Long[] ids){
paymentInfoService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
/* 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.activiti5.engine.impl.bpmn.parser.handler;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.BoundaryEvent;
import org.activiti.bpmn.model.IntermediateCatchEvent;
import org.activiti.bpmn.model.Signal;
import org.activiti.bpmn.model.SignalEventDefinition;
import org.activiti.bpmn.model.StartEvent;
import org.activiti.bpmn.model.ThrowEvent;
import org.activiti5.engine.impl.bpmn.parser.BpmnParse;
import org.activiti5.engine.impl.bpmn.parser.EventSubscriptionDeclaration;
import org.activiti5.engine.impl.pvm.process.ActivityImpl;
/**
* @author Joram Barrez
*/
public class SignalEventDefinitionParseHandler extends AbstractBpmnParseHandler<SignalEventDefinition> {
public Class< ? extends BaseElement> getHandledType() {
return SignalEventDefinition.class;
}
protected void executeParse(BpmnParse bpmnParse, SignalEventDefinition signalDefinition) {
Signal signal = null;
if (bpmnParse.getBpmnModel().containsSignalId(signalDefinition.getSignalRef())) {
signal = bpmnParse.getBpmnModel().getSignal(signalDefinition.getSignalRef());
String signalName = signal.getName();
signalDefinition.setSignalRef(signalName);
}
if (signal == null) {
return;
}
ActivityImpl activity = bpmnParse.getCurrentActivity();
if (bpmnParse.getCurrentFlowElement() instanceof StartEvent) {
activity.setProperty("type", "signalStartEvent");
EventSubscriptionDeclaration eventSubscriptionDeclaration = new EventSubscriptionDeclaration(signalDefinition.getSignalRef(), "signal");
eventSubscriptionDeclaration.setActivityId(activity.getId());
eventSubscriptionDeclaration.setStartEvent(true);
addEventSubscriptionDeclaration(bpmnParse, eventSubscriptionDeclaration, signalDefinition, bpmnParse.getCurrentScope());
} else if (bpmnParse.getCurrentFlowElement() instanceof IntermediateCatchEvent){
activity.setProperty("type", "intermediateSignalCatch");
EventSubscriptionDeclaration eventSubscriptionDeclaration = new EventSubscriptionDeclaration(signalDefinition.getSignalRef(), "signal");
if (signal.getScope() != null) {
eventSubscriptionDeclaration.setConfiguration(signal.getScope());
}
if (getPrecedingEventBasedGateway(bpmnParse, (IntermediateCatchEvent) bpmnParse.getCurrentFlowElement()) != null) {
eventSubscriptionDeclaration.setActivityId(activity.getId());
addEventSubscriptionDeclaration(bpmnParse, eventSubscriptionDeclaration, signalDefinition, activity.getParent());
} else {
activity.setScope(true);
addEventSubscriptionDeclaration(bpmnParse, eventSubscriptionDeclaration, signalDefinition, activity);
}
} else if (bpmnParse.getCurrentFlowElement() instanceof ThrowEvent) {
ThrowEvent throwEvent = (ThrowEvent) bpmnParse.getCurrentFlowElement();
activity.setProperty("type", "intermediateSignalThrow");
EventSubscriptionDeclaration eventSubscriptionDeclaration = new EventSubscriptionDeclaration(signalDefinition.getSignalRef(), "signal");
eventSubscriptionDeclaration.setAsync(signalDefinition.isAsync());
activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateThrowSignalEventActivityBehavior(throwEvent, signal, eventSubscriptionDeclaration));
} else if (bpmnParse.getCurrentFlowElement() instanceof BoundaryEvent) {
BoundaryEvent boundaryEvent = (BoundaryEvent) bpmnParse.getCurrentFlowElement();
boolean interrupting = boundaryEvent.isCancelActivity();
activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createBoundaryEventActivityBehavior(boundaryEvent, interrupting, activity));
activity.setProperty("type", "boundarySignal");
EventSubscriptionDeclaration eventSubscriptionDeclaration = new EventSubscriptionDeclaration(signalDefinition.getSignalRef(), "signal");
eventSubscriptionDeclaration.setActivityId(activity.getId());
if (signal.getScope() != null) {
eventSubscriptionDeclaration.setConfiguration(signal.getScope());
}
addEventSubscriptionDeclaration(bpmnParse, eventSubscriptionDeclaration, signalDefinition, activity.getParent());
if (activity.getParent() instanceof ActivityImpl) {
((ActivityImpl) activity.getParent()).setScope(true);
}
}
}
}
|
package my.own.pkg;
import static abc.def;
import static abc.def.Another;
import static abc.def.Something;
import static java.utils.*;
import static something.Different;
import abc.def;
import abc.def.Another;
import abc.def.Something;
import java.utils.*;
import one.last;
import something.Different;
public class PackageAndImports {}
|
/*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (c) 2019 Samsung
* ================================================================================
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.so.bpmn.infrastructure.flowspecific.tasks;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.onap.so.logger.LoggingAnchor;
import org.onap.appc.client.lcm.model.Action;
import org.onap.so.bpmn.appc.payload.beans.ConfigScaleOutPayload;
import org.onap.so.bpmn.appc.payload.beans.RequestParametersConfigScaleOut;
import org.onap.so.bpmn.common.BuildingBlockExecution;
import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
import org.onap.so.client.appc.ApplicationControllerAction;
import org.onap.so.client.exception.ExceptionBuilder;
import org.onap.so.db.catalog.beans.ControllerSelectionReference;
import org.onap.so.db.catalog.client.CatalogDbClient;
import org.onap.logging.filter.base.ErrorCode;
import org.onap.so.logger.MessageEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
@Component
public class ConfigurationScaleOut {
private static final Logger logger = LoggerFactory.getLogger(ConfigurationScaleOut.class);
@Autowired
private ExceptionBuilder exceptionUtil;
@Autowired
private ExtractPojosForBB extractPojosForBB;
@Autowired
private CatalogDbClient catalogDbClient;
@Autowired
private ApplicationControllerAction appCClient;
private static final String ACTION = "action";
private static final String MSO_REQUEST_ID = "msoRequestId";
private static final String VNF_ID = "vnfId";
private static final String VNF_NAME = "vnfName";
private static final String VFMODULE_ID = "vfModuleId";
private static final String CONTROLLER_TYPE = "controllerType";
private static final String PAYLOAD = "payload";
public void setParamsForConfigurationScaleOut(BuildingBlockExecution execution) {
GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock();
try {
List<Map<String, String>> jsonPathForCfgParams = gBBInput.getRequestContext().getConfigurationParameters();
String key = null;
String paramValue = null;
ObjectMapper mapper = new ObjectMapper();
String configScaleOutPayloadString = null;
ControllerSelectionReference controllerSelectionReference;
ConfigScaleOutPayload configPayload = new ConfigScaleOutPayload();
GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
String vnfId = vnf.getVnfId();
String vnfName = vnf.getVnfName();
String vnfType = vnf.getVnfType();
String actionCategory = Action.ConfigScaleOut.toString();
controllerSelectionReference =
catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory);
String controllerName = controllerSelectionReference.getControllerName();
VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID);
String sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId());
Map<String, String> paramsMap = new HashMap<>();
RequestParametersConfigScaleOut requestParameters = new RequestParametersConfigScaleOut();
String configScaleOutParam = null;
if (jsonPathForCfgParams != null) {
for (Map<String, String> param : jsonPathForCfgParams) {
for (Map.Entry<String, String> entry : param.entrySet()) {
key = entry.getKey();
paramValue = entry.getValue();
try {
configScaleOutParam = JsonPath.parse(sdncVfModuleQueryResponse).read(paramValue);
} catch (ClassCastException e) {
configScaleOutParam = null;
logger.warn("Incorrect JSON path. Path points to object rather than value causing: ", e);
}
paramsMap.put(key, configScaleOutParam);
}
}
}
requestParameters.setVfModuleId(vfModule.getVfModuleId());
requestParameters.setVnfHostIpAddress(vnf.getIpv4OamAddress());
configPayload.setConfigurationParameters(paramsMap);
configPayload.setRequestParameters(requestParameters);
configScaleOutPayloadString = mapper.writeValueAsString(configPayload);
execution.setVariable(ACTION, actionCategory);
execution.setVariable(MSO_REQUEST_ID, gBBInput.getRequestContext().getMsoRequestId());
execution.setVariable(VNF_ID, vnfId);
execution.setVariable(VNF_NAME, vnfName);
execution.setVariable(VFMODULE_ID, vfModule.getVfModuleId());
execution.setVariable(CONTROLLER_TYPE, controllerName);
execution.setVariable(PAYLOAD, configScaleOutPayloadString);
} catch (Exception ex) {
exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
}
}
public void callAppcClient(BuildingBlockExecution execution) {
logger.trace("Start runAppcCommand ");
String appcCode = "1002";
String appcMessage = "";
try {
Action commandAction = Action.valueOf(execution.getVariable(ACTION));
String msoRequestId = execution.getVariable(MSO_REQUEST_ID);
String vnfId = execution.getVariable(VNF_ID);
Optional<String> payloadString = null;
if (execution.getVariable(PAYLOAD) != null) {
String pay = execution.getVariable(PAYLOAD);
payloadString = Optional.of(pay);
}
String controllerType = execution.getVariable(CONTROLLER_TYPE);
HashMap<String, String> payloadInfo = new HashMap<>();
payloadInfo.put(VNF_NAME, execution.getVariable(VNF_NAME));
payloadInfo.put(VFMODULE_ID, execution.getVariable(VFMODULE_ID));
logger.debug("Running APP-C action: {}", commandAction.toString());
logger.debug("VNFID: {}", vnfId);
// PayloadInfo contains extra information that adds on to payload before making request to appc
appCClient.runAppCCommand(commandAction, msoRequestId, vnfId, payloadString, payloadInfo, controllerType);
appcCode = appCClient.getErrorCode();
appcMessage = appCClient.getErrorMessage();
} catch (Exception e) {
logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION.toString(),
"Caught exception in runAppcCommand in ConfigurationScaleOut", "BPMN",
ErrorCode.UnknownError.getValue(), "APPC Error", e);
appcMessage = e.getMessage();
}
logger.error("Error Message: " + appcMessage);
logger.error("ERROR CODE: " + appcCode);
logger.trace("End of runAppCommand ");
if (appcCode != null && !("0").equals(appcCode)) {
exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage);
}
}
}
|
/*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 herddb.server;
import herddb.client.ClientConfiguration;
import herddb.cluster.BookKeeperDataStorageManager;
import herddb.cluster.BookkeeperCommitLogManager;
import herddb.cluster.EmbeddedBookie;
import herddb.cluster.ZookeeperMetadataStorageManager;
import herddb.core.DBManager;
import herddb.core.stats.ConnectionsInfo;
import herddb.core.stats.ConnectionsInfoProvider;
import herddb.file.FileBasedUserManager;
import herddb.file.FileCommitLogManager;
import herddb.file.FileDataStorageManager;
import herddb.file.FileMetadataStorageManager;
import herddb.log.CommitLogManager;
import herddb.mem.MemoryCommitLogManager;
import herddb.mem.MemoryDataStorageManager;
import herddb.mem.MemoryLocalNodeIdManager;
import herddb.mem.MemoryMetadataStorageManager;
import herddb.metadata.MetadataStorageManager;
import herddb.metadata.MetadataStorageManagerException;
import herddb.model.TableSpace;
import herddb.network.Channel;
import herddb.network.ServerHostData;
import herddb.network.ServerSideConnection;
import herddb.network.ServerSideConnectionAcceptor;
import herddb.network.netty.NettyChannelAcceptor;
import herddb.network.netty.NetworkUtils;
import herddb.security.SimpleSingleUserManager;
import herddb.security.UserManager;
import herddb.storage.DataStorageManager;
import herddb.utils.Version;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.bookkeeper.stats.NullStatsLogger;
import org.apache.bookkeeper.stats.StatsLogger;
/**
* HerdDB Server
*
* @author enrico.olivelli
*/
public class Server implements AutoCloseable, ServerSideConnectionAcceptor<ServerSideConnection>, ConnectionsInfoProvider {
private static final Logger LOGGER = Logger.getLogger(Server.class.getName());
private final DBManager manager;
private final NettyChannelAcceptor networkServer;
private final ServerConfiguration configuration;
private final StatsLogger statsLogger;
private final Path baseDirectory;
private final Path dataDirectory;
private final Path tmpDirectory;
private final ServerHostData serverHostData;
private final Map<Long, ServerSideConnectionPeer> connections = new ConcurrentHashMap<>();
private final String mode;
private final MetadataStorageManager metadataStorageManager;
private final CommitLogManager commitLogManager;
private String jdbcUrl;
private UserManager userManager;
private EmbeddedBookie embeddedBookie;
public UserManager getUserManager() {
return userManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public MetadataStorageManager getMetadataStorageManager() {
return metadataStorageManager;
}
public DBManager getManager() {
return manager;
}
public NettyChannelAcceptor getNetworkServer() {
return networkServer;
}
public Server(ServerConfiguration configuration) {
this(configuration, null);
}
public Server(ServerConfiguration configuration, StatsLogger statsLogger) {
this.statsLogger = statsLogger == null ? new NullStatsLogger() : statsLogger;
this.configuration = configuration;
String nodeId = configuration.getString(ServerConfiguration.PROPERTY_NODEID, "");
this.mode = configuration.getString(ServerConfiguration.PROPERTY_MODE, ServerConfiguration.PROPERTY_MODE_STANDALONE);
this.baseDirectory = Paths.get(configuration.getString(ServerConfiguration.PROPERTY_BASEDIR, ServerConfiguration.PROPERTY_BASEDIR_DEFAULT)).toAbsolutePath();
if (!mode.equals(ServerConfiguration.PROPERTY_MODE_LOCAL)) {
try {
Files.createDirectories(this.baseDirectory);
} catch (IOException ignore) {
LOGGER.log(Level.SEVERE, "Cannot create baseDirectory " + this.baseDirectory, ignore);
}
}
this.dataDirectory = this.baseDirectory.resolve(configuration.getString(ServerConfiguration.PROPERTY_DATADIR, ServerConfiguration.PROPERTY_DATADIR_DEFAULT));
this.tmpDirectory = this.baseDirectory.resolve(configuration.getString(ServerConfiguration.PROPERTY_TMPDIR, ServerConfiguration.PROPERTY_TMPDIR_DEFAULT));
String usersfile = configuration.getString(ServerConfiguration.PROPERTY_USERS_FILE, ServerConfiguration.PROPERTY_USERS_FILE_DEFAULT);
if (usersfile.isEmpty()) {
this.userManager = new SimpleSingleUserManager(configuration);
} else {
try {
Path userDirectoryFile = baseDirectory.resolve(usersfile).toAbsolutePath();
LOGGER.log(Level.INFO, "Reading users from file " + userDirectoryFile);
this.userManager = new FileBasedUserManager(userDirectoryFile);
} catch (IOException error) {
throw new RuntimeException(error);
}
}
this.metadataStorageManager = buildMetadataStorageManager();
String host = configuration.getString(ServerConfiguration.PROPERTY_HOST, ServerConfiguration.PROPERTY_HOST_DEFAULT);
int port = configuration.getInt(ServerConfiguration.PROPERTY_PORT, ServerConfiguration.PROPERTY_PORT_DEFAULT);
if (!mode.equals(ServerConfiguration.PROPERTY_MODE_LOCAL)) {
LOGGER.log(Level.INFO, "Configured network parameters: " + ServerConfiguration.PROPERTY_HOST + "={0}, "
+ ServerConfiguration.PROPERTY_PORT + "={1}", new Object[]{host, port});
}
if (host.trim().isEmpty()) {
String _host = "0.0.0.0";
LOGGER.log(Level.INFO, "As configuration parameter "
+ ServerConfiguration.PROPERTY_HOST + " is {0}, I have choosen to use {1}."
+ " Set to a non-empty value in order to use a fixed hostname", new Object[]{host, _host});
host = _host;
}
if (port <= 0) {
try {
int _port = NetworkUtils.assignFirstFreePort();
LOGGER.log(Level.INFO, "As configuration parameter "
+ ServerConfiguration.PROPERTY_PORT + " is {0},I have choosen to listen on port {1}."
+ " Set to a positive number in order to use a fixed port", new Object[]{Integer.toString(port), Integer.toString(_port)});
port = _port;
} catch (IOException err) {
LOGGER.log(Level.SEVERE, "Cannot find a free port", err);
throw new RuntimeException(err);
}
}
String advertised_host = configuration.getString(ServerConfiguration.PROPERTY_ADVERTISED_HOST, host);
if (advertised_host.trim().isEmpty() || advertised_host.equals("0.0.0.0")) {
try {
String _host = NetworkUtils.getLocalNetworkAddress();
LOGGER.log(Level.INFO, "As configuration parameter "
+ ServerConfiguration.PROPERTY_ADVERTISED_HOST + " is {0}, I have choosen to use {1}."
+ " Set to a non-empty value in order to use a fixed hostname", new Object[]{advertised_host, _host});
advertised_host = _host;
} catch (IOException err) {
LOGGER.log(Level.SEVERE, "Cannot get local host name", err);
throw new RuntimeException(err);
}
}
int advertised_port = configuration.getInt(ServerConfiguration.PROPERTY_ADVERTISED_PORT, port);
HashMap<String, String> realData = new HashMap<>();
realData.put(ServerConfiguration.PROPERTY_HOST, host);
realData.put(ServerConfiguration.PROPERTY_PORT, port + "");
if (!mode.equals(ServerConfiguration.PROPERTY_MODE_LOCAL)) {
LOGGER.info("Public endpoint: " + ServerConfiguration.PROPERTY_ADVERTISED_HOST + "=" + advertised_host
+ ", Public endpoint: " + ServerConfiguration.PROPERTY_ADVERTISED_PORT + "=" + advertised_port);
}
this.serverHostData = new ServerHostData(
advertised_host,
advertised_port,
"",
configuration.getBoolean(ServerConfiguration.PROPERTY_SSL, false),
realData);
if (nodeId.isEmpty()) {
LocalNodeIdManager localNodeIdManager = buildLocalNodeIdManager();
try {
nodeId = localNodeIdManager.readLocalNodeId();
if (nodeId == null) {
// we need to eagerly start the metadataStorageManager, for instance to open the connection to ZK
metadataStorageManager.start();
nodeId = metadataStorageManager.generateNewNodeId(configuration);
if (!mode.equals(ServerConfiguration.PROPERTY_MODE_LOCAL)) {
LOGGER.info("Generated new node id " + nodeId);
}
localNodeIdManager.persistLocalNodeId(nodeId);
// let downstream code see this new id (Embedded Bookie for instance)
configuration.set(ServerConfiguration.PROPERTY_NODEID, nodeId);
}
} catch (IOException | MetadataStorageManagerException error) {
LOGGER.log(Level.SEVERE, "Fatal error while generating the local node ID", error);
throw new RuntimeException(new Exception("Fatal error while generating the local node ID: " + error, error));
}
}
this.commitLogManager = buildCommitLogManager();
this.manager = new DBManager(nodeId,
metadataStorageManager,
buildDataStorageManager(nodeId),
commitLogManager,
tmpDirectory, serverHostData, configuration, statsLogger
);
this.manager.setClearAtBoot(configuration.getBoolean(ServerConfiguration.PROPERTY_CLEAR_AT_BOOT, ServerConfiguration.PROPERTY_CLEAR_AT_BOOT_DEFAULT));
this.manager.setHaltOnTableSpaceBootError(configuration.getBoolean(ServerConfiguration.PROPERTY_HALT_ON_TABLESPACE_BOOT_ERROR, ServerConfiguration.PROPERTY_HALT_ON_TABLESPACE_BOOT_ERROR_DEAULT));
this.manager.setConnectionsInfoProvider(this);
this.manager.setServerToServerUsername(configuration.getString(ServerConfiguration.PROPERTY_SERVER_TO_SERVER_USERNAME, ClientConfiguration.PROPERTY_CLIENT_USERNAME_DEFAULT));
this.manager.setServerToServerPassword(configuration.getString(ServerConfiguration.PROPERTY_SERVER_TO_SERVER_PASSWORD, ClientConfiguration.PROPERTY_CLIENT_PASSWORD_DEFAULT));
this.manager.setCheckpointPeriod(configuration.getLong(ServerConfiguration.PROPERTY_CHECKPOINT_PERIOD, ServerConfiguration.PROPERTY_CHECKPOINT_PERIOD_DEFAULT));
this.manager.setAbandonedTransactionsTimeout(configuration.getLong(ServerConfiguration.PROPERTY_ABANDONED_TRANSACTIONS_TIMEOUT, ServerConfiguration.PROPERTY_ABANDONED_TRANSACTIONS_TIMEOUT_DEFAULT));
boolean enforeLeadership = configuration.getBoolean(ServerConfiguration.PROPERTY_ENFORCE_LEADERSHIP, ServerConfiguration.PROPERTY_ENFORCE_LEADERSHIP_DEFAULT);
this.manager.setErrorIfNotLeader(enforeLeadership);
this.networkServer = buildChannelAcceptor();
this.networkServer.setAcceptor(this);
switch (mode) {
case ServerConfiguration.PROPERTY_MODE_LOCAL:
jdbcUrl = "jdbc:herddb:server:" + serverHostData.getHost() + ":" + serverHostData.getPort();
LOGGER.info("JDBC URL is not available. This server will not be accessible outside the JVM");
break;
case ServerConfiguration.PROPERTY_MODE_STANDALONE:
jdbcUrl = "jdbc:herddb:server:" + serverHostData.getHost() + ":" + serverHostData.getPort();
LOGGER.log(Level.INFO, "Use this JDBC URL to connect to this server: {0}", new Object[]{jdbcUrl});
break;
case ServerConfiguration.PROPERTY_MODE_CLUSTER:
case ServerConfiguration.PROPERTY_MODE_DISKLESSCLUSTER:
this.embeddedBookie = new EmbeddedBookie(baseDirectory, configuration, (ZookeeperMetadataStorageManager) this.metadataStorageManager, statsLogger);
jdbcUrl = "jdbc:herddb:zookeeper:" + configuration.getString(ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS, ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS_DEFAULT) + configuration.getString(ServerConfiguration.PROPERTY_ZOOKEEPER_PATH, ServerConfiguration.PROPERTY_ZOOKEEPER_PATH_DEFAULT);
LOGGER.log(Level.INFO, "Use this JDBC URL to connect to this HerdDB cluster: {0}", new Object[]{jdbcUrl});
break;
default:
throw new IllegalStateException("invalid " + ServerConfiguration.PROPERTY_MODE + "=" + mode);
}
LOGGER.log(Level.INFO, "HerdDB version {0}", new Object[]{Version.getVERSION()});
LOGGER.log(Level.INFO, "Local " + ServerConfiguration.PROPERTY_NODEID + " is {0}", new Object[]{nodeId});
}
public String getJdbcUrl() {
return jdbcUrl;
}
private NettyChannelAcceptor buildChannelAcceptor() {
String realHost = serverHostData.getAdditionalData().get(ServerConfiguration.PROPERTY_HOST);
int realPort = Integer.parseInt(serverHostData.getAdditionalData().get(ServerConfiguration.PROPERTY_PORT));
NettyChannelAcceptor acceptor = new NettyChannelAcceptor(realHost, realPort, serverHostData.isSsl(),
statsLogger.scope("network"));
// with 'local' mode we are disabling network by default
// but in case you want to run benchmarks with 'local' mode using
// the client on a separate process/machine you should be able
// to enable network
boolean isLocal = ServerConfiguration.PROPERTY_MODE_LOCAL.equals(mode);
boolean nextworkEnabled = configuration.getBoolean(ServerConfiguration.PROPERTY_NETWORK_ENABLED,
!isLocal && ServerConfiguration.PROPERTY_NETWORK_ENABLED_DEFAULT);
if (!nextworkEnabled) {
acceptor.setEnableRealNetwork(false);
LOGGER.log(Level.FINE, "Local in-JVM acceptor on {0}:{1} ssl:{2}",
new Object[]{realHost, realPort, serverHostData.isSsl()});
} else {
LOGGER.log(Level.INFO, "Binding network acceptor to {0}:{1} ssl:{2}",
new Object[]{realHost, realPort, serverHostData.isSsl()});
}
int callbackThreads = configuration.getInt(
ServerConfiguration.PROPERTY_NETWORK_CALLBACK_THREADS,
ServerConfiguration.PROPERTY_NETWORK_CALLBACK_THREADS_DEFAULT);
int workerThreads = configuration.getInt(
ServerConfiguration.PROPERTY_NETWORK_WORKER_THREADS,
ServerConfiguration.PROPERTY_NETWORK_WORKER_THREADS_DEFAULT);
acceptor.setCallbackThreads(callbackThreads);
acceptor.setWorkerThreads(workerThreads);
return acceptor;
}
private MetadataStorageManager buildMetadataStorageManager() {
switch (mode) {
case ServerConfiguration.PROPERTY_MODE_LOCAL:
return new MemoryMetadataStorageManager();
case ServerConfiguration.PROPERTY_MODE_STANDALONE:
Path metadataDirectory = this.baseDirectory.resolve(configuration.getString(ServerConfiguration.PROPERTY_METADATADIR, ServerConfiguration.PROPERTY_METADATADIR_DEFAULT));
return new FileMetadataStorageManager(metadataDirectory);
case ServerConfiguration.PROPERTY_MODE_CLUSTER:
case ServerConfiguration.PROPERTY_MODE_DISKLESSCLUSTER:
return new ZookeeperMetadataStorageManager(configuration.getString(ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS, ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS_DEFAULT),
configuration.getInt(ServerConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT, ServerConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT_DEFAULT),
configuration.getString(ServerConfiguration.PROPERTY_ZOOKEEPER_PATH, ServerConfiguration.PROPERTY_ZOOKEEPER_PATH_DEFAULT));
default:
throw new RuntimeException();
}
}
private DataStorageManager buildDataStorageManager(String nodeId) {
switch (mode) {
case ServerConfiguration.PROPERTY_MODE_LOCAL:
return new MemoryDataStorageManager();
case ServerConfiguration.PROPERTY_MODE_STANDALONE:
case ServerConfiguration.PROPERTY_MODE_CLUSTER: {
int diskswapThreshold = configuration.getInt(ServerConfiguration.PROPERTY_DISK_SWAP_MAX_RECORDS, ServerConfiguration.PROPERTY_DISK_SWAP_MAX_RECORDS_DEFAULT);
boolean requirefsync = configuration.getBoolean(ServerConfiguration.PROPERTY_REQUIRE_FSYNC, ServerConfiguration.PROPERTY_REQUIRE_FSYNC_DEFAULT);
boolean pageodirect = configuration.getBoolean(ServerConfiguration.PROPERTY_PAGE_USE_ODIRECT, ServerConfiguration.PROPERTY_PAGE_USE_ODIRECT_DEFAULT);
boolean indexodirect = configuration.getBoolean(ServerConfiguration.PROPERTY_INDEX_USE_ODIRECT, ServerConfiguration.PROPERTY_INDEX_USE_ODIRECT_DEFAULT);
boolean hashChecksEnabled = configuration.getBoolean(ServerConfiguration.PROPERTY_HASH_CHECKS_ENABLED, ServerConfiguration.PROPERTY_HASH_CHECKS_ENABLED_DEFAULT);
boolean hashWritesEnabled = configuration.getBoolean(ServerConfiguration.PROPERTY_HASH_WRITES_ENABLED, ServerConfiguration.PROPERTY_HASH_WRITES_ENABLED_DEFAULT);
return new FileDataStorageManager(dataDirectory, tmpDirectory, diskswapThreshold, requirefsync, pageodirect, indexodirect, hashChecksEnabled, hashWritesEnabled, statsLogger);
}
case ServerConfiguration.PROPERTY_MODE_DISKLESSCLUSTER: {
int diskswapThreshold = configuration.getInt(ServerConfiguration.PROPERTY_DISK_SWAP_MAX_RECORDS, ServerConfiguration.PROPERTY_DISK_SWAP_MAX_RECORDS_DEFAULT);
return new BookKeeperDataStorageManager(nodeId, tmpDirectory, diskswapThreshold, (ZookeeperMetadataStorageManager) metadataStorageManager,
(BookkeeperCommitLogManager) this.commitLogManager, this.statsLogger);
}
default:
throw new RuntimeException();
}
}
protected CommitLogManager buildCommitLogManager() {
switch (mode) {
case ServerConfiguration.PROPERTY_MODE_LOCAL:
return new MemoryCommitLogManager(false);
case ServerConfiguration.PROPERTY_MODE_STANDALONE:
Path logDirectory = this.baseDirectory.resolve(configuration.getString(ServerConfiguration.PROPERTY_LOGDIR, ServerConfiguration.PROPERTY_LOGDIR_DEFAULT));
return new FileCommitLogManager(logDirectory,
configuration.getLong(ServerConfiguration.PROPERTY_MAX_LOG_FILE_SIZE, ServerConfiguration.PROPERTY_MAX_LOG_FILE_SIZE_DEFAULT),
configuration.getInt(ServerConfiguration.PROPERTY_MAX_UNSYNCHED_BATCH, ServerConfiguration.PROPERTY_MAX_UNSYNCHED_BATCH_DEFAULT),
configuration.getInt(ServerConfiguration.PROPERTY_MAX_UNSYNCHED_BATCH_BYTES, ServerConfiguration.PROPERTY_MAX_UNSYNCHED_BATCH_BYTES_DEFAULT),
configuration.getInt(ServerConfiguration.PROPERTY_MAX_SYNC_TIME, ServerConfiguration.PROPERTY_MAX_SYNC_TIME_DEFAULT),
configuration.getBoolean(ServerConfiguration.PROPERTY_REQUIRE_FSYNC, ServerConfiguration.PROPERTY_REQUIRE_FSYNC_DEFAULT),
configuration.getBoolean(ServerConfiguration.PROPERTY_TXLOG_USE_ODIRECT, ServerConfiguration.PROPERTY_TXLOG_USE_ODIRECT_DEFAULT),
configuration.getInt(ServerConfiguration.PROPERTY_DEFERRED_SYNC_PERIOD, ServerConfiguration.PROPERTY_DEFERRED_SYNC_PERIOD_DEFAULT),
statsLogger.scope("txlog")
);
case ServerConfiguration.PROPERTY_MODE_CLUSTER:
case ServerConfiguration.PROPERTY_MODE_DISKLESSCLUSTER:
BookkeeperCommitLogManager bkmanager = new BookkeeperCommitLogManager((ZookeeperMetadataStorageManager) this.metadataStorageManager, configuration, statsLogger);
bkmanager.setAckQuorumSize(configuration.getInt(ServerConfiguration.PROPERTY_BOOKKEEPER_ACKQUORUMSIZE, ServerConfiguration.PROPERTY_BOOKKEEPER_ACKQUORUMSIZE_DEFAULT));
bkmanager.setEnsemble(configuration.getInt(ServerConfiguration.PROPERTY_BOOKKEEPER_ENSEMBLE, ServerConfiguration.PROPERTY_BOOKKEEPER_ENSEMBLE_DEFAULT));
bkmanager.setWriteQuorumSize(configuration.getInt(ServerConfiguration.PROPERTY_BOOKKEEPER_WRITEQUORUMSIZE, ServerConfiguration.PROPERTY_BOOKKEEPER_WRITEQUORUMSIZE_DEFAULT));
long ledgersRetentionPeriod = configuration.getLong(ServerConfiguration.PROPERTY_BOOKKEEPER_LEDGERS_RETENTION_PERIOD, ServerConfiguration.PROPERTY_BOOKKEEPER_LEDGERS_RETENTION_PERIOD_DEFAULT);
bkmanager.setLedgersRetentionPeriod(ledgersRetentionPeriod);
long maxLedgerSizeBytes = configuration.getLong(ServerConfiguration.PROPERTY_BOOKKEEPER_LEDGERS_MAX_SIZE, ServerConfiguration.PROPERTY_BOOKKEEPER_LEDGERS_MAX_SIZE_DEFAULT);
bkmanager.setMaxLedgerSizeBytes(maxLedgerSizeBytes);
long maxIdleTime = configuration.getLong(ServerConfiguration.PROPERTY_BOOKKEEPER_MAX_IDLE_TIME, ServerConfiguration.PROPERTY_BOOKKEEPER_MAX_IDLE_TIME_DEFAULT);
bkmanager.setMaxIdleTime(maxIdleTime);
long checkPointperiod = configuration.getLong(ServerConfiguration.PROPERTY_CHECKPOINT_PERIOD, ServerConfiguration.PROPERTY_CHECKPOINT_PERIOD_DEFAULT);
if (checkPointperiod > 0 && ledgersRetentionPeriod > 0) {
long limit = ledgersRetentionPeriod / 2;
if (checkPointperiod > limit) {
throw new RuntimeException(ServerConfiguration.PROPERTY_CHECKPOINT_PERIOD + "=" + checkPointperiod
+ " must be less then " + ServerConfiguration.PROPERTY_BOOKKEEPER_LEDGERS_RETENTION_PERIOD + "/2=" + limit);
}
}
return bkmanager;
default:
throw new RuntimeException();
}
}
private LocalNodeIdManager buildLocalNodeIdManager() {
switch (mode) {
case ServerConfiguration.PROPERTY_MODE_LOCAL:
return new MemoryLocalNodeIdManager(dataDirectory);
case ServerConfiguration.PROPERTY_MODE_STANDALONE:
case ServerConfiguration.PROPERTY_MODE_CLUSTER:
case ServerConfiguration.PROPERTY_MODE_DISKLESSCLUSTER:
return new LocalNodeIdManager(dataDirectory);
default:
throw new RuntimeException();
}
}
public void start() throws Exception {
boolean startBookie = configuration.getBoolean(ServerConfiguration.PROPERTY_BOOKKEEPER_START,
ServerConfiguration.PROPERTY_BOOKKEEPER_START_DEFAULT);
if (startBookie && embeddedBookie != null) {
this.embeddedBookie.start();
}
this.manager.start();
this.networkServer.start();
}
public void waitForStandaloneBoot() throws Exception {
waitForTableSpaceBoot(TableSpace.DEFAULT, true);
}
public void waitForTableSpaceBoot(String tableSpace, boolean leader) throws Exception {
waitForTableSpaceBoot(tableSpace, 180000, leader);
}
public void waitForTableSpaceBoot(String tableSpace, int timeout, boolean leader) throws Exception {
if (!this.manager.waitForTablespace(tableSpace, timeout, leader)) {
throw new Exception("TableSpace " + tableSpace + " not started within " + timeout + " ms");
}
}
public void waitForBootOfLocalTablespaces(int timeout) throws Exception {
this.manager.waitForBootOfLocalTablespaces(timeout);
}
@Override
public void close() throws Exception {
try {
networkServer.close();
} catch (Throwable error) {
LOGGER.log(Level.SEVERE, "error while stopping Network Manager" + error, error);
}
try {
manager.close();
} catch (Throwable error) {
LOGGER.log(Level.SEVERE, "error while stopping embedded DBManager " + error, error);
}
if (embeddedBookie != null) {
try {
embeddedBookie.close();
} catch (Throwable error) {
LOGGER.log(Level.SEVERE, "error while stopping embedded bookie " + error, error);
}
}
}
protected ServerSideConnectionPeer buildPeer(Channel channel) {
return new ServerSideConnectionPeer(channel, this);
}
@Override
public ServerSideConnection createConnection(Channel channel) {
ServerSideConnectionPeer peer = buildPeer(channel);
connections.put(peer.getConnectionId(), peer);
return peer;
}
Map<Long, ServerSideConnectionPeer> getConnections() {
return connections;
}
void connectionClosed(ServerSideConnectionPeer connection) {
connections.remove(connection.getConnectionId());
}
public String getNodeId() {
return manager.getNodeId();
}
public ServerHostData getServerHostData() {
return serverHostData;
}
public int getConnectionCount() {
return connections.size();
}
@Override
public ConnectionsInfo getActualConnections() {
return new ConnectionsInfo(connections
.values()
.stream()
.map(c -> {
return c.toConnectionInfo();
})
.collect(Collectors.toList()));
}
public EmbeddedBookie getEmbeddedBookie() {
return embeddedBookie;
}
}
|
package com.team1458.turtleshell2.implementations.input;
import com.team1458.turtleshell2.interfaces.input.InputMapping;
import static com.team1458.turtleshell2.implementations.input.InputManager.InputDevice.FLIGHT_STICK;
import static com.team1458.turtleshell2.implementations.input.InputManager.InputDevice.XBOX_CONTROLLER;
/**
* Class for managing user inputs. Currently supports dual flight-sticks OR Xbox controller.
*
* @author asinghani
*/
public class InputManager {
private TurtleFlightStick leftStick;
private TurtleFlightStick rightStick;
private TurtleXboxController xboxController;
private InputDevice inputDevice;
private InputMapping mapping;
public InputManager(TurtleXboxController xboxController, InputMapping mapping) {
this.xboxController = xboxController;
this.mapping = mapping;
this.inputDevice = XBOX_CONTROLLER;
}
public InputManager(TurtleFlightStick leftStick, TurtleFlightStick rightStick, InputMapping mapping) {
this.leftStick = leftStick;
this.rightStick = rightStick;
this.mapping = mapping;
this.inputDevice = FLIGHT_STICK;
}
public TurtleJoystickAxis getAxis(String s) {
InputObject object = mapping.getMapping().get(s);
switch(inputDevice) {
case XBOX_CONTROLLER:
return xboxController.getAxis(object.getXboxAxis());
case FLIGHT_STICK:
return object.isRightFlightStick() ? rightStick.getAxis(object.getFlightAxis()) : leftStick.getAxis(object.getFlightAxis());
}
return null;
}
public double getAxisValue(String s) {
return getAxis(s).getButton();
}
public TurtleJoystickButton getButton(String s) {
InputObject object = mapping.getMapping().get(s);
switch(inputDevice) {
case XBOX_CONTROLLER:
return xboxController.getButton(object.getXboxButton());
case FLIGHT_STICK:
return object.isRightFlightStick() ? rightStick.getButton(object.getFlightButton()) : leftStick.getButton(object.getFlightButton());
}
return null;
}
public boolean getButtonValue(String s) {
return getButton(s).getButton();
}
public boolean getButtonUp(String s) {
return getButton(s).getUp();
}
public boolean getButtonDown(String s) {
return getButton(s).getDown();
}
public TurtleJoystickPOVSwitch getPOV(String s) {
InputObject object = mapping.getMapping().get(s);
switch(inputDevice) {
case XBOX_CONTROLLER:
return xboxController.getDPad();
case FLIGHT_STICK:
return object.isRightFlightStick() ? rightStick.getPOVSwitch() : leftStick.getPOVSwitch();
}
return null;
}
public com.team1458.turtleshell2.input.POVValue getPOVvalue(String s) {
return getPOV(s).getButton();
}
public void rumbleRight(float strength, long millis) {
if(xboxController != null) xboxController.rumbleRight(strength, millis);
}
public void rumbleLeft(float strength, long millis) {
if(xboxController != null) xboxController.rumbleLeft(strength, millis);
}
public void rumble(float strength, long millis) {
if(xboxController != null) xboxController.rumble(strength, millis);
}
public enum InputType {
BUTTON, ANALOG, POV
}
public enum InputDevice {
XBOX_CONTROLLER, FLIGHT_STICK
}
}
|
package top.panll.assist.utils;
import java.util.ArrayList;
import java.util.List;
public class PageInfo<T> {
//当前页
private int pageNum;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//总页数
private int pages;
//总数
private int total;
private List<T> resultData;
private List<T> list;
public PageInfo(List<T> resultData) {
this.resultData = resultData;
}
public void startPage(int page, int count) {
if (count <= 0) count = 10;
if (page <= 0) page = 1;
this.pageNum = page;
this.pageSize = count;
this.total = resultData.size();
this.pages = total%count == 0 ? total/count : total/count + 1;
int fromIndx = (page - 1) * count;
if ( fromIndx > this.total - 1) {
this.list = new ArrayList<>();
this.size = 0;
return;
}
int toIndx = page * count;
if (toIndx > this.total) {
toIndx = this.total;
}
this.list = this.resultData.subList(fromIndx, toIndx);
this.size = this.list.size();
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
|
package jforgame.server.game.skill.message;
import com.baidu.bjf.remoting.protobuf.annotation.Protobuf;
import jforgame.server.game.Modules;
import jforgame.server.game.skill.SkillDataPool;
import jforgame.socket.annotation.MessageMeta;
import jforgame.socket.message.Message;
@MessageMeta(module=Modules.SKILL, cmd=SkillDataPool.REQ_USE_SKILL)
public class ReqUseSkill extends Message {
@Protobuf
private int skillId;
public int getSkillId() {
return skillId;
}
public void setSkillId(int skillId) {
this.skillId = skillId;
}
@Override
public String toString() {
return "ReqUseSkillMessage [skillId=" + skillId + "]";
}
}
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (almaslvl@gmail.com).
* See LICENSE for details.
*/
package com.almasb.fxgl.physics.box2d.dynamics;
import com.almasb.fxgl.core.math.Vec2;
import com.almasb.fxgl.physics.HitBox;
import com.almasb.fxgl.physics.box2d.collision.AABB;
import com.almasb.fxgl.physics.box2d.collision.RayCastInput;
import com.almasb.fxgl.physics.box2d.collision.RayCastOutput;
import com.almasb.fxgl.physics.box2d.collision.broadphase.BroadPhase;
import com.almasb.fxgl.physics.box2d.collision.shapes.MassData;
import com.almasb.fxgl.physics.box2d.collision.shapes.Shape;
import com.almasb.fxgl.physics.box2d.collision.shapes.ShapeType;
import com.almasb.fxgl.physics.box2d.common.Transform;
import com.almasb.fxgl.physics.box2d.dynamics.contacts.Contact;
import com.almasb.fxgl.physics.box2d.dynamics.contacts.ContactEdge;
/**
* A fixture is used to attach a shape to a body for collision detection. A fixture inherits its
* transform from its parent. Fixtures hold additional non-geometric data such as friction,
* collision filters, etc. Fixtures are created via Body::CreateFixture.
* Note: you cannot reuse fixtures.
*
* @author daniel
*/
public final class Fixture {
private final Filter filter = new Filter();
private final Body body;
private final Shape shape;
private Object userData;
private HitBox hitBox;
private float density;
private float friction;
private float restitution;
private boolean isSensor;
private FixtureProxy[] proxies;
private int proxyCount = 0;
Fixture(Body body, FixtureDef def) {
this.body = body;
shape = def.getShape().clone();
userData = def.getUserData();
density = def.getDensity();
friction = def.getFriction();
restitution = def.getRestitution();
isSensor = def.isSensor();
filter.set(def.getFilter());
// Reserve proxy space
int childCount = shape.getChildCount();
proxies = new FixtureProxy[childCount];
for (int i = 0; i < childCount; i++) {
proxies[i] = new FixtureProxy();
}
}
/**
* @return the parent body of this fixture
*/
public Body getBody() {
return body;
}
/**
* You can modify the child shape, however you should not change the number
* of vertices because this will crash some collision caching mechanisms.
*
* @return child shape
*/
public Shape getShape() {
return shape;
}
/**
* @return the type of the child shape. You can use this to down cast to the concrete shape.
*/
public ShapeType getType() {
return shape.getType();
}
/**
* @return the contact filtering data
*/
public Filter getFilterData() {
return filter;
}
/**
* Set the contact filtering data.
* This will not update contacts until the next time step when either parent body is awake.
* This automatically calls refilter.
* This is an expensive operation and should not be called frequently.
*
* @param filter filter
*/
public void setFilterData(final Filter filter) {
this.filter.set(filter);
refilter();
}
/**
* The same as in the fixture definition, unless explicitly changed.
* Use this to store your application specific data.
*
* @return user data
*/
public Object getUserData() {
return userData;
}
/**
* Set the user data.
* Use this to store your application specific data.
*
* @param data user data
*/
public void setUserData(Object data) {
userData = data;
}
public HitBox getHitBox() {
return hitBox;
}
public void setHitBox(HitBox hitBox) {
this.hitBox = hitBox;
}
public float getDensity() {
return density;
}
public void setDensity(float density) {
this.density = density;
}
public float getFriction() {
return friction;
}
/**
* This will <b>NOT</b> change the friction of existing contacts.
*/
public void setFriction(float friction) {
this.friction = friction;
}
public float getRestitution() {
return restitution;
}
/**
* This will <b>NOT</b> change the restitution of existing contacts.
*/
public void setRestitution(float restitution) {
this.restitution = restitution;
}
/**
* @return true if the fixture / shape is a sensor (non-solid)
*/
public boolean isSensor() {
return isSensor;
}
/**
* Set if this fixture is a sensor.
*/
public void setSensor(boolean sensor) {
if (sensor != isSensor) {
body.setAwake(true);
isSensor = sensor;
}
}
public int getProxyCount() {
return proxyCount;
}
public int getProxyId(int index) {
return proxies[index].proxyId;
}
/**
* Call this if you want to establish collision that was previously disabled by
* ContactFilter::ShouldCollide.
*/
public void refilter() {
// Flag associated contacts for filtering.
ContactEdge edge = body.getContactList();
while (edge != null) {
Contact contact = edge.contact;
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
if (fixtureA == this || fixtureB == this) {
contact.flagForFiltering();
}
edge = edge.next;
}
World world = body.getWorld();
if (world == null) {
return;
}
// Touch each proxy so that new pairs may be created
BroadPhase broadPhase = world.getContactManager().broadPhase;
for (int i = 0; i < proxyCount; ++i) {
broadPhase.touchProxy(proxies[i].proxyId);
}
}
/**
* Test a point for containment in this fixture.
* This only works for convex shapes.
*
* @param p a point in world coordinates
*/
public boolean containsPoint(Vec2 p) {
return shape.containsPoint(body.m_xf, p);
}
/**
* Cast a ray against this shape.
*
* @param output the ray-cast results
* @param input the ray-cast input parameters
*/
public boolean raycast(RayCastOutput output, RayCastInput input, int childIndex) {
return shape.raycast(output, input, body.m_xf, childIndex);
}
/**
* Get the mass data for this fixture.
* The mass data is based on the density and the shape.
* The rotational inertia is about the shape's origin.
*/
public void getMassData(MassData massData) {
shape.computeMass(massData, density);
}
/**
* This AABB may be enlarged and/or stale.
* If you need a more accurate AABB, compute it using the shape and the body transform.
*
* @return the fixture's AABB
*/
public AABB getAABB(int childIndex) {
return proxies[childIndex].aabb;
}
/**
* Compute the distance from this fixture.
*
* @param p a point in world coordinates.
* @return distance
*/
public float computeDistance(Vec2 p, int childIndex, Vec2 normalOut) {
return shape.computeDistanceToOut(body.getTransform(), p, childIndex, normalOut);
}
// These support body activation/deactivation.
void createProxies(BroadPhase broadPhase, final Transform xf) {
// Create proxies in the broad-phase.
proxyCount = shape.getChildCount();
for (int i = 0; i < proxyCount; ++i) {
FixtureProxy proxy = proxies[i];
shape.computeAABB(proxy.aabb, xf, i);
proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy);
proxy.fixture = this;
proxy.childIndex = i;
}
}
void destroyProxies(BroadPhase broadPhase) {
// Destroy proxies in the broad-phase.
for (int i = 0; i < proxyCount; ++i) {
FixtureProxy proxy = proxies[i];
broadPhase.destroyProxy(proxy.proxyId);
proxy.proxyId = BroadPhase.NULL_PROXY;
}
proxyCount = 0;
}
private final AABB pool1 = new AABB();
private final AABB pool2 = new AABB();
private final Vec2 displacement = new Vec2();
void synchronize(BroadPhase broadPhase, Transform transform1, Transform transform2) {
if (proxyCount == 0) {
return;
}
for (int i = 0; i < proxyCount; ++i) {
FixtureProxy proxy = proxies[i];
// Compute an AABB that covers the swept shape (may miss some rotation effect).
AABB aabb1 = pool1;
AABB aabb2 = pool2;
shape.computeAABB(aabb1, transform1, proxy.childIndex);
shape.computeAABB(aabb2, transform2, proxy.childIndex);
proxy.aabb.combine(aabb1, aabb2);
displacement.x = transform2.p.x - transform1.p.x;
displacement.y = transform2.p.y - transform1.p.y;
broadPhase.moveProxy(proxy.proxyId, proxy.aabb, displacement);
}
}
// The proxies must be destroyed before calling this.
void destroy() {
proxies = null;
}
/**
* This proxy is used internally to connect fixtures to the broad-phase.
*/
static class FixtureProxy {
final AABB aabb = new AABB();
Fixture fixture = null;
int proxyId = BroadPhase.NULL_PROXY;
int childIndex;
// only we can create these
private FixtureProxy() { }
}
}
|
package com.amsidh.mvc.handler;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import com.amsidh.mvc.document.Album;
import com.amsidh.mvc.service.AlbumService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Component
@AllArgsConstructor
@Slf4j
public class AlbumHandler {
private final AlbumService albumService;
public HandlerFunction<ServerResponse> findAllAlbums() {
log.info("AlbumHandler findAllAlbums called");
return request -> ServerResponse.ok().body(albumService.getAllAlbums(), Album.class);
}
public HandlerFunction<ServerResponse> findAlbumsById() {
log.info("AlbumHandler findAlbumsById called");
return request -> ServerResponse.ok().body(albumService.getAlbumById(request.pathVariable("albumId")), Album.class);
}
public HandlerFunction<ServerResponse> createAlbum() {
log.info("AlbumHandler findAlbumsById called");
return request -> request.bodyToMono(Album.class).flatMap(album->ServerResponse.ok().body(albumService.saveAlbum(album), Album.class));
}
public HandlerFunction<ServerResponse> updateAlbum() {
log.info("AlbumHandler updateAlbum called");
return request -> ServerResponse.ok().body(request.bodyToMono(Album.class).flatMap(alb-> albumService.updateAlbum(request.pathVariable("albumId"), alb)), Album.class);
}
public HandlerFunction<ServerResponse> deleteAlbum() {
log.info("AlbumHandler deleteAlbum called");
return request -> ServerResponse.ok().body(albumService.deleteAlbumById(request.pathVariable("albumId")), Void.class);
}
public HandlerFunction<ServerResponse> getAlbumsByUserId() {
log.info("AlbumHandler getAlbumsByUserId called");
return request -> ServerResponse.ok().body(albumService.getAlbumsByUserId(request.pathVariable("userId")), Album.class);
}
}
|
/*
* Copyright 2010-2019 Boxfuse 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 org.flywaydb.core.internal.parser;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.api.logging.LogFactory;
import org.flywaydb.core.internal.database.base.Database;
import org.flywaydb.core.internal.database.base.Schema;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class ParsingContext {
private static final Log LOG = LogFactory.getLog(ParsingContext.class);
private static final String DEFAULT_SCHEMA_PLACEHOLDER = "flyway:defaultSchema";
private static final String USER_PLACEHOLDER = "flyway:user";
private static final String DATABASE_PLACEHOLDER = "flyway:database";
private Map<String, String> placeholders = new HashMap<>();
public Map<String, String> getPlaceholders() {
return placeholders;
}
public void populate(Database database) {
Schema schema = getDefaultSchema(database);
String catalog = getCatalog(database);
String currentUser = getUser(database);
if (schema != null) {
placeholders.put(DEFAULT_SCHEMA_PLACEHOLDER, schema.getName());
}
if (catalog != null) {
placeholders.put(DATABASE_PLACEHOLDER, catalog);
}
placeholders.put(USER_PLACEHOLDER, currentUser);
}
private String getCatalog(Database database) {
try {
return database.getMainConnection().getJdbcConnection().getCatalog();
} catch (SQLException e) {
LOG.debug("Could not get database name for " + DATABASE_PLACEHOLDER + " placeholder.");
return null;
}
}
private Schema getDefaultSchema(Database database) {
try {
return database.getMainConnection().getCurrentSchema();
} catch (FlywayException e) {
LOG.debug("Could not get schema for " + DEFAULT_SCHEMA_PLACEHOLDER + " placeholder.");
return null;
}
}
private String getUser(Database database) {
try {
return database.getCurrentUser();
} catch (FlywayException e) {
LOG.debug("Could not get user for " + USER_PLACEHOLDER + " placeholder.");
return null;
}
}
}
|
package com.znmall.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.znmall.common.utils.PageUtils;
import com.znmall.order.entity.OrderOperateHistoryEntity;
import java.util.Map;
/**
* 订单操作历史记录
*
* @author qingzhe
* @email liqingzhe86@gmail.com
* @date 2020-08-08 09:32:58
*/
public interface OrderOperateHistoryService extends IService<OrderOperateHistoryEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spi.predicate;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.type.Type;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.Collection;
import static java.util.stream.Collectors.toList;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "@type")
@JsonSubTypes({
@JsonSubTypes.Type(value = EquatableValueSet.class, name = "equatable"),
@JsonSubTypes.Type(value = SortedRangeSet.class, name = "sortable"),
@JsonSubTypes.Type(value = AllOrNoneValueSet.class, name = "allOrNone")})
public interface ValueSet
{
static ValueSet none(Type type)
{
if (type.isOrderable()) {
return SortedRangeSet.none(type);
}
if (type.isComparable()) {
return EquatableValueSet.none(type);
}
return AllOrNoneValueSet.none(type);
}
static ValueSet all(Type type)
{
if (type.isOrderable()) {
return SortedRangeSet.all(type);
}
if (type.isComparable()) {
return EquatableValueSet.all(type);
}
return AllOrNoneValueSet.all(type);
}
static ValueSet of(Type type, Object first, Object... rest)
{
if (type.isOrderable()) {
return SortedRangeSet.of(type, first, rest);
}
if (type.isComparable()) {
return EquatableValueSet.of(type, first, rest);
}
throw new IllegalArgumentException("Cannot create discrete ValueSet with non-comparable type: " + type);
}
static ValueSet copyOf(Type type, Collection<Object> values)
{
if (type.isOrderable()) {
return SortedRangeSet.copyOf(type, values.stream()
.map(value -> Range.equal(type, value))
.collect(toList()));
}
if (type.isComparable()) {
return EquatableValueSet.copyOf(type, values);
}
throw new IllegalArgumentException("Cannot create discrete ValueSet with non-comparable type: " + type);
}
static ValueSet ofRanges(Range first, Range... rest)
{
return SortedRangeSet.of(first, rest);
}
static ValueSet copyOfRanges(Type type, Collection<Range> ranges)
{
return SortedRangeSet.copyOf(type, ranges);
}
Type getType();
boolean isNone();
boolean isAll();
boolean isSingleValue();
Object getSingleValue();
boolean containsValue(Object value);
/**
* @return value predicates for equatable Types (but not orderable)
*/
default DiscreteValues getDiscreteValues()
{
throw new UnsupportedOperationException();
}
/**
* @return range predicates for orderable Types
*/
default Ranges getRanges()
{
throw new UnsupportedOperationException();
}
ValuesProcessor getValuesProcessor();
ValueSet intersect(ValueSet other);
ValueSet union(ValueSet other);
default ValueSet union(Collection<ValueSet> valueSets)
{
ValueSet current = this;
for (ValueSet valueSet : valueSets) {
current = current.union(valueSet);
}
return current;
}
ValueSet complement();
default boolean overlaps(ValueSet other)
{
return !this.intersect(other).isNone();
}
default ValueSet subtract(ValueSet other)
{
return this.intersect(other.complement());
}
default boolean contains(ValueSet other)
{
return this.union(other).equals(this);
}
String toString(ConnectorSession session);
}
|
package dev.xdark.ssvm;
import dev.xdark.ssvm.mirror.InstanceJavaClass;
import dev.xdark.ssvm.mirror.JavaClass;
import dev.xdark.ssvm.mirror.JavaField;
import dev.xdark.ssvm.mirror.JavaMethod;
import dev.xdark.ssvm.symbol.VMSymbols;
import dev.xdark.ssvm.util.VMHelper;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import static org.objectweb.asm.Opcodes.*;
/**
* Linking code.
*
* @author xDark
*/
public final class LinkResolver {
private final VMHelper helper;
private final VMSymbols symbols;
/**
* @param vm VM instance.
*/
public LinkResolver(VirtualMachine vm) {
helper = vm.getHelper();
symbols = vm.getSymbols();
}
public JavaMethod resolveMethod(JavaClass klass, String name, String desc, boolean requireMethodRef) {
if (requireMethodRef && klass.isInterface()) {
helper.throwException(symbols.java_lang_IncompatibleClassChangeError(), "Found interface " + klass.getName() + ", but class was expected");
}
return doResolveMethod(klass, name, desc);
}
public JavaMethod resolveVirtualMethod(JavaClass klass, JavaClass current, String name, String desc) {
JavaMethod method = resolveMethod(klass, name, desc, true);
if (klass.isInterface() && (method.getAccess() & ACC_PRIVATE) != 0) {
helper.throwException(symbols.java_lang_IncompatibleClassChangeError(), "private interface method requires invokespecial, not invokevirtual: method " + formatMethod(klass, name, desc) + ", caller-class: " + (current == null ? "<NULL>" : current.getInternalName()));
}
if ((method.getAccess() & ACC_STATIC) != 0) {
helper.throwException(symbols.java_lang_IncompatibleClassChangeError(), "Expected non-static method " + formatMethod(klass, name, desc));
}
return method;
}
public JavaMethod resolveInterfaceMethod(JavaClass klass, String name, String desc, boolean nonStatic) {
if (!klass.isInterface()) {
helper.throwException(symbols.java_lang_IncompatibleClassChangeError(), "Found class " + klass.getName() + ", but interface was expected");
}
JavaMethod method = doResolveMethod(klass, name, desc);
if (nonStatic && (method.getAccess() & ACC_STATIC) != 0) {
helper.throwException(symbols.java_lang_IncompatibleClassChangeError(), "Expected instance not static method " + formatMethod(klass, name, desc));
}
return method;
}
public JavaMethod resolveStaticMethod(JavaClass klass, String name, String desc) {
JavaMethod method;
if (klass.isInterface()) {
method = resolveInterfaceMethod(klass, name, desc, false);
} else {
method = resolveMethod(klass, name, desc, false);
}
if ((method.getAccess() & ACC_STATIC) == 0) {
helper.throwException(symbols.java_lang_IncompatibleClassChangeError(), "Expected static method " + formatMethod(klass, name, desc));
}
return method;
}
public JavaMethod resolveSpecialMethod(JavaClass klass, String name, String desc) {
JavaMethod method;
if (klass.isInterface()) {
method = resolveInterfaceMethod(klass, name, desc, true);
} else {
method = resolveMethod(klass, name, desc, false);
}
if (method.isConstructor() && klass != method.getOwner()) {
helper.throwException(symbols.java_lang_NoSuchMethodError(), klass.getName() + ": method " + name + desc + " not found");
}
if ((method.getAccess() & ACC_STATIC) != 0) {
helper.throwException(symbols.java_lang_IncompatibleClassChangeError(), "Expected non-static method " + formatMethod(klass, name, desc));
}
return method;
}
public JavaField resolveStaticField(InstanceJavaClass klass, String name, String desc) {
while (klass != null) {
JavaField field = klass.getStaticField(name, desc);
if (field != null) {
return field;
}
klass = klass.getSuperClass();
}
helper.throwException(symbols.java_lang_NoSuchFieldError(), name);
return null;
}
public JavaField resolveVirtualField(InstanceJavaClass klass, InstanceJavaClass current, String name, String desc) {
JavaField field = klass.getVirtualField(name, desc);
if (field == null) {
while (current != null) {
if ((field = current.getVirtualField(name, desc)) != null) {
break;
}
current = current.getSuperClass();
}
}
if (field != null) {
return field;
}
helper.throwException(symbols.java_lang_NoSuchFieldError(), name);
return null;
}
private JavaMethod doResolveMethod(JavaClass klass, String name, String desc) {
JavaMethod method = lookupMethodInClasses(klass, name, desc, false);
if (method == null && !klass.isArray()) {
method = lookupMethodInInterfaces((InstanceJavaClass) klass, name, desc);
}
if (method == null) {
helper.throwException(symbols.java_lang_NoSuchMethodError(), formatMethod(klass, name, desc));
}
return method;
}
private JavaMethod lookupMethodInClasses(JavaClass klass, String name, String desc, boolean inMethodResolve) {
JavaMethod method = uncachedLookupMethod(klass, name, desc);
if (klass.isArray()) {
return method;
}
int acc;
if (inMethodResolve &&
method != null &&
klass.isInterface() &&
(((acc = method.getAccess()) & ACC_STATIC) != 0 || (acc & ACC_PUBLIC) == 0) &&
method.getOwner() == symbols.java_lang_Object()) {
method = null;
}
if (method == null) {
InstanceJavaClass jc = (InstanceJavaClass) klass;
method = jc.getMethod(name, desc);
}
return method;
}
private JavaMethod lookupMethodInInterfaces(InstanceJavaClass klass, String name, String desc) {
Deque<InstanceJavaClass> deque = new ArrayDeque<>();
InstanceJavaClass current = klass;
do {
deque.addAll(Arrays.asList(current.getInterfaces()));
while ((klass = deque.poll()) != null) {
JavaMethod method = klass.getMethod(name, desc);
if (method != null) {
return method;
}
deque.addAll(Arrays.asList(klass.getInterfaces()));
}
} while ((current = current.getSuperclassWithoutResolving()) != null);
return null;
}
private JavaMethod uncachedLookupMethod(JavaClass klass, String name, String desc) {
if (klass.isArray()) {
return uncachedLookupMethod(symbols.java_lang_Object(), name, desc);
}
InstanceJavaClass jc = (InstanceJavaClass) klass;
while (jc != null) {
JavaMethod method = jc.getMethod(name, desc);
if (method != null) {
return method;
}
jc = jc.getSuperclassWithoutResolving();
}
return null;
}
private static String formatMethod(JavaClass klass, String name, String desc) {
return klass.getName() + '.' + name + desc;
}
}
|
package com.feiyue.entiy;
// 大小写
public class AdviseTypeBean {
private String adviseTypeId, adviseTypeName, extent;
public AdviseTypeBean() {
super();
}
public AdviseTypeBean(String adviseTypeId, String adviseTypeName,
String extent) {
super();
this.adviseTypeId = adviseTypeId;
this.adviseTypeName = adviseTypeName;
this.extent = extent;
}
public String getAdviseTypeId() {
return adviseTypeId;
}
public void setAdviseTypeId(String adviseTypeId) {
this.adviseTypeId = adviseTypeId;
}
public String getAdviseTypeName() {
return adviseTypeName;
}
public void setAdviseTypeName(String adviseTypeName) {
this.adviseTypeName = adviseTypeName;
}
public String getExtent() {
return extent;
}
public void setExtent(String extent) {
this.extent = extent;
}
}
|
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON)
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 zuo.biao.apijson.server.sql;
import static zuo.biao.apijson.RequestMethod.GET;
import static zuo.biao.apijson.RequestMethod.POST;
import static zuo.biao.apijson.SQL.AND;
import static zuo.biao.apijson.SQL.NOT;
import static zuo.biao.apijson.SQL.OR;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import zuo.biao.apijson.JSONRequest;
import zuo.biao.apijson.JSONResponse;
import zuo.biao.apijson.Log;
import zuo.biao.apijson.RequestMethod;
import zuo.biao.apijson.SQL;
import zuo.biao.apijson.StringUtil;
import zuo.biao.apijson.server.Logic;
import zuo.biao.apijson.server.Parser;
import zuo.biao.apijson.server.exception.NotExistException;
/**config model for query
* @author Lemon
*/
public class QueryConfig {
private static final String TAG = "QueryConfig";
public static final String ID = JSONResponse.KEY_ID;
public static final List<String> ARRAY_KEY_LIST;
static {
ARRAY_KEY_LIST = new ArrayList<String>();
ARRAY_KEY_LIST.add(JSONRequest.KEY_QUERY);
ARRAY_KEY_LIST.add(JSONRequest.KEY_COUNT);
ARRAY_KEY_LIST.add(JSONRequest.KEY_PAGE);
}
public static final List<String> TABLE_KEY_LIST;
static {
TABLE_KEY_LIST = new ArrayList<String>();
TABLE_KEY_LIST.add(JSONRequest.KEY_COLUMN);
TABLE_KEY_LIST.add(JSONRequest.KEY_GROUP);
TABLE_KEY_LIST.add(JSONRequest.KEY_HAVING);
TABLE_KEY_LIST.add(JSONRequest.KEY_ORDER);
}
private long id;
private RequestMethod method;
private String table;
private String values;
private Map<String, Object> where;
private String column;
private String group;
private String having;
private String order;
//array item <<<<<<<<<<
private int count;
private int page;
private int position;
private int query; //JSONRequest.query
private int type; //ObjectParser.type
//array item >>>>>>>>>>
private boolean cacheStatic;
public QueryConfig(RequestMethod method) {
setMethod(method);
}
public QueryConfig(RequestMethod method, String table) {
this(method);
setTable(table);
}
public QueryConfig(RequestMethod method, String table, Map<String, Object> where) {
this(method, table);
setWhere(where);
}
public QueryConfig(RequestMethod method, String table, String column, String values) {
this(method, table);
setColumn(column);
setValues(values);
}
public QueryConfig(RequestMethod method, String table, String[] column, String[][] values) {
this(method, table);
setColumn(column);
setValues(values);
}
public QueryConfig(RequestMethod method, int count, int page) {
this(method);
setCount(count);
setPage(page);
}
public RequestMethod getMethod() {
if (method == null) {
method = GET;
}
return method;
}
public QueryConfig setMethod(RequestMethod method) {
this.method = method;
return this;
}
public String getTable() {
return table;
}
public QueryConfig setTable(String table) {
this.table = table;
return this;
}
public String getColumn() {
return column;
}
public QueryConfig setColumn(String... keys) {
return setColumn(StringUtil.getString(keys));
}
public QueryConfig setColumn(String column) {
this.column = column;
return this;
}
public String getColumnString() throws NotExistException {
switch (getMethod()) {
case HEAD:
case POST_HEAD:
return "count(0) AS count";
case POST:
if (StringUtil.isEmpty(column, true)) {
throw new NotExistException(TAG + "getColumnString getMethod() = POST"
+ " >> StringUtil.isEmpty(column, true)");
}
return "(" + column + ")";
default:
column = StringUtil.getString(column);
if (column.isEmpty()) {
return "*";
}
return column.contains(":") == false ? column : column.replaceAll(":", " AS ");//不能在这里改,后续还要用到:
}
}
public String getGroup() {
return group;
}
public QueryConfig setGroup(String... keys) {
return setGroup(StringUtil.getString(keys));
}
public QueryConfig setGroup(String group) {
this.group = group;
return this;
}
public String getGroupString() {
group = StringUtil.getTrimedString(group);
return group.isEmpty() ? "" : " GROUP BY " + group;
}
public String getHaving() {
return having;
}
public QueryConfig setHaving(String... conditions) {
return setHaving(StringUtil.getString(conditions));
}
public QueryConfig setHaving(String having) {
this.having = having;
return this;
}
public String getHavingString() {
having = StringUtil.getTrimedString(having);
return having.isEmpty() ? "" : " HAVING " + having;
}
public String getOrder() {
return order;
}
public QueryConfig setOrder(String... conditions) {
return setOrder(StringUtil.getString(conditions));
}
public QueryConfig setOrder(String order) {
this.order = order;
return this;
}
public String getOrderString() {
order = StringUtil.getTrimedString(order);
if (order.isEmpty()) {
return "";
}
if (order.contains("+")) {//replace没有包含的replacement会崩溃
order = order.replaceAll("\\+", " ASC ");
}
if (order.contains("-")) {
order = order.replaceAll("-", " DESC ");
}
return " ORDER BY " + order;
}
public long getId() {
return id;
}
public QueryConfig setId(long id) {
this.id = id;
return this;
}
public String getValues() {
return values;
}
public String getValuesString() {
return values;
}
public QueryConfig setValues(String[][] values) {
String s = "";
if (values != null && values.length > 0) {
String[] items = new String[values.length];
for (int i = 0; i < values.length; i++) {
items[i] = "(" + StringUtil.getString(values[i]) + ")";
}
s = StringUtil.getString(items);
}
return setValues(s);
}
public QueryConfig setValues(String values) {
this.values = values;
return this;
}
public Map<String, Object> getWhere() {
return where;
}
public QueryConfig setWhere(Map<String, Object> where) {
this.where = where;
return this;
}
public int getCount() {
return count;
}
public QueryConfig setCount(int count) {
this.count = count;
return this;
}
public int getPage() {
return page;
}
public QueryConfig setPage(int page) {
this.page = page;
return this;
}
public int getPosition() {
return position;
}
public QueryConfig setPosition(int position) {
this.position = position;
return this;
}
public int getQuery() {
return query;
}
public QueryConfig setQuery(int query) {
this.query = query;
return this;
}
public int getType() {
return type;
}
public QueryConfig setType(int type) {
this.type = type;
return this;
}
public QueryConfig setCacheStatic(boolean cacheStatic) {
this.cacheStatic = cacheStatic;
return this;
}
public boolean isCacheStatic() {
return cacheStatic;
}
/**获取限制数量
* @return
*/
public String getLimitString() {
return getLimitString(getPage(), getCount());// + 1);
}
/**获取限制数量
* @param limit
* @return
*/
public static String getLimitString(int page, int count) {
return count <= 0 ? "" : " LIMIT " + page*count + ", " + count;
}
//WHERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取WHERE
* @return
* @throws Exception
*/
public String getWhereString() throws Exception {
return getWhereString(getMethod(), getWhere());
}
/**获取WHERE
* @param method
* @param where
* @return
* @throws Exception
*/
public static String getWhereString(RequestMethod method, Map<String, Object> where) throws Exception {
Set<String> set = where == null ? null : where.keySet();
if (set != null && set.size() > 0) {
String whereString = "";
boolean isFirst = true;
int keyType = 0;// 0 - =; 1 - $, 2 - {}
Object value;
for (String key : set) {
Log.d(TAG, "getWhereString key = " + key);
//避免筛选到全部 value = key == null ? null : where.get(key);
if (key == null || key.startsWith("@") || key.endsWith("()")) {//关键字||方法, +或-直接报错
Log.d(TAG, "getWhereString key == null || key.startsWith(@) || key.endsWith(()) >> continue;");
continue;
}
if (key.endsWith("@")) {//引用
key = key.substring(0, key.lastIndexOf("@"));
// throw new IllegalArgumentException(TAG + ".getWhereString: 字符 " + key + " 不合法!");
}
if (key.endsWith("$")) {
keyType = 1;
} else if (key.endsWith("{}")) {
keyType = 2;
} else if (key.endsWith("<>")) {
keyType = 3;
}
value = where.get(key);
key = Parser.getRealKey(method, key, false, true);
String condition = "";
switch (keyType) {
case 1:
condition = getSearchString(key, value);
break;
case 2:
condition = getRangeString(key, value);
break;
case 3:
condition = getContainString(key, value);
break;
default:
condition = (key + "='" + value + "'");
break;
}
if (StringUtil.isEmpty(condition, true)) {//避免SQL条件连接错误
continue;
}
whereString += (isFirst ? "" : AND) + condition;
isFirst = false;
}
if (whereString.isEmpty() == false) {
return " WHERE " + whereString;
}
}
return "";
}
//$ search <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**search key match value
* @param in
* @return {@link #getSearchString(String, Object[], int)}
* @throws IllegalArgumentException
*/
public static String getSearchString(String key, Object value) throws IllegalArgumentException {
if (value == null) {
return "";
}
Logic logic = new Logic(key);
key = logic.getKey();
Log.i(TAG, "getRangeString key = " + key);
if (value instanceof JSONArray == false) {//TODO 直接掉Like性能最好!
JSONArray array = new JSONArray();
array.add(value);
value = array;
}
if (((JSONArray) value).isEmpty()) {
return "";
}
return getSearchString(key, ((JSONArray) value).toArray(), logic.getType());
}
/**search key match values
* @param in
* @return LOGIC [ key LIKE 'values[i]' ]
* @throws IllegalArgumentException
*/
public static String getSearchString(String key, Object[] values, int type) throws IllegalArgumentException {
if (values == null || values.length <= 0) {
return "";
}
String condition = "";
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof String == false) {
throw new IllegalArgumentException(key + "$\":value 中value只能为String或JSONArray<String>!");
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR)) + getLikeString(key, values[i]);
}
return (Logic.isNot(type) ? NOT : "") + "(" + condition + ")";
}
/**WHERE key LIKE 'value'
* @param key endsWith("!") ? key = key.substring(0, key.length() - 1) + NOT;
* @param value
* @return key LIKE 'value'
*/
public static String getLikeString(String key, Object value) {
return key + " LIKE '" + value + "'";
}
//$ search >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//{} range <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE key > 'key0' AND key <= 'key1' AND ...
* @param key
* @param range "condition0,condition1..."
* @return key condition0 AND key condition1 AND ...
* @throws Exception
*/
public static String getRangeString(String key, Object range) throws Exception {
Log.i(TAG, "getRangeString key = " + key);
if (range == null) {//依赖的对象都没有给出有效值,这个存在无意义。如果是客户端传的,那就能在客户端确定了。
throw new NotExistException(TAG + "getRangeString(" + key + ", " + range
+ ") range == null");
}
Logic logic = new Logic(key);
key = logic.getKey();
Log.i(TAG, "getRangeString key = " + key);
if (range instanceof JSONArray) {
if (logic.isOr() || logic.isNot()) {
return key + getInString(key, ((JSONArray) range).toArray(), logic.isNot());
}
throw new IllegalArgumentException(key + "{}\":[] 中key末尾的逻辑运算符只能用'|','!'中的一种 !");
}
if (range instanceof String) {//非Number类型需要客户端拼接成 < 'value0', >= 'value1'这种
String[] conditions = StringUtil.split((String) range);
String condition = "";
if (conditions != null) {
int index;
for (int i = 0; i < conditions.length; i++) {//对函数条件length(key)<=5这种不再在开头加key
index = conditions[i] == null ? -1 : conditions[i].indexOf("(");
condition += ((i <= 0 ? "" : (logic.isAnd() ? AND : OR))//连接方式
+ (index >= 0 && index < conditions[i].indexOf(")") ? "" : key + " ")//函数和非函数条件
+ conditions[i]);//单个条件
}
}
if (condition.isEmpty()) {
return "";
}
condition = "(" + condition + ")";
return logic.isNot() ? NOT + condition : condition;
}
throw new IllegalArgumentException(key + "{}\":range 中range只能是 用','分隔条件的字符串 或者 可取选项JSONArray!");
}
/**WHERE key IN ('key0', 'key1', ... )
* @param in
* @return IN ('key0', 'key1', ... )
* @throws NotExistException
*/
public static String getInString(String key, Object[] in, boolean not) throws NotExistException {
String condition = "";
if (in != null) {//返回 "" 会导致 id:[] 空值时效果和没有筛选id一样!
for (int i = 0; i < in.length; i++) {
condition += ((i > 0 ? "," : "") + "'" + in[i] + "'");
}
}
if (condition.isEmpty()) {//条件如果存在必须执行,不能忽略。条件为空会导致出错,又很难保证条件不为空(@:条件),所以还是这样好
throw new NotExistException(TAG + ".getInString(" + key + ", [], " + not
+ ") >> condition.isEmpty() >> IN()");
}
return (not ? NOT : "") + " IN " + "(" + condition + ")";
}
//{} range >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//<> contain <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**WHERE key contains value
* @param key
* @param value
* @return {@link #getContainString(String, Object[], int)}
* @throws NotExistException
*/
public static String getContainString(String key, Object value) throws NotExistException {
if (value == null) {
return "";
}
Logic logic = new Logic(key);
key = logic.getKey();
Log.i(TAG, "getRangeString key = " + key);
if (value instanceof JSONArray == false) {//TODO 直接调Like性能最好!
JSONArray array = new JSONArray();
array.add(value);
value = array;
}
return getContainString(key, ((JSONArray) value).toArray(), logic.getType());
}
/**WHERE key contains childs
* @param key
* @param childs null ? "" : (empty ? no child : contains childs)
* @param type |, &, !
* @return LOGIC [ ( key LIKE '[" + childs[i] + "]' OR key LIKE '[" + childs[i] + ", %'
* OR key LIKE '%, " + childs[i] + ", %' OR key LIKE '%, " + childs[i] + "]' ) ]
* @throws IllegalArgumentException
*/
public static String getContainString(String key, Object[] childs, int type) throws IllegalArgumentException {
String condition = "";
if (childs != null) {
for (int i = 0; i < childs.length; i++) {
if (childs[i] != null) {
if (childs[i] instanceof JSON) {
throw new IllegalArgumentException(key + "<>\":value 中value类型不能为JSON!");
}
if (childs[i] instanceof String) {
childs[i] = "\"" + childs[i] + "\"";
}
condition += (i <= 0 ? "" : (Logic.isAnd(type) ? AND : OR))
+ getSearchString(
key
, new String[]{
"[" + childs[i] + "]", //全等
"[" + childs[i] + ", %", //开始
"%, " + childs[i] + ", %", //中间
"%, " + childs[i] + "]" //末尾
}
, Logic.TYPE_OR
);
}
}
if (condition.isEmpty()) {
condition = (SQL.isEmpty(key, true) + OR + getLikeString(key, "[]"));
}
}
if (condition.isEmpty()) {
return "";
}
return (Logic.isNot(type) ? NOT : "") + "(" + condition + ")";
}
//<> contain >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//WHERE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//SET <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**获取SET
* @return
* @throws Exception
*/
public String getSetString() throws Exception {
return getSetString(getMethod(), getWhere());
}
/**获取SET
* @param method
* @param where
* @return
* @throws Exception
*/
public static String getSetString(RequestMethod method, Map<String, Object> where) throws Exception {
Set<String> set = where == null ? null : where.keySet();
if (set != null && set.size() > 0) {
if (where.containsKey(ID) == false) {
throw new IllegalArgumentException("请设置" + ID + "!");
}
String setString = "";
boolean isFirst = true;
int keyType = 0;// 0 - =; 1 - +, 2 - -
Object value;
for (String key : set) {
//避免筛选到全部 value = key == null ? null : where.get(key);
if (key == null || ID.equals(key)) {
continue;
}
if (key.endsWith("+")) {
keyType = 1;
} else if (key.endsWith("-")) {
keyType = 2;
}
value = where.get(key);
key = Parser.getRealKey(method, key, false, true);
setString += (isFirst ? "" : ", ") + (key + "=" + (keyType == 1 ? getAddString(key, value) : (keyType == 2
? getRemoveString(key, value) : "'" + value + "'") ) );
isFirst = false;
}
if (setString.isEmpty()) {
throw new NotExistException(TAG + "getSetString >> setString.isEmpty()");
}
return " SET " + setString + " WHERE " + ID + "='" + where.get(ID) + "' ";
}
return "";
}
/**SET key = CONCAT (key, 'value')
* @param key
* @param value
* @return CONCAT (key, 'value')
* @throws IllegalArgumentException
*/
public static String getAddString(String key, Object value) throws IllegalArgumentException {
if (value instanceof Number) {
return key + " + " + value;
}
if (value instanceof String) {
return " CONCAT (" + key + ", '" + value + "') ";
}
throw new IllegalArgumentException(key + "+ 对应的值 " + value + " 不是Number,String,Array中的任何一种!");
}
/**SET key = REPLACE (key, 'value', '')
* @param key
* @param value
* @return REPLACE (key, 'value', '')
* @throws IllegalArgumentException
*/
public static String getRemoveString(String key, Object value) throws IllegalArgumentException {
if (value instanceof Number) {
return key + " - " + value;
}
if (value instanceof String) {
return " REPLACE (" + key + ", '" + value + "', '') ";
}
throw new IllegalArgumentException(key + "- 对应的值 " + value + " 不是Number,String,Array中的任何一种!");
}
//SET >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/**获取查询配置
* @param table
* @param request
* @return
*/
public static synchronized QueryConfig newQueryConfig(RequestMethod method, String table, JSONObject request) {
QueryConfig config = new QueryConfig(method, table);
if (method == POST && request != null && request.get(ID) == null) {
request.put(ID, System.currentTimeMillis());
}
Set<String> set = request == null ? null : request.keySet();
if (set != null) {
String column = request.getString(JSONRequest.KEY_COLUMN);
String group = request.getString(JSONRequest.KEY_GROUP);
String having = request.getString(JSONRequest.KEY_HAVING);
String order = request.getString(JSONRequest.KEY_ORDER);
request.remove(JSONRequest.KEY_COLUMN);
request.remove(JSONRequest.KEY_GROUP);
request.remove(JSONRequest.KEY_HAVING);
request.remove(JSONRequest.KEY_ORDER);
if (method == POST) {
config.setColumn(StringUtil.getString(set.toArray(new String[]{})));
String valuesString = "";
Collection<Object> valueCollection = request.values();
Object[] values = valueCollection == null || valueCollection.isEmpty() ? null : valueCollection.toArray();
if (values != null) {
for (int i = 0; i < values.length; i++) {
valuesString += ((i > 0 ? "," : "") + "'" + values[i] + "'");
}
}
config.setValues("(" + valuesString + ")");
} else {
config.setColumn(column);
Map<String, Object> transferredRequest = new HashMap<String, Object>();
Object value;
for (String key : set) {
value = request.get(key);
if (value instanceof JSONObject == false) {//只允许常规Object
transferredRequest.put(key, value);//一样 instanceof JSONArray ? JSON.toJSONString(value) : value);
}
}
config.setWhere(transferredRequest);
}
config.setGroup(group);
config.setHaving(having);
config.setOrder(order);
//后面还可能用到,要还原
request.put(JSONRequest.KEY_COLUMN, column);
request.put(JSONRequest.KEY_GROUP, group);
request.put(JSONRequest.KEY_HAVING, having);
request.put(JSONRequest.KEY_ORDER, order);
}
try {
config.setId(request.getLongValue(ID));
} catch (Exception e) {
// TODO: handle exception
}
return config;
}
/**
* @return
* @throws Exception
*/
public String getSQL() throws Exception {
return getSQL(this);
}
/**
* @param config
* @return
* @throws Exception
*/
public static String getSQL(QueryConfig config) throws Exception {
if (config == null || StringUtil.isNotEmpty(config.getTable(), true) == false) {
Log.i(TAG, "getSQL config == null || StringUtil.isNotEmpty(config.getTable(), true) == false >> return null;");
return null;
}
RequestMethod method = config.getMethod();
switch (method) {
case POST:
return "INSERT INTO " + config.getTable() + config.getColumnString() + " VALUES" + config.getValuesString();
case PUT:
return "UPDATE " + config.getTable() + config.getSetString();
case DELETE:
return "DELETE FROM " + config.getTable() + config.getWhereString();
default:
return "SELECT "+ config.getColumnString() + " FROM " + config.getTable() + config.getWhereString()
+ (RequestMethod.isGetMethod(method, true) == false ?
"" : config.getGroupString() + config.getHavingString() + config.getOrderString() )
+ config.getLimitString();
}
}
}
|
/**
* Copyright (C) 2014-2018 LinkedIn Corp. (pinot-core@linkedin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pinot.thirdeye.notification;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import org.apache.commons.mail.HtmlEmail;
import org.apache.pinot.thirdeye.notification.commons.EmailEntity;
public class ContentFormatterUtils {
public static String getHtmlContent(String htmlPath) throws IOException {
StringBuilder htmlContent;
try (BufferedReader br = new BufferedReader(new FileReader(htmlPath))) {
htmlContent = new StringBuilder();
for (String line = br.readLine(); line != null; line = br.readLine()) {
htmlContent.append(line).append("\n");
}
}
return htmlContent.toString();
}
public static String getEmailHtml(EmailEntity emailEntity) throws Exception {
HtmlEmail email = emailEntity.getContent();
Field field = email.getClass().getDeclaredField("html");
field.setAccessible(true);
return field.get(email).toString();
}
}
|
/**
* Copyright 2006 StartNet s.r.o.
*
* Distributed under MIT license
*/
package cz.startnet.utils.pgdiff.schema;
import java.util.Locale;
/**
* Utilities for {@link PgColumn}.
*
* @author fordfrog
*/
public class PgColumnUtils {
/**
* Returns default value for given column type. If no default value is
* specified then null is returned.
*
* @param type column type
*
* @return found default value or null
*/
public static String getDefaultValue(final String type) {
final String defaultValue;
final String adjType = type.toLowerCase(Locale.ENGLISH);
if ("smallint".equals(adjType)
|| "integer".equals(adjType)
|| "bigint".equals(adjType)
|| adjType.startsWith("decimal")
|| adjType.startsWith("numeric")
|| "real".equals(adjType)
|| "double precision".equals(adjType)
|| "int2".equals(adjType)
|| "int4".equals(adjType)
|| "int8".equals(adjType)
|| adjType.startsWith("float")
|| "double".equals(adjType)
|| "money".equals(adjType)) {
defaultValue = "0";
} else if (adjType.startsWith("character varying")
|| adjType.startsWith("varchar")
|| adjType.startsWith("character")
|| adjType.startsWith("char")
|| "text".equals(adjType)) {
defaultValue = "''";
} else if ("boolean".equals(adjType)) {
defaultValue = "false";
} else {
defaultValue = null;
}
return defaultValue;
}
/**
* Creates a new PgColumnUtils object.
*/
private PgColumnUtils() {
}
}
|
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class FrameworkNameReducerTest {
private FrameworkNameReducer uut;
@Before
public void init() {
uut = new FrameworkNameReducer();
}
@Test
public void parseStringWithPrefixCorrectly() {
// Given
String input = "/discussions/assets/libs/css3-mediaqueries.js";
String expected = "css3-mediaqueries";
// When
String actual = uut.reduce(input);
// Then
Assert.assertEquals(expected, actual);
}
@Test
public void parseStringWithEnCorrectly() {
// Given
String input = "js/explore-qlist.en.js";
String expected = "explore-qlist";
// When
String actual = uut.reduce(input);
// Then
Assert.assertEquals(expected, actual);
}
@Test
public void parseStringWithMinCorrectly() {
// Given
String input = "js/bootstrap.min.js";
String expected = "bootstrap";
// When
String actual = uut.reduce(input);
// Then
Assert.assertEquals(expected, actual);
}
@Test
public void parseStringWithMultipleEnCorrectly() {
// Given
String input = "js/begin-edit-event.en.js";
String expected = "begin-edit-event";
// When
String actual = uut.reduce(input);
// Then
Assert.assertEquals(expected, actual);
}
@Test
public void parseStringWithBase64Correctly() {
// Given
String input = "jquery.base64.min.js";
String expected = "jquery";
// When
String actual = uut.reduce(input);
// Then
Assert.assertEquals(expected, actual);
}
}
|
/*
* Copyright 2020-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.r2dbc.core;
import reactor.core.publisher.Mono;
import org.springframework.data.relational.core.query.Query;
import org.springframework.data.relational.core.query.Update;
import org.springframework.data.relational.core.sql.SqlIdentifier;
/**
* The {@link ReactiveUpdateOperation} interface allows creation and execution of {@code UPDATE} operations in a fluent
* API style.
* <p>
* The starting {@literal domainType} is used for mapping the {@link Query} provided via {@code matching}, as well as
* the {@link Update} via {@code apply}.
* <p>
* By default, the table to operate on is derived from the initial {@literal domainType} and can be defined there via
* the {@link org.springframework.data.relational.core.mapping.Table} annotation. Using {@code inTable} allows a
* developer to override the table name for the execution.
*
* <pre>
* <code>
* update(Jedi.class)
* .table("star_wars")
* .matching(query(where("firstname").is("luke")))
* .apply(update("lastname", "skywalker"))
* .all();
* </code>
* </pre>
*
* @author Mark Paluch
* @since 1.1
*/
public interface ReactiveUpdateOperation {
/**
* Begin creating an {@code UPDATE} operation for the given {@link Class domainType}.
*
* @param domainType {@link Class type} of domain object to update; must not be {@literal null}.
* @return new instance of {@link ReactiveUpdate}.
* @throws IllegalArgumentException if {@link Class domainType} is {@literal null}.
* @see ReactiveUpdate
*/
ReactiveUpdate update(Class<?> domainType);
/**
* Table override (optional).
*/
interface UpdateWithTable extends TerminatingUpdate {
/**
* Explicitly set the {@link String name} of the table on which to perform the update.
* <p>
* Skip this step to use the default table derived from the {@link Class domain type}.
*
* @param table {@link String name} of the table; must not be {@literal null} or empty.
* @return new instance of {@link UpdateWithQuery}.
* @throws IllegalArgumentException if {@link String table} is {@literal null} or empty.
* @see UpdateWithQuery
*/
default UpdateWithQuery inTable(String table) {
return inTable(SqlIdentifier.unquoted(table));
}
/**
* Explicitly set the {@link SqlIdentifier name} of the table on which to perform the update.
* <p>
* Skip this step to use the default table derived from the {@link Class domain type}.
*
* @param table {@link SqlIdentifier name} of the table; must not be {@literal null}.
* @return new instance of {@link UpdateWithQuery}.
* @throws IllegalArgumentException if {@link SqlIdentifier table} is {@literal null}.
* @see UpdateWithQuery
*/
UpdateWithQuery inTable(SqlIdentifier table);
}
/**
* Define a {@link Query} used as the filter for the {@link Update}.
*/
interface UpdateWithQuery extends TerminatingUpdate {
/**
* Filter rows to update by the given {@link Query}.
*
* @param query {@link Query} used as a filter in the update; must not be {@literal null}.
* @return new instance of {@link TerminatingUpdate}.
* @throws IllegalArgumentException if {@link Query} is {@literal null}.
* @see Query
* @see TerminatingUpdate
*/
TerminatingUpdate matching(Query query);
}
/**
* Trigger {@code UPDATE} execution by calling one of the terminating methods.
*/
interface TerminatingUpdate {
/**
* Update all matching rows in the table.
*
* @return the number of affected rows by the update; never {@literal null}.
* @see Mono
*/
Mono<Integer> apply(Update update);
}
/**
* The {@link ReactiveUpdate} interface provides methods for constructing {@code UPDATE} operations in a fluent way.
*/
interface ReactiveUpdate extends UpdateWithTable, UpdateWithQuery {}
}
|
package com.lcmf.mmgo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.sip.SipSession;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import com.lcmf.mmgo.recyclemenu.HolyTsMainActivity;
import com.tencent.bugly.crashreport.CrashReport;
import java.util.Random;
import cdc.sed.yff.AdManager;
public class SplashActivity extends Activity {
private final String TAG = "---SplashActivity---";
//加载三个动画
Animation mFadeIn;
Animation mFadeInScale;
Animation mFadeOut;
//图片控件
ImageView mImageView;
//背景图片
View mView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CrashReport.initCrashReport(getApplicationContext(), "18df439d92", false);
//AdManager.getInstance(SplashActivity.this.getApplicationContext()).init("98b79534d27dd504", "a44a477c4f5c8b0a", true);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
mImageView = (ImageView)findViewById(R.id.image);
//mView = (View)findViewById(R.id.idview);
int[] arrImage = {
R.drawable.cake,
R.drawable.lyq1,
R.drawable.entrance3,
R.drawable.sky,
R.drawable.snow,
R.drawable.tower,
R.drawable.cl,
R.drawable.tt,
R.drawable.dy
};
Random r = new Random();
int ran1 = r.nextInt(arrImage.length);
Log.v(TAG, "number:" + String.valueOf(ran1));
mImageView.setImageResource(arrImage[2]);
//1、先判断版本是不是首次运行
SharedPreferences mVersion = getSharedPreferences("version", MODE_PRIVATE);
int nVerTimes = mVersion.getInt("times", 0);
if(Integer.compare(nVerTimes, 1) != 0){
SharedPreferences.Editor editor = getSharedPreferences("version", MODE_PRIVATE).edit();
editor.putInt("times", 1);
editor.apply();
}else {
Intent intent = new Intent(SplashActivity.this, HolyTsMainActivity.class);
startActivity(intent);
finish();
}
//打印日志
Log.v(TAG, "加载Splash动画");
//2.初始化动画
initAnim();
//3.初始化响应
initListener();
}
private void initAnim(){
mFadeIn = AnimationUtils.loadAnimation(this, R.anim.welcome_fade_in);
mFadeIn.setDuration(500);
mFadeInScale = AnimationUtils.loadAnimation(this, R.anim.welcome_fade_in_scale);
mFadeInScale.setDuration(2000);
mFadeOut = AnimationUtils.loadAnimation(this, R.anim.welcome_fade_out);
mFadeOut.setDuration(500);
mImageView.startAnimation(mFadeIn);
}
private void initListener(){
mFadeIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mImageView.startAnimation(mFadeInScale);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mFadeInScale.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mImageView.startAnimation(mFadeOut);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mFadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
Intent intent = new Intent(SplashActivity.this, HolyTsMainActivity.class);
startActivity(intent);
finish();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
|
package com.atguigu.gulimall.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.gulimall.product.entity.SpuInfoEntity;
import java.util.Map;
/**
* spu信息
*
* @author Vegedog
* @email vegedog@qq.com
* @date 2020-05-21 22:16:59
*/
public interface SpuInfoService extends IService<SpuInfoEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
package chaosnetworkz.java.samples.soccermanager;
public interface Freundschaftsspiel {
String getHeimMannschaft();
String getGastMannschaft();
int getHeimPunkte();
int getGastPunkte();
String getErgebnisText();
}
|
package com.ifknow.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author ifknow
* @since 2020-09-04
*/
@RestController
public class UserController {
@PostMapping("login")
public String name(String username, String password) {
String result = "已登录";
// 获取当前登录用户
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
if (!currentUser.isAuthenticated()) {
try {
// 会触发com.shiro.config.MyShiroRealm的doGetAuthenticationInfo方法
currentUser.login(token);
result = "登录成功";
} catch (UnknownAccountException e) {
result = "用户名错误";
} catch (IncorrectCredentialsException e) {
result = "密码错误";
}
}
return result;
}
@GetMapping("logout")
public void logout() {
Subject currentUser = SecurityUtils.getSubject();
currentUser.logout();
}
@RequiresPermissions("role:update")
@GetMapping("/role")
public String name() {
return "hello";
}
@RequiresPermissions("user:select")
@GetMapping("/role2")
public String permission() {
return "hello sel";
}
}
|
//
// ========================================================================
// Copyright (c) 1995-2012 Sabre Holdings.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.ant.types;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jetty.server.handler.ContextHandler;
/**
* Specifies <code><contextHandlers/></code> element in web app configuration.
*/
public class ContextHandlers
{
private List<ContextHandler> contextHandlers = new ArrayList<ContextHandler>();
public void add(ContextHandler handler)
{
contextHandlers.add(handler);
}
public List<ContextHandler> getContextHandlers()
{
return contextHandlers;
}
}
|
package com.mapzen.android.lost.internal;
import com.mapzen.android.lost.BaseRobolectricTest;
import com.mapzen.android.lost.api.LocationAvailability;
import com.mapzen.android.lost.api.LocationCallback;
import com.mapzen.android.lost.api.LocationRequest;
import com.mapzen.android.lost.api.LocationResult;
import com.mapzen.android.lost.api.LostApiClient;
import com.mapzen.lost.BuildConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Looper;
import java.util.ArrayList;
import java.util.List;
import static android.location.LocationManager.GPS_PROVIDER;
import static com.mapzen.android.lost.api.LocationAvailability.EXTRA_LOCATION_AVAILABILITY;
import static com.mapzen.android.lost.api.LocationResult.EXTRA_LOCATION_RESULT;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.robolectric.RuntimeEnvironment.application;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, manifest = Config.NONE)
public class LostClientManagerTest extends BaseRobolectricTest {
Clock clock;
HandlerFactory handlerFactory;
LostClientManager manager;
LostApiClient client;
@Before public void setup() throws Exception {
clock = mock(Clock.class);
handlerFactory = new TestHandlerFactory();
manager = new LostClientManager(clock, handlerFactory);
client = new LostApiClient.Builder(application).build();
}
@Test public void shouldHaveZeroClientCount() {
assertThat(manager.numberOfClients()).isEqualTo(0);
}
@Test public void addClient_shouldIncreaseClientCount() {
manager.addClient(client);
assertThat(manager.numberOfClients()).isEqualTo(1);
manager.removeClient(client);
}
@Test public void removeClient_shouldDecreaseClientCount() {
manager.addClient(client);
LostApiClient anotherClient = new LostApiClient.Builder(application).build();
manager.addClient(anotherClient);
assertThat(manager.numberOfClients()).isEqualTo(2);
manager.removeClient(client);
assertThat(manager.numberOfClients()).isEqualTo(1);
manager.removeClient(anotherClient);
}
@Test(expected = IllegalArgumentException.class)
public void addListener_shouldThrowExceptionIfClientWasNotAdded() throws Exception {
manager.addListener(client, LocationRequest.create(), new TestLocationListener());
}
@Test(expected = IllegalArgumentException.class)
public void addPendingIntent_shouldThrowExceptionIfClientWasNotAdded() throws Exception {
manager.addPendingIntent(client, LocationRequest.create(), mock(PendingIntent.class));
}
@Test(expected = IllegalArgumentException.class)
public void addLocationCallback_shouldThrowExceptionIfClientWasNotAdded() throws Exception {
manager.addLocationCallback(client, LocationRequest.create(), new TestLocationCallback(),
mock(Looper.class));
}
@Test public void addListener_shouldAddListenerForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationListener listener = new TestLocationListener();
manager.addListener(client, request, listener);
assertThat(manager.getLocationListeners().get(client)).contains(listener);
}
@Test public void addPendingIntent_shouldAddPendingIntentForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
PendingIntent pendingIntent = mock(PendingIntent.class);
manager.addPendingIntent(client, request, pendingIntent);
assertThat(manager.getPendingIntents().get(client)).contains(pendingIntent);
}
@Test public void addLocationCallback_shouldAddLocationCallbackForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationCallback callback = new TestLocationCallback();
Looper looper = mock(Looper.class);
manager.addLocationCallback(client, request, callback, looper);
assertThat(manager.getLocationCallbacks().get(client)).contains(callback);
}
@Test public void removeListener_shouldRemoveListenerForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationListener listener = new TestLocationListener();
manager.addListener(client, request, listener);
manager.removeListener(client, listener);
assertThat(manager.getLocationListeners().get(client)).isEmpty();
}
@Test public void removeListener_shouldSendUpdateImmediatelyOnReAdd() throws Exception {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationListener listener = new TestLocationListener();
manager.addListener(client, request, listener);
manager.reportLocationChanged(mock(Location.class));
assertThat(listener.getAllLocations().size()).isEqualTo(1);
manager.removeListener(client, listener);
manager.addListener(client, request, listener);
manager.reportLocationChanged(mock(Location.class));
assertThat(listener.getAllLocations().size()).isEqualTo(2);
}
@Test public void removePendingIntent_shouldRemovePendingIntentForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
PendingIntent pendingIntent = mock(PendingIntent.class);
manager.addPendingIntent(client, request, pendingIntent);
manager.removePendingIntent(client, pendingIntent);
assertThat(manager.getPendingIntents().get(client)).isEmpty();
}
@Test public void removePendingIntent_shouldSendUpdateImmediatelyOnReAdd() throws Exception {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
PendingIntent pendingIntent = mock(PendingIntent.class);
manager.addPendingIntent(client, request, pendingIntent);
List<Location> locations = new ArrayList();
manager.sendPendingIntent(mock(Context.class), mock(Location.class),
mock(LocationAvailability.class), LocationResult.create(locations));
verify(pendingIntent).send(any(Context.class), anyInt(), any(Intent.class));
manager.removePendingIntent(client, pendingIntent);
manager.addPendingIntent(client, request, pendingIntent);
manager.sendPendingIntent(mock(Context.class), mock(Location.class),
mock(LocationAvailability.class), LocationResult.create(locations));
verify(pendingIntent, times(2)).send(any(Context.class), anyInt(), any(Intent.class));
}
@Test public void removeLocationCallback_shouldRemoveLocationCallbackForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationCallback callback = new TestLocationCallback();
Looper looper = mock(Looper.class);
manager.addLocationCallback(client, request, callback, looper);
manager.removeLocationCallback(client, callback);
assertThat(manager.getLocationCallbacks().get(client)).isEmpty();
}
@Test public void removeLocationCallback_shouldSendUpdateImmediatelyOnReAdd() throws Exception {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
LocationCallback callback = mock(LocationCallback.class);
Looper looper = mock(Looper.class);
manager.addLocationCallback(client, request, callback, looper);
List<Location> locations = new ArrayList();
manager.reportLocationResult(mock(Location.class), LocationResult.create(locations));
verify(callback).onLocationResult(any(LocationResult.class));
manager.removeLocationCallback(client, callback);
manager.addLocationCallback(client, request, callback, looper);
manager.reportLocationResult(mock(Location.class), LocationResult.create(locations));
verify(callback, times(2)).onLocationResult(any(LocationResult.class));
}
@Test public void reportLocationChanged_shouldNotifyListener() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationListener listener = new TestLocationListener();
manager.addListener(client, request, listener);
Location location = new Location("test");
manager.reportLocationChanged(location);
assertThat(listener.getAllLocations()).contains(location);
}
@Test public void sendPendingIntent_shouldFireIntent() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
Intent intent = new Intent(application,
FusedLocationProviderServiceDelegateTest.TestService.class);
PendingIntent pendingIntent = PendingIntent.getService(application, 0, intent, 0);
manager.addPendingIntent(client, request, pendingIntent);
Location location = new Location("test");
LocationAvailability availability = new LocationAvailability(true);
ArrayList<Location> locations = new ArrayList<>();
locations.add(location);
LocationResult result = LocationResult.create(locations);
manager.sendPendingIntent(application, location, availability, result);
Intent nextStartedService = ShadowApplication.getInstance().getNextStartedService();
assertThat(nextStartedService).isNotNull();
assertThat(nextStartedService.getParcelableExtra(
EXTRA_LOCATION_AVAILABILITY)).isNotNull();
assertThat(nextStartedService.getParcelableExtra(
EXTRA_LOCATION_RESULT)).isNotNull();
}
@Test public void reportLocationResult_shouldNotifyCallback() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationCallback callback = new TestLocationCallback();
Looper looper = Looper.myLooper();
manager.addLocationCallback(client, request, callback, looper);
Location location = new Location("test");
ArrayList<Location> locations = new ArrayList<>();
locations.add(location);
LocationResult result = LocationResult.create(locations);
manager.reportLocationResult(location, result);
assertThat(callback.getResult()).isEqualTo(result);
}
@Test public void notifyLocationAvailability_shouldNotifyCallback() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationCallback callback = new TestLocationCallback();
Looper looper = Looper.myLooper();
manager.addLocationCallback(client, request, callback, looper);
LocationAvailability availability = new LocationAvailability(true);
manager.notifyLocationAvailability(availability);
assertThat(callback.getAvailability()).isEqualTo(availability);
}
@Test public void hasNoListeners_shouldReturnTrue() {
manager.addClient(client);
assertThat(manager.hasNoListeners()).isTrue();
}
@Test public void hasNoListeners_shouldReturnFalseWhenListenerAdded() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationListener listener = new TestLocationListener();
manager.addListener(client, request, listener);
assertThat(manager.hasNoListeners()).isFalse();
}
@Test public void hasNoListeners_shouldReturnFalseWhenPendingIntentAdded() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
PendingIntent pendingIntent = mock(PendingIntent.class);
manager.addPendingIntent(client, request, pendingIntent);
assertThat(manager.hasNoListeners()).isFalse();
}
@Test public void hasNoListeners_shouldReturnFalseWhenCallbackAdded() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationCallback callback = new TestLocationCallback();
Looper looper = mock(Looper.class);
manager.addLocationCallback(client, request, callback, looper);
assertThat(manager.hasNoListeners()).isFalse();
}
@Test public void removeClient_shouldRemoveListenersForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationListener listener = new TestLocationListener();
manager.addListener(client, request, listener);
manager.removeClient(client);
assertThat(manager.getLocationListeners().get(client)).isNull();
}
@Test public void removeClient_shouldRemovePendingIntentsForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
PendingIntent pendingIntent = mock(PendingIntent.class);
manager.addPendingIntent(client, request, pendingIntent);
manager.removeClient(client);
assertThat(manager.getPendingIntents().get(client)).isNull();
}
@Test public void removeClient_shouldRemoveCallbacksForClient() {
manager.addClient(client);
LocationRequest request = LocationRequest.create();
TestLocationCallback callback = new TestLocationCallback();
Looper looper = mock(Looper.class);
manager.addLocationCallback(client, request, callback, looper);
manager.removeClient(client);
assertThat(manager.getLocationCallbacks().get(client)).isNull();
}
@Test public void reportLocationChanged_shouldNotNotifyIfLessThanFastestInterval()
throws Exception {
final TestLocationListener listener = new TestLocationListener();
final LocationRequest request = LocationRequest.create()
.setFastestInterval(2000)
.setSmallestDisplacement(0);
manager.addClient(client);
manager.addListener(client, request, listener);
Location location1 = getTestLocation("test_provider", 0, 0, 0);
Location location2 = getTestLocation("test_provider", 1, 1, 1000);
manager.reportLocationChanged(location1);
manager.reportLocationChanged(location2);
assertThat(listener.getMostRecentLocation()).isEqualTo(location1);
}
@Test public void reportLocationChanged_shouldNotNotifyIfLessThanSmallestDisplacement()
throws Exception {
final TestLocationListener listener = new TestLocationListener();
final LocationRequest locationRequest = LocationRequest.create()
.setFastestInterval(0)
.setSmallestDisplacement(1000000);
manager.addClient(client);
manager.addListener(client, locationRequest, listener);
Location location1 = getTestLocation("test_provider", 0, 0, 0);
Location location2 = getTestLocation("test_provider", 1, 1, 1);
manager.reportLocationChanged(location1);
manager.reportLocationChanged(location2);
assertThat(listener.getMostRecentLocation()).isEqualTo(location1);
}
@Test public void sendPendingIntent_shouldNotifyPendingIntentWithLocationAvailability() {
Intent i = new Intent(application, FusedLocationProviderServiceDelegateTest.TestService.class);
PendingIntent pendingIntent = PendingIntent.getService(application, 0, i, 0);
Location location = new Location("test");
ArrayList<Location> locations = new ArrayList<>();
locations.add(location);
LocationResult result = LocationResult.create(locations);
manager.addClient(client);
manager.addPendingIntent(client, LocationRequest.create(), pendingIntent);
manager.sendPendingIntent(application, location, new LocationAvailability(true), result);
Intent next = ShadowApplication.getInstance().getNextStartedService();
assertThat(next).isNotNull();
assertThat(next.getParcelableExtra(EXTRA_LOCATION_AVAILABILITY)).isNotNull();
assertThat(next.getParcelableExtra(EXTRA_LOCATION_RESULT)).isNotNull();
}
@Test public void reportLocationResult_shouldNotifyLocationCallback() {
TestLocationCallback callback = new TestLocationCallback();
Location location = new Location("test");
ArrayList<Location> locations = new ArrayList<>();
locations.add(location);
LocationResult result = LocationResult.create(locations);
manager.addClient(client);
manager.addLocationCallback(client, LocationRequest.create(), callback, Looper.myLooper());
manager.reportLocationResult(location, result);
assertThat(callback.getResult().getLastLocation()).isEqualTo(location);
}
@Test public void sendPendingIntent_shouldNotNotifyRemovedPendingIntent() throws Exception {
Intent i1 = new Intent(application, FusedLocationProviderServiceDelegateTest.TestService.class);
Intent i2 = new Intent(application, FusedLocationProviderServiceDelegateTest.TestService.class);
PendingIntent pendingIntent = PendingIntent.getService(application, 0, i1, 0);
PendingIntent otherPendingIntent = PendingIntent.getService(application, 0, i2, 0);
Location location = new Location("test");
ArrayList<Location> locations = new ArrayList<>();
locations.add(location);
LocationResult result = LocationResult.create(locations);
manager.addClient(client);
manager.addPendingIntent(client, LocationRequest.create(), pendingIntent);
manager.addPendingIntent(client, LocationRequest.create(), otherPendingIntent);
manager.removePendingIntent(client, otherPendingIntent);
manager.sendPendingIntent(application, location, new LocationAvailability(true), result);
// Only one service should be started since the second pending intent request was removed.
assertThat(ShadowApplication.getInstance().getNextStartedService()).isNotNull();
assertThat(ShadowApplication.getInstance().getNextStartedService()).isNull();
}
@Test public void reportLocationChanged_shouldNotifyBothListeners() {
TestLocationListener listener1 = new TestLocationListener();
TestLocationListener listener2 = new TestLocationListener();
manager.addClient(client);
manager.addListener(client, LocationRequest.create(), listener1);
manager.addListener(client, LocationRequest.create(), listener2);
Location location = new Location("test");
manager.reportLocationChanged(location);
assertThat(listener1.getAllLocations()).contains(location);
assertThat(listener2.getAllLocations()).contains(location);
}
@Test public void sendPendingIntent_shouldNotifyBothPendingIntents() throws Exception {
Intent i1 = new Intent(application, FusedLocationProviderServiceDelegateTest.TestService.class);
Intent i2 = new Intent(application, FusedLocationProviderServiceDelegateTest.TestService.class);
PendingIntent pendingIntent = PendingIntent.getService(application, 0, i1, 0);
PendingIntent otherPendingIntent = PendingIntent.getService(application, 0, i2, 0);
Location location = new Location("test");
ArrayList<Location> locations = new ArrayList<>();
locations.add(location);
LocationResult result = LocationResult.create(locations);
manager.addClient(client);
manager.addPendingIntent(client, LocationRequest.create(), pendingIntent);
manager.addPendingIntent(client, LocationRequest.create(), otherPendingIntent);
manager.sendPendingIntent(application, location, new LocationAvailability(true), result);
// Two services should be started.
assertThat(ShadowApplication.getInstance().getNextStartedService()).isNotNull();
assertThat(ShadowApplication.getInstance().getNextStartedService()).isNotNull();
}
@Test public void reportLocationChanged_shouldNotifyBothCallbacks() {
TestLocationCallback callback1 = new TestLocationCallback();
TestLocationCallback callback2 = new TestLocationCallback();
manager.addClient(client);
manager.addLocationCallback(client, LocationRequest.create(), callback1, Looper.myLooper());
manager.addLocationCallback(client, LocationRequest.create(), callback2, Looper.myLooper());
Location location = new Location("test");
ArrayList<Location> locations = new ArrayList<>();
locations.add(location);
LocationResult locationResult = LocationResult.create(locations);
manager.reportLocationResult(location, locationResult);
assertThat(callback1.getResult()).isEqualTo(locationResult);
assertThat(callback2.getResult()).isEqualTo(locationResult);
}
@Test public void reportLocationChanged_shouldNotNotifyRemovedListener() {
LocationRequest request = LocationRequest.create();
TestLocationListener listener1 = new TestLocationListener();
TestLocationListener listener2 = new TestLocationListener();
manager.addClient(client);
manager.addListener(client, request, listener1);
manager.addListener(client, request, listener2);
manager.removeListener(client, listener2);
Location location = new Location(GPS_PROVIDER);
manager.reportLocationChanged(location);
assertThat(listener1.getAllLocations()).contains(location);
assertThat(listener2.getAllLocations()).doesNotContain(location);
}
private static Location getTestLocation(String provider, float lat, float lng, long time) {
Location location = new Location(provider);
location.setLatitude(lat);
location.setLongitude(lng);
location.setTime(time);
return location;
}
}
|
package com.wenguang.chat.event;
/**
* 作者:chenpan
* 时间:2016/11/30 11:12
* 邮箱:616707902@qq.com
* 描述:
*/
public interface CallBackBmob<T> {
void succssCallBack(T jsonArray);
void failed(String e);
}
|
package jforgame.server.game.activity;
import jforgame.server.game.database.user.PlayerEnt;
import jforgame.socket.message.Message;
public interface IActivityHandler {
void load();
Message openPanel(PlayerEnt player);
void receiveRewards(PlayerEnt player);
ActivityTypes getActivityType();
Activity getActivity();
boolean canOpen();
void checkPrepare();
void checkStart();
void checkEnd();
void activityPrepare();
void activityStart();
void activityEnd();
/**
* 把活动数据持久化到数据库
* @param fastSave 是否马上入库
*/
void saveToDb(boolean fastSave);
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.threads;
import org.jboss.as.controller.OperationContext;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Resolves the service name of the executor service a thread pool service should use if it cannot itself accept
* a task. Optionally provides an executor service for the thread pool to use in case the thread pool does not have a
* specifically configured handoff executor. The absence of a specifically configured thread pool would be typical.
*
* @author Brian Stansberry (c) 2011 Red Hat Inc.
*/
public interface HandoffExecutorResolver {
/**
* Resolves the service name of the handoff executor a thread pool service should use, optionally providing a default
* executor in case the thread pool does not have a specifically configured handoff executor.
*
*
* @param handoffExecutorName the simple name of the handoff executor. Typically a reference value from
* the thread pool resource's configuration. Can be {@code null} in which case a
* default handoff executor may be returned.
* @param threadPoolName the name of the thread pool
* @param threadPoolServiceName the full name of the {@link org.jboss.msc.service.Service} that provides the thread pool
* @param serviceTarget service target that is installing the thread pool service; can be used to install
* a {@link org.jboss.as.threads.ThreadFactoryService}
* @return the {@link ServiceName} of the executor service the thread pool should use. May be {@link null}
*/
ServiceName resolveHandoffExecutor(String handoffExecutorName, String threadPoolName, ServiceName threadPoolServiceName,
ServiceTarget serviceTarget);
/**
* Releases the handoff executor, doing any necessary cleanup, such as removing a default executor that
* was installed by {@link #resolveHandoffExecutor(String, String, org.jboss.msc.service.ServiceName, org.jboss.msc.service.ServiceTarget)}.
*
* @param handoffExecutorName the simple name of the thread factory. Typically a reference value from
* the thread pool resource's configuration. Can be {@code null} in which case a
* default thread factory should be released.
* @param threadPoolName the name of the thread pool
* @param threadPoolServiceName the full name of the {@link org.jboss.msc.service.Service} that provides the thread pool
* @param context the context of the current operation; can be used to perform any necessary
* {@link OperationContext#removeService(ServiceName) service removals}
*/
void releaseHandoffExecutor(String handoffExecutorName, String threadPoolName, ServiceName threadPoolServiceName,
OperationContext context);
/**
* Standard implementation of {@link ThreadFactoryResolver} -- a {@link SimpleResolver} with a base service name
* of {@link ThreadsServices#EXECUTOR}.
*/
HandoffExecutorResolver STANDARD_RESOLVER = new SimpleResolver(ThreadsServices.EXECUTOR);
/**
* Base class for {@code ThreadFactoryResolver} implementations that handles the case of a null
* {@code threadFactoryName} by installing a {@link ThreadFactoryService} whose service name is
* the service name of the thread pool with {@code thread-factory} appended.
*/
abstract class AbstractThreadFactoryResolver implements HandoffExecutorResolver {
@Override
public ServiceName resolveHandoffExecutor(String handoffExecutorName, String threadPoolName, ServiceName threadPoolServiceName, ServiceTarget serviceTarget) {
ServiceName threadFactoryServiceName = null;
if (handoffExecutorName != null) {
threadFactoryServiceName = resolveNamedHandoffExecutor(handoffExecutorName, threadPoolName, threadPoolServiceName);
} else {
// Create a default
threadFactoryServiceName = resolveDefaultHandoffExecutor(threadPoolName, threadPoolServiceName, serviceTarget);
}
return threadFactoryServiceName;
}
@Override
public void releaseHandoffExecutor(String handoffExecutorName, String threadPoolName, ServiceName threadPoolServiceName,
OperationContext context) {
if (handoffExecutorName != null) {
releaseNamedHandoffExecutor(handoffExecutorName, threadPoolName, threadPoolServiceName, context);
} else {
releaseDefaultHandoffExecutor(threadPoolServiceName, context);
}
}
/**
* Create a service name to use for the thread factory in the case where a simple name for the factory was provided.
*
* @param handoffExecutorName the simple name of the thread factory. Will not be {@code null}
* @param threadPoolName the simple name of the related thread pool
* @param threadPoolServiceName the full service name of the thread pool
*
* @return the {@link ServiceName} of the {@link ThreadFactoryService} the thread pool should use. Cannot be
* {@code null}
*/
protected abstract ServiceName resolveNamedHandoffExecutor(String handoffExecutorName, String threadPoolName, ServiceName threadPoolServiceName);
/**
* Handles the work of {@link #releaseHandoffExecutor(String, String, ServiceName, OperationContext)} for the case
* where {@code threadFactoryName} is not {@code null}. This default implementation does nothing, assuming
* the thread factory is independently managed from the pool.
*
* @param handoffExecutorName the simple name of the thread factory. Will not be {@code null}
* @param threadPoolName the simple name of the related thread pool
* @param threadPoolServiceName the full service name of the thread pool
* @param context the context of the current operation; can be used to perform any necessary
* {@link OperationContext#removeService(ServiceName) service removals}
*/
protected void releaseNamedHandoffExecutor(String handoffExecutorName, String threadPoolName, ServiceName threadPoolServiceName,
OperationContext context) {
// no-op
}
/**
* Optionally provides the service name of a default handoff executor. This implementation simply returns
* {@code null}, meaning there is no default.
*
* @param threadPoolName the name of the thread pool
* @param threadPoolServiceName the full name of the {@link org.jboss.msc.service.Service} that provides the thread pool
* @param serviceTarget service target that is installing the thread pool service; can be used to install
* a {@link org.jboss.as.threads.ThreadFactoryService}
* @return the {@link ServiceName} of the {@link ThreadFactoryService} the thread pool should use. May be {@code null}
*/
protected ServiceName resolveDefaultHandoffExecutor(String threadPoolName, ServiceName threadPoolServiceName,
ServiceTarget serviceTarget) {
return null;
}
/**
* Removes any default thread factory installed in {@link #resolveDefaultHandoffExecutor(String, org.jboss.msc.service.ServiceName, org.jboss.msc.service.ServiceTarget)}.
* This default implementation does nothing, but any subclass that installs a default service should override this
* method to remove it.
*
* @param threadPoolServiceName the full name of the {@link org.jboss.msc.service.Service} that provides the thread pool
* @param context the context of the current operation; can be used to perform any necessary
* {@link OperationContext#removeService(ServiceName) service removals}
*/
protected void releaseDefaultHandoffExecutor(ServiceName threadPoolServiceName, OperationContext context) {
// nothing to do since we didn't create anything
}
}
/**
* Extends {@link AbstractThreadFactoryResolver} to deal with named thread factories by appending their
* simple name to a provided base name.
*/
class SimpleResolver extends AbstractThreadFactoryResolver {
final ServiceName handoffExecutorServiceNameBase;
public SimpleResolver(ServiceName handoffExecutorServiceNameBase) {
this.handoffExecutorServiceNameBase = handoffExecutorServiceNameBase;
}
@Override
public ServiceName resolveNamedHandoffExecutor(String handoffExecutorName, String threadPoolName, ServiceName threadPoolServiceName) {
return handoffExecutorServiceNameBase.append(handoffExecutorName);
}
}
}
|
/**
* Copyright 2016-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.antheminc.oss.nimbus.domain.rules.drools;
import org.drools.common.InternalFactHandle;
import org.drools.spi.KnowledgeHelper;
import com.antheminc.oss.nimbus.support.JustLogit;
/**
* DroolsLoggerUtil will provide a logging capability within drl files <br>
* Usage in drl files : <br>
* <pre>
* import function com.antheminc.oss.nimbus.domain.rules.drools.DroolsLoggerUtil.*;
* rule "Rule"
* when
* some condition
* then
* // Log a message
* info(drools, "log message");
*
* // Log a message with an exception
* info(drools, "An exception occurred", new RuntimeException("Some exception message"));
* end
* </pre>
*
* The KnowledgeHelper interface is made available to the RHS code block of drl files as a predefined variable called "drools".
* @see <a href="https://docs.jboss.org/drools/release/5.6.0.Final/drools-expert-docs/html/ch04.html#d0e7386">Drools Docs</a>
*
* @author Swetha Vemuri
*
*/
public class DroolsLoggerUtil {
public DroolsLoggerUtil() {};
protected static JustLogit getLogger(final KnowledgeHelper drools) {
InternalFactHandle factHandle = (InternalFactHandle) drools.getActivation().getPropagationContext().getFactHandleOrigin();
final String ruleFileName = factHandle.getObject().getClass().getName();
final String ruleResource = ruleFileName+ "." +drools.getRule().getName();
final JustLogit logit = new JustLogit(ruleResource);
return logit;
}
public static void info(final KnowledgeHelper drools,final String msg) {
final JustLogit logit = getLogger(drools);
logit.info(() -> msg);
}
public static void info(final KnowledgeHelper drools,final String msg, Throwable t) {
final JustLogit logit = getLogger(drools);
logit.info(() -> msg, t);
}
public static void debug(final KnowledgeHelper drools,final String msg) {
final JustLogit logit = getLogger(drools);
logit.debug(() -> msg);
}
public static void debug(final KnowledgeHelper drools,final String msg, Throwable t) {
final JustLogit logit = getLogger(drools);
logit.debug(() -> msg, t);
}
public static void trace(final KnowledgeHelper drools,final String msg) {
final JustLogit logit = getLogger(drools);
logit.trace(() -> msg);
}
public static void trace(final KnowledgeHelper drools,final String msg, Throwable t) {
final JustLogit logit = getLogger(drools);
logit.trace(() -> msg, t);
}
public static void error(final KnowledgeHelper drools,final String msg) {
final JustLogit logit = getLogger(drools);
logit.error(() -> msg);
}
public static void error(final KnowledgeHelper drools,final String msg, Throwable t) {
final JustLogit logit = getLogger(drools);
logit.error(() -> msg, t);
}
}
|
/*
* Copyright (C) 2008 ZXing 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 com.example.foodordering.zxing.camera;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import com.google.zxing.PlanarYUVLuminanceSource;
import java.io.IOException;
/**
* This object wraps the Camera service object and expects to be the only one
* talking to it. The implementation encapsulates the steps needed to take
* preview-sized images, which are used for both preview and decoding.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class CameraManager {
private static final String TAG = CameraManager.class.getSimpleName();
private static final int MIN_FRAME_WIDTH = 240;
private static final int MIN_FRAME_HEIGHT = 240;
private static final int MAX_FRAME_WIDTH = 1200; // = 5/8 * 1920
private static final int MAX_FRAME_HEIGHT = 675; // = 5/8 * 1080
private final Context context;
private final CameraConfigurationManager configManager;
private Camera camera;
private AutoFocusManager autoFocusManager;
private Rect framingRect;
private Rect framingRectInPreview;
private boolean initialized;
private boolean previewing;
private int requestedCameraId = -1;
private int requestedFramingRectWidth;
private int requestedFramingRectHeight;
/**
* Preview frames are delivered here, which we pass on to the registered
* handler. Make sure to clear the handler so it will only receive one
* message.
*/
private final PreviewCallback previewCallback;
public CameraManager(Context context) {
this.context = context;
this.configManager = new CameraConfigurationManager(context);
previewCallback = new PreviewCallback(configManager);
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @param holder
* The surface object which the camera will draw preview frames
* into.
* @throws IOException
* Indicates the camera driver failed to open.
*/
public synchronized void openDriver(SurfaceHolder holder)
throws IOException {
Camera theCamera = camera;
if (theCamera == null) {
if (requestedCameraId >= 0) {
theCamera = OpenCameraInterface.open(requestedCameraId);
} else {
theCamera = OpenCameraInterface.open();
}
if (theCamera == null) {
throw new IOException();
}
camera = theCamera;
}
theCamera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(theCamera);
if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) {
setManualFramingRect(requestedFramingRectWidth,
requestedFramingRectHeight);
requestedFramingRectWidth = 0;
requestedFramingRectHeight = 0;
}
}
Camera.Parameters parameters = theCamera.getParameters();
String parametersFlattened = parameters == null ? null : parameters
.flatten(); // Save these, temporarily
try {
configManager.setDesiredCameraParameters(theCamera, false);
} catch (RuntimeException re) {
// Driver failed
Log.w(TAG,
"Camera rejected parameters. Setting only minimal safe-mode parameters");
Log.i(TAG, "Resetting to saved camera params: "
+ parametersFlattened);
// Reset:
if (parametersFlattened != null) {
parameters = theCamera.getParameters();
parameters.unflatten(parametersFlattened);
try {
theCamera.setParameters(parameters);
configManager.setDesiredCameraParameters(theCamera, true);
} catch (RuntimeException re2) {
// Well, darn. Give up
Log.w(TAG,
"Camera rejected even safe-mode parameters! No configuration");
}
}
}
}
public synchronized boolean isOpen() {
return camera != null;
}
/**
* Closes the camera driver if still in use.
*/
public synchronized void closeDriver() {
if (camera != null) {
camera.release();
camera = null;
// Make sure to clear these each time we close the camera, so that
// any scanning rect
// requested by intent is forgotten.
framingRect = null;
framingRectInPreview = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public synchronized void startPreview() {
Camera theCamera = camera;
if (theCamera != null && !previewing) {
theCamera.startPreview();
previewing = true;
autoFocusManager = new AutoFocusManager(context, camera);
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public synchronized void stopPreview() {
if (autoFocusManager != null) {
autoFocusManager.stop();
autoFocusManager = null;
}
if (camera != null && previewing) {
camera.stopPreview();
previewCallback.setHandler(null, 0);
previewing = false;
}
}
/**
* A single preview frame will be returned to the handler supplied. The data
* will arrive as byte[] in the message.obj field, with width and height
* encoded as message.arg1 and message.arg2, respectively.
*
* @param handler
* The handler to send the message to.
* @param message
* The what field of the message to be sent.
*/
public synchronized void requestPreviewFrame(Handler handler, int message) {
Camera theCamera = camera;
if (theCamera != null && previewing) {
previewCallback.setHandler(handler, message);
theCamera.setOneShotPreviewCallback(previewCallback);
}
}
/**
* Calculates the framing rect which the UI should draw to show the user
* where to place the barcode. This target helps with alignment as well as
* forces the user to hold the device far enough away to ensure the image
* will be in focus. 计算这个条形码的扫描框;便于声明的同时,也强制用户通过改变距离来扫描到整个条形码
*
* @return The rectangle to draw on screen in window coordinates.
*/
public synchronized Rect getFramingRect() {
if (framingRect == null) {
if (camera == null) {
return null;
}
Point screenResolution = configManager.getScreenResolution();
if (screenResolution == null) {
// Called early, before init even finished
return null;
}
// int width = findDesiredDimensionInRange(screenResolution.x,
// MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);
// int height = findDesiredDimensionInRange(screenResolution.y,
// MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT);
int width = findDesiredDimensionInRange(screenResolution.x,
MIN_FRAME_WIDTH, MAX_FRAME_WIDTH)*4/5;
int height = findDesiredDimensionInRange(screenResolution.y,
MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT)*4/5;
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
topOffset + height);
Log.d(TAG, "Calculated framing rect: " + framingRect);
}
return framingRect;
}
private static int findDesiredDimensionInRange(int resolution, int hardMin,
int hardMax) {
int dim = 5 * resolution / 8; // Target 5/8 of each dimension
if (dim < hardMin) {
return hardMin;
}
if (dim > hardMax) {
return hardMax;
}
return dim;
}
/**
* Like {@link #getFramingRect} but coordinates are in terms of the preview
* frame, not UI / screen.
*
* @return {@link Rect} expressing barcode scan area in terms of the preview
* size
*/
public synchronized Rect getFramingRectInPreview() {
if (framingRectInPreview == null) {
Rect framingRect = getFramingRect();
if (framingRect == null) {
return null;
}
Rect rect = new Rect(framingRect);
Point cameraResolution = configManager.getCameraResolution();
Point screenResolution = configManager.getScreenResolution();
if (cameraResolution == null || screenResolution == null) {
// Called early, before init even finished
return null;
}
/******************** 竖屏更改1(cameraResolution.x/y互换) ************************/
rect.left = rect.left * cameraResolution.y / screenResolution.x;
rect.right = rect.right * cameraResolution.y / screenResolution.x;
rect.top = rect.top * cameraResolution.x / screenResolution.y;
rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;
framingRectInPreview = rect;
}
return framingRectInPreview;
}
/**
* Allows third party apps to specify the camera ID, rather than determine
* it automatically based on available cameras and their orientation.
*
* @param cameraId
* camera ID of the camera to use. A negative value means
* "no preference".
*/
public synchronized void setManualCameraId(int cameraId) {
requestedCameraId = cameraId;
}
/**
* Allows third party apps to specify the scanning rectangle dimensions,
* rather than determine them automatically based on screen resolution.
*
* @param width
* The width in pixels to scan.
* @param height
* The height in pixels to scan.
*/
public synchronized void setManualFramingRect(int width, int height) {
if (initialized) {
Point screenResolution = configManager.getScreenResolution();
if (width > screenResolution.x) {
width = screenResolution.x;
}
if (height > screenResolution.y) {
height = screenResolution.y;
}
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
topOffset + height);
Log.d(TAG, "Calculated manual framing rect: " + framingRect);
framingRectInPreview = null;
} else {
requestedFramingRectWidth = width;
requestedFramingRectHeight = height;
}
}
/**
* A factory method to build the appropriate LuminanceSource object based on
* the format of the preview buffers, as described by Camera.Parameters.
*
* @param data
* A preview frame.
* @param width
* The width of the image.
* @param height
* The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data,
int width, int height) {
Rect rect = getFramingRectInPreview();
if (rect == null) {
return null;
}
// Go ahead and assume it's YUV rather than die.
return new PlanarYUVLuminanceSource(data, width, height, rect.left,
rect.top, rect.width(), rect.height(), false);
}
}
|
package com.softplan.apigerenciarprocessos.modules.processos.infra.http.controllers;
import java.util.List;
import com.softplan.apigerenciarprocessos.modules.processos.entities.Processo;
import com.softplan.apigerenciarprocessos.modules.processos.services.CriarProcessoService;
import com.softplan.apigerenciarprocessos.modules.processos.services.ListarProcessosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/processos")
public class ProcessosController {
@Autowired
private ListarProcessosService listarProcessosService;
@Autowired
private CriarProcessoService criarProcessoService;
public ProcessosController(ListarProcessosService listarProcessosService, CriarProcessoService criarProcessoService) {
this.listarProcessosService = listarProcessosService;
this.criarProcessoService = criarProcessoService;
}
@GetMapping()
public List<Processo> getAll() {
return listarProcessosService.listar();
}
@PostMapping()
public Processo post(@RequestBody Processo processo) {
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@" + processo.getDescricao());
return criarProcessoService.criarProcesso(processo);
}
}
|
/*
* 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.geode.redis.internal.executor.sortedset;
import org.junit.ClassRule;
import org.apache.geode.redis.GeodeRedisServerRule;
public class ZUnionStoreIntegrationTest extends AbstractZUnionStoreIntegrationTest {
@ClassRule
public static GeodeRedisServerRule server = new GeodeRedisServerRule();
@Override
public int getPort() {
return server.getPort();
}
}
|
/*
* Copyright 1999-2011 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.registry.support;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.utils.ConcurrentHashSet;
import com.alibaba.dubbo.common.utils.NamedThreadFactory;
import com.alibaba.dubbo.registry.NotifyListener;
/**
* FailbackRegistry. (SPI, Prototype, ThreadSafe)
*
* @author william.liangf
*/
public abstract class FailbackRegistry extends AbstractRegistry {
// 定时任务执行器
private final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryFailedRetryTimer", true));
// 失败重试定时器,定时检查是否有请求失败,如有,无限次重试
private final ScheduledFuture<?> retryFuture;
private final Set<URL> failedRegistered = new ConcurrentHashSet<URL>();
private final Set<URL> failedUnregistered = new ConcurrentHashSet<URL>();
private final ConcurrentMap<URL, Set<NotifyListener>> failedSubscribed = new ConcurrentHashMap<URL, Set<NotifyListener>>();
private final ConcurrentMap<URL, Set<NotifyListener>> failedUnsubscribed = new ConcurrentHashMap<URL, Set<NotifyListener>>();
private final ConcurrentMap<URL, Map<NotifyListener, List<URL>>> failedNotified = new ConcurrentHashMap<URL, Map<NotifyListener, List<URL>>>();
public FailbackRegistry(URL url) {
super(url);
int retryPeriod = url.getParameter(Constants.REGISTRY_RETRY_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RETRY_PERIOD);
this.retryFuture = retryExecutor.scheduleWithFixedDelay(new Runnable() {
public void run() {
// 检测并连接注册中心
try {
retry();
} catch (Throwable t) { // 防御性容错
logger.error("Unexpected error occur at failed retry, cause: " + t.getMessage(), t);
}
}
}, retryPeriod, retryPeriod, TimeUnit.MILLISECONDS);
}
public Future<?> getRetryFuture() {
return retryFuture;
}
public Set<URL> getFailedRegistered() {
return failedRegistered;
}
public Set<URL> getFailedUnregistered() {
return failedUnregistered;
}
public Map<URL, Set<NotifyListener>> getFailedSubscribed() {
return failedSubscribed;
}
public Map<URL, Set<NotifyListener>> getFailedUnsubscribed() {
return failedUnsubscribed;
}
public Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified() {
return failedNotified;
}
private void addFailedSubscribed(URL url, NotifyListener listener) {
Set<NotifyListener> listeners = failedSubscribed.get(url);
if (listeners == null) {
failedSubscribed.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
listeners = failedSubscribed.get(url);
}
listeners.add(listener);
}
private void removeFailedSubscribed(URL url, NotifyListener listener) {
Set<NotifyListener> listeners = failedSubscribed.get(url);
if (listeners != null) {
listeners.remove(listener);
}
listeners = failedUnsubscribed.get(url);
if (listeners != null) {
listeners.remove(listener);
}
Map<NotifyListener, List<URL>> notified = failedNotified.get(url);
if (notified != null) {
notified.remove(listener);
}
}
@Override
public void register(URL url) {
super.register(url);
failedRegistered.remove(url);
failedUnregistered.remove(url);
try {
// 向服务器端发送注册请求
doRegister(url);
} catch (Exception e) {
Throwable t = e;
// 如果开启了启动时检测,则直接抛出异常
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true)
&& ! Constants.CONSUMER_PROTOCOL.equals(url.getProtocol());
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if(skipFailback) {
t = t.getCause();
}
throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t);
} else {
logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t);
}
// 将失败的注册请求记录到失败列表,定时重试
failedRegistered.add(url);
}
}
@Override
public void unregister(URL url) {
super.unregister(url);
failedRegistered.remove(url);
failedUnregistered.remove(url);
try {
// 向服务器端发送取消注册请求
doUnregister(url);
} catch (Exception e) {
Throwable t = e;
// 如果开启了启动时检测,则直接抛出异常
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true)
&& ! Constants.CONSUMER_PROTOCOL.equals(url.getProtocol());
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if(skipFailback) {
t = t.getCause();
}
throw new IllegalStateException("Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t);
} else {
logger.error("Failed to uregister " + url + ", waiting for retry, cause: " + t.getMessage(), t);
}
// 将失败的取消注册请求记录到失败列表,定时重试
failedUnregistered.add(url);
}
}
@Override
public void subscribe(URL url, NotifyListener listener) {
super.subscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// 向服务器端发送订阅请求
doSubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
List<URL> urls = getCacheUrls(url);
if (urls != null && urls.size() > 0) {
notify(url, listener, urls);
logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t);
} else {
// 如果开启了启动时检测,则直接抛出异常
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if(skipFailback) {
t = t.getCause();
}
throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t);
} else {
logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
}
}
// 将失败的订阅请求记录到失败列表,定时重试
addFailedSubscribed(url, listener);
}
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
super.unsubscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// 向服务器端发送取消订阅请求
doUnsubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
// 如果开启了启动时检测,则直接抛出异常
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true);
boolean skipFailback = t instanceof SkipFailbackWrapperException;
if (check || skipFailback) {
if(skipFailback) {
t = t.getCause();
}
throw new IllegalStateException("Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t);
} else {
logger.error("Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
}
// 将失败的取消订阅请求记录到失败列表,定时重试
Set<NotifyListener> listeners = failedUnsubscribed.get(url);
if (listeners == null) {
failedUnsubscribed.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
listeners = failedUnsubscribed.get(url);
}
listeners.add(listener);
}
}
@Override
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
try {
doNotify(url, listener, urls);
} catch (Exception t) {
// 将失败的通知请求记录到失败列表,定时重试
Map<NotifyListener, List<URL>> listeners = failedNotified.get(url);
if (listeners == null) {
failedNotified.putIfAbsent(url, new ConcurrentHashMap<NotifyListener, List<URL>>());
listeners = failedNotified.get(url);
}
listeners.put(listener, urls);
logger.error("Failed to notify for subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
}
}
protected void doNotify(URL url, NotifyListener listener, List<URL> urls) {
super.notify(url, listener, urls);
}
@Override
protected void recover() throws Exception {
// register
Set<URL> recoverRegistered = new HashSet<URL>(getRegistered());
if (! recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}
for (URL url : recoverRegistered) {
failedRegistered.add(url);
}
}
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<URL, Set<NotifyListener>>(getSubscribed());
if (! recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover subscribe url " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
addFailedSubscribed(url, listener);
}
}
}
}
// 重试失败的动作
protected void retry() {
if (! failedRegistered.isEmpty()) {
Set<URL> failed = new HashSet<URL>(failedRegistered);
if (failed.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Retry register " + failed);
}
try {
for (URL url : failed) {
try {
doRegister(url);
failedRegistered.remove(url);
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry register " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry register " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
if(! failedUnregistered.isEmpty()) {
Set<URL> failed = new HashSet<URL>(failedUnregistered);
if (failed.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Retry unregister " + failed);
}
try {
for (URL url : failed) {
try {
doUnregister(url);
failedUnregistered.remove(url);
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry unregister " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry unregister " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
if (! failedSubscribed.isEmpty()) {
Map<URL, Set<NotifyListener>> failed = new HashMap<URL, Set<NotifyListener>>(failedSubscribed);
for (Map.Entry<URL, Set<NotifyListener>> entry : new HashMap<URL, Set<NotifyListener>>(failed).entrySet()) {
if (entry.getValue() == null || entry.getValue().size() == 0) {
failed.remove(entry.getKey());
}
}
if (failed.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Retry subscribe " + failed);
}
try {
for (Map.Entry<URL, Set<NotifyListener>> entry : failed.entrySet()) {
URL url = entry.getKey();
Set<NotifyListener> listeners = entry.getValue();
for (NotifyListener listener : listeners) {
try {
doSubscribe(url, listener);
listeners.remove(listener);
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry subscribe " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry subscribe " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
if (! failedUnsubscribed.isEmpty()) {
Map<URL, Set<NotifyListener>> failed = new HashMap<URL, Set<NotifyListener>>(failedUnsubscribed);
for (Map.Entry<URL, Set<NotifyListener>> entry : new HashMap<URL, Set<NotifyListener>>(failed).entrySet()) {
if (entry.getValue() == null || entry.getValue().size() == 0) {
failed.remove(entry.getKey());
}
}
if (failed.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Retry unsubscribe " + failed);
}
try {
for (Map.Entry<URL, Set<NotifyListener>> entry : failed.entrySet()) {
URL url = entry.getKey();
Set<NotifyListener> listeners = entry.getValue();
for (NotifyListener listener : listeners) {
try {
doUnsubscribe(url, listener);
listeners.remove(listener);
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry unsubscribe " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry unsubscribe " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
if (! failedNotified.isEmpty()) {
Map<URL, Map<NotifyListener, List<URL>>> failed = new HashMap<URL, Map<NotifyListener, List<URL>>>(failedNotified);
for (Map.Entry<URL, Map<NotifyListener, List<URL>>> entry : new HashMap<URL, Map<NotifyListener, List<URL>>>(failed).entrySet()) {
if (entry.getValue() == null || entry.getValue().size() == 0) {
failed.remove(entry.getKey());
}
}
if (failed.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Retry notify " + failed);
}
try {
for (Map<NotifyListener, List<URL>> values : failed.values()) {
for (Map.Entry<NotifyListener, List<URL>> entry : values.entrySet()) {
try {
NotifyListener listener = entry.getKey();
List<URL> urls = entry.getValue();
listener.notify(urls);
values.remove(listener);
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry notify " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
} catch (Throwable t) { // 忽略所有异常,等待下次重试
logger.warn("Failed to retry notify " + failed + ", waiting for again, cause: " + t.getMessage(), t);
}
}
}
}
@Override
public void destroy() {
super.destroy();
try {
retryFuture.cancel(true);
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
}
}
// ==== 模板方法 ====
protected abstract void doRegister(URL url);
protected abstract void doUnregister(URL url);
protected abstract void doSubscribe(URL url, NotifyListener listener);
protected abstract void doUnsubscribe(URL url, NotifyListener listener);
}
|
/**
* This package contains a Java implementation of the
* esregex AST format.
*
* <p>
* The root of the AST class hierarchy is {@link com.semmle.js.ast.regexp.RegExpTerm}, which in
* turn extends {@link com.semmle.js.ast.SourceElement}.
* </p>
*
* <p>
* Nodes accept visitors implementing interface {@link com.semmle.js.ast.regexp.Visitor}.
* </p>
*/
package com.semmle.js.ast.regexp;
|
package ru.sbtqa.tag.api.entries.parameters;
import ru.sbtqa.tag.api.EndpointEntry;
import ru.sbtqa.tag.api.Rest;
import ru.sbtqa.tag.api.annotation.Cookie;
import ru.sbtqa.tag.api.annotation.Endpoint;
import ru.sbtqa.tag.api.annotation.Validation;
import ru.sbtqa.tag.api.utils.Default;
import static org.hamcrest.Matchers.equalTo;
@Endpoint(method = Rest.GET, path = "client/cookie", title = "cookie")
public class CookieEntry extends EndpointEntry {
@Cookie(name = Default.COOKIE_NAME)
private String cookie = Default.COOKIE_VALUE;
@Validation(title = "result")
public void validate() {
getResponse().body("result", equalTo(cookie));
}
}
|
package org.tron.trident.abi.datatypes.generated;
import java.math.BigInteger;
import org.tron.trident.abi.datatypes.Uint;
/**
* Auto generated code.
* <p><strong>Do not modifiy!</strong>
* <p>Please use org.tron.trident.codegen.AbiTypesGenerator in the
* <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
*/
public class Uint56 extends Uint {
public static final Uint56 DEFAULT = new Uint56(BigInteger.ZERO);
public Uint56(BigInteger value) {
super(56, value);
}
public Uint56(long value) {
this(BigInteger.valueOf(value));
}
}
|
package com.example.configservice;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConfigServiceApplicationTests {
@Test
public void contextLoads() {
}
}
|
import java.util.*;
class Sangram{
static boolean[] prime=new boolean[10001];
static int ans[]=new int[10001];//count array
public static void make(){
/*prime calculation*/
int len=prime.length;
for(int i=0;i<len;i++){
prime[i]=true;
}
for(int i=2;i<prime.length;i++){
if(prime[i]){
for(int j=i*i;j<prime.length;j=j+i){
prime[j]=false;
}
}
}
/*prime calculation*/
for(int p=2;p<len;p++){
for(int q=2;q<len;q++){
//if p and q both are prime and the condition is true add count
if (prime[p] && prime[q] && (p+2*q)<len)
ans[p+2*q]++;
}
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
make();
int t=sc.nextInt();
while(t-->0){
System.out.println(ans[sc.nextInt()]);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.