text
stringlengths 7
1.01M
|
|---|
/**
* Copyright © 2016-2021 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.common.data.oauth2;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.SearchTextBasedWithAdditionalInfo;
import org.thingsboard.server.common.data.id.OAuth2ClientRegistrationInfoId;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
@ToString(exclude = {"clientSecret"})
@NoArgsConstructor
public class OAuth2ClientRegistrationInfo extends SearchTextBasedWithAdditionalInfo<OAuth2ClientRegistrationInfoId> implements HasName {
private boolean enabled;
private OAuth2MapperConfig mapperConfig;
private String clientId;
private String clientSecret;
private String authorizationUri;
private String accessTokenUri;
private List<String> scope;
private String userInfoUri;
private String userNameAttributeName;
private String jwkSetUri;
private String clientAuthenticationMethod;
private String loginButtonLabel;
private String loginButtonIcon;
public OAuth2ClientRegistrationInfo(OAuth2ClientRegistrationInfo clientRegistration) {
super(clientRegistration);
this.enabled = clientRegistration.enabled;
this.mapperConfig = clientRegistration.mapperConfig;
this.clientId = clientRegistration.clientId;
this.clientSecret = clientRegistration.clientSecret;
this.authorizationUri = clientRegistration.authorizationUri;
this.accessTokenUri = clientRegistration.accessTokenUri;
this.scope = clientRegistration.scope;
this.userInfoUri = clientRegistration.userInfoUri;
this.userNameAttributeName = clientRegistration.userNameAttributeName;
this.jwkSetUri = clientRegistration.jwkSetUri;
this.clientAuthenticationMethod = clientRegistration.clientAuthenticationMethod;
this.loginButtonLabel = clientRegistration.loginButtonLabel;
this.loginButtonIcon = clientRegistration.loginButtonIcon;
}
@Override
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getName() {
return loginButtonLabel;
}
@Override
public String getSearchText() {
return getName();
}
}
|
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.stack.Protocol;
import org.jgroups.util.MyReceiver;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
/**
* Tests UNICAST2. Created to test the last-message-dropped problem, see https://issues.jboss.org/browse/JGRP-1548.
* @author Bela Ban
* @since 3.3
*/
@Test(groups=Global.FUNCTIONAL,singleThreaded=true)
public class UNICAST_DropFirstAndLastTest {
protected JChannel a, b;
protected MyReceiver<Integer> rb;
protected DISCARD discard; // on A
protected void setup(Class<? extends Protocol> unicast_class) throws Exception {
a=createChannel(unicast_class, "A");
discard=(DISCARD)a.getProtocolStack().findProtocol(DISCARD.class);
assert discard != null;
a.connect("UNICAST_DropFirstAndLastTest");
rb=new MyReceiver<Integer>().name("B").verbose(true);
b=createChannel(unicast_class, "B").receiver(rb);
b.connect("UNICAST_DropFirstAndLastTest");
Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b);
}
@AfterMethod protected void destroy() {setLevel("warn", a, b); Util.close(b, a); rb.reset();}
@DataProvider
static Object[][] configProvider() {
return new Object[][]{
{UNICAST.class},
{UNICAST2.class},
{UNICAST3.class}
};
}
/**
* A sends unicast messages 1-5 to B, but we drop message 5. The code in
* https://issues.jboss.org/browse/JGRP-1548 now needs to make sure message 5 is retransmitted to B
* within a short time period, and we don't have to rely on the stable task to kick in.
*/
@Test(dataProvider="configProvider")
public void testLastMessageDropped(Class<? extends Protocol> unicast_class) throws Exception {
setup(unicast_class);
setLevel("trace", a, b);
Address dest=b.getAddress();
for(int i=1; i <= 5; i++) {
Message msg=new Message(dest, i);
if(i == 5)
discard.setDropDownUnicasts(1); // drops the next unicast
a.send(msg);
}
List<Integer> msgs=rb.list();
Util.waitUntilListHasSize(msgs, 5, 5000, 500);
System.out.println("list=" + msgs);
}
/**
* A sends unicast message 1 to B, but we drop message 1. The code in
* https://issues.jboss.org/browse/JGRP-1563 now needs to make sure message 1 is retransmitted to B
* within a short time period, and we don't have to rely on the stable task to kick in.
*/
@Test(dataProvider="configProvider")
public void testFirstMessageDropped(Class<? extends Protocol> unicast_class) throws Exception {
setup(unicast_class);
System.out.println("**** closing all connections ****");
// close all connections, so we can start from scratch and send message A1 to B
for(JChannel ch: Arrays.asList(a,b)) {
Protocol unicast=ch.getProtocolStack().findProtocol(Util.getUnicastProtocols());
removeAllConnections(unicast);
}
setLevel("trace", a, b);
System.out.println("--> A sending first message to B (dropped before it reaches B)");
discard.setDropDownUnicasts(1); // drops the next unicast
a.send(new Message(b.getAddress(), 1));
List<Integer> msgs=rb.list();
try {
Util.waitUntilListHasSize(msgs, 1, 500000, 500);
}
catch(AssertionError err) {
printConnectionTables(a, b);
throw err;
}
System.out.println("list=" + msgs);
printConnectionTables(a, b);
// assert ((UNICAST2)a.getProtocolStack().findProtocol(UNICAST2.class)).connectionEstablished(b.getAddress());
}
protected JChannel createChannel(Class<? extends Protocol> unicast_class, String name) throws Exception {
Protocol unicast=unicast_class.newInstance();
if(unicast instanceof UNICAST2)
unicast.setValue("stable_interval", 1000);
return new JChannel(new SHARED_LOOPBACK().setValue("enable_batching", true),
new PING().setValue("timeout", 1000),
new NAKACK2().setValue("use_mcast_xmit", false),
new DISCARD(),
unicast.setValue("xmit_interval", 500),
new GMS().setValue("print_local_addr", false))
.name(name);
}
protected void printConnectionTables(JChannel ... channels) {
System.out.println("**** CONNECTIONS:");
for(JChannel ch: channels) {
Protocol ucast=ch.getProtocolStack().findProtocol(Util.getUnicastProtocols());
System.out.println(ch.getName() + ":\n" + printConnections(ucast) + "\n");
}
}
protected void setLevel(String level, JChannel ... channels) {
for(JChannel ch: channels)
ch.getProtocolStack().findProtocol(Util.getUnicastProtocols()).level(level);
}
protected String printConnections(Protocol prot) {
if(prot instanceof UNICAST) {
UNICAST unicast=(UNICAST)prot;
return unicast.printConnections();
}
else if(prot instanceof UNICAST2) {
UNICAST2 unicast=(UNICAST2)prot;
return unicast.printConnections();
}
else if(prot instanceof UNICAST3) {
UNICAST3 unicast=(UNICAST3)prot;
return unicast.printConnections();
}
else
throw new IllegalArgumentException("prot (" + prot + ") needs to be UNICAST, UNICAST2 or UNICAST3");
}
protected void removeAllConnections(Protocol prot) {
if(prot instanceof UNICAST) {
UNICAST unicast=(UNICAST)prot;
unicast.removeAllConnections();
}
else if(prot instanceof UNICAST2) {
UNICAST2 unicast=(UNICAST2)prot;
unicast.removeAllConnections();
}
else if(prot instanceof UNICAST3) {
UNICAST3 unicast=(UNICAST3)prot;
unicast.removeAllConnections();
}
else
throw new IllegalArgumentException("prot (" + prot + ") needs to be UNICAST, UNICAST2 or UNICAST3");
}
}
|
/*
* 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.flink.storm.exclamation.util;
/**
* Expected output of Exclamation programs.
*/
public class ExclamationData {
public static final String TEXT_WITH_EXCLAMATIONS =
"Goethe - Faust: Der Tragoedie erster Teil!!!!!!\n"
+ "Prolog im Himmel.!!!!!!\n"
+ "Der Herr. Die himmlischen Heerscharen. Nachher Mephistopheles. Die drei!!!!!!\n"
+ "Erzengel treten vor.!!!!!!\n"
+ "RAPHAEL: Die Sonne toent, nach alter Weise, In Brudersphaeren Wettgesang,!!!!!!\n"
+ "Und ihre vorgeschriebne Reise Vollendet sie mit Donnergang. Ihr Anblick!!!!!!\n"
+ "gibt den Engeln Staerke, Wenn keiner Sie ergruenden mag; die unbegreiflich!!!!!!\n"
+ "hohen Werke Sind herrlich wie am ersten Tag.!!!!!!\n"
+ "GABRIEL: Und schnell und unbegreiflich schnelle Dreht sich umher der Erde!!!!!!\n"
+ "Pracht; Es wechselt Paradieseshelle Mit tiefer, schauervoller Nacht. Es!!!!!!\n"
+ "schaeumt das Meer in breiten Fluessen Am tiefen Grund der Felsen auf, Und!!!!!!\n"
+ "Fels und Meer wird fortgerissen Im ewig schnellem Sphaerenlauf.!!!!!!\n"
+ "MICHAEL: Und Stuerme brausen um die Wette Vom Meer aufs Land, vom Land!!!!!!\n"
+ "aufs Meer, und bilden wuetend eine Kette Der tiefsten Wirkung rings umher.!!!!!!\n"
+ "Da flammt ein blitzendes Verheeren Dem Pfade vor des Donnerschlags. Doch!!!!!!\n"
+ "deine Boten, Herr, verehren Das sanfte Wandeln deines Tags.!!!!!!\n"
+ "ZU DREI: Der Anblick gibt den Engeln Staerke, Da keiner dich ergruenden!!!!!!\n"
+ "mag, Und alle deine hohen Werke Sind herrlich wie am ersten Tag.!!!!!!\n"
+ "MEPHISTOPHELES: Da du, o Herr, dich einmal wieder nahst Und fragst, wie!!!!!!\n"
+ "alles sich bei uns befinde, Und du mich sonst gewoehnlich gerne sahst, So!!!!!!\n"
+ "siehst du mich auch unter dem Gesinde. Verzeih, ich kann nicht hohe Worte!!!!!!\n"
+ "machen, Und wenn mich auch der ganze Kreis verhoehnt; Mein Pathos braechte!!!!!!\n"
+ "dich gewiss zum Lachen, Haettst du dir nicht das Lachen abgewoehnt. Von!!!!!!\n"
+ "Sonn' und Welten weiss ich nichts zu sagen, Ich sehe nur, wie sich die!!!!!!\n"
+ "Menschen plagen. Der kleine Gott der Welt bleibt stets von gleichem!!!!!!\n"
+ "Schlag, Und ist so wunderlich als wie am ersten Tag. Ein wenig besser!!!!!!\n"
+ "wuerd er leben, Haettst du ihm nicht den Schein des Himmelslichts gegeben;!!!!!!\n"
+ "Er nennt's Vernunft und braucht's allein, Nur tierischer als jedes Tier!!!!!!\n"
+ "zu sein. Er scheint mir, mit Verlaub von euer Gnaden, Wie eine der!!!!!!\n"
+ "langbeinigen Zikaden, Die immer fliegt und fliegend springt Und gleich im!!!!!!\n"
+ "Gras ihr altes Liedchen singt; Und laeg er nur noch immer in dem Grase! In!!!!!!\n"
+ "jeden Quark begraebt er seine Nase.!!!!!!\n"
+ "DER HERR: Hast du mir weiter nichts zu sagen? Kommst du nur immer!!!!!!\n"
+ "anzuklagen? Ist auf der Erde ewig dir nichts recht?!!!!!!\n"
+ "MEPHISTOPHELES: Nein Herr! ich find es dort, wie immer, herzlich!!!!!!\n"
+ "schlecht. Die Menschen dauern mich in ihren Jammertagen, Ich mag sogar!!!!!!\n"
+ "die armen selbst nicht plagen.!!!!!!\n" + "DER HERR: Kennst du den Faust?!!!!!!\n"
+ "MEPHISTOPHELES: Den Doktor?!!!!!!\n"
+ "DER HERR: Meinen Knecht!!!!!!!\n"
+ "MEPHISTOPHELES: Fuerwahr! er dient Euch auf besondre Weise. Nicht irdisch!!!!!!\n"
+ "ist des Toren Trank noch Speise. Ihn treibt die Gaerung in die Ferne, Er!!!!!!\n"
+ "ist sich seiner Tollheit halb bewusst; Vom Himmel fordert er die schoensten!!!!!!\n"
+ "Sterne Und von der Erde jede hoechste Lust, Und alle Naeh und alle Ferne!!!!!!\n"
+ "Befriedigt nicht die tiefbewegte Brust.!!!!!!\n"
+ "DER HERR: Wenn er mir auch nur verworren dient, So werd ich ihn bald in!!!!!!\n"
+ "die Klarheit fuehren. Weiss doch der Gaertner, wenn das Baeumchen gruent, Das!!!!!!\n"
+ "Bluet und Frucht die kuenft'gen Jahre zieren.!!!!!!\n"
+ "MEPHISTOPHELES: Was wettet Ihr? den sollt Ihr noch verlieren! Wenn Ihr!!!!!!\n"
+ "mir die Erlaubnis gebt, Ihn meine Strasse sacht zu fuehren.!!!!!!\n"
+ "DER HERR: Solang er auf der Erde lebt, So lange sei dir's nicht verboten,!!!!!!\n"
+ "Es irrt der Mensch so lang er strebt.!!!!!!\n"
+ "MEPHISTOPHELES: Da dank ich Euch; denn mit den Toten Hab ich mich niemals!!!!!!\n"
+ "gern befangen. Am meisten lieb ich mir die vollen, frischen Wangen. Fuer!!!!!!\n"
+ "einem Leichnam bin ich nicht zu Haus; Mir geht es wie der Katze mit der Maus.!!!!!!\n"
+ "DER HERR: Nun gut, es sei dir ueberlassen! Zieh diesen Geist von seinem!!!!!!\n"
+ "Urquell ab, Und fuehr ihn, kannst du ihn erfassen, Auf deinem Wege mit!!!!!!\n"
+ "herab, Und steh beschaemt, wenn du bekennen musst: Ein guter Mensch, in!!!!!!\n"
+ "seinem dunklen Drange, Ist sich des rechten Weges wohl bewusst.!!!!!!\n"
+ "MEPHISTOPHELES: Schon gut! nur dauert es nicht lange. Mir ist fuer meine!!!!!!\n"
+ "Wette gar nicht bange. Wenn ich zu meinem Zweck gelange, Erlaubt Ihr mir!!!!!!\n"
+ "Triumph aus voller Brust. Staub soll er fressen, und mit Lust, Wie meine!!!!!!\n"
+ "Muhme, die beruehmte Schlange.!!!!!!\n"
+ "DER HERR: Du darfst auch da nur frei erscheinen; Ich habe deinesgleichen!!!!!!\n"
+ "nie gehasst. Von allen Geistern, die verneinen, ist mir der Schalk am!!!!!!\n"
+ "wenigsten zur Last. Des Menschen Taetigkeit kann allzu leicht erschlaffen,!!!!!!\n"
+ "er liebt sich bald die unbedingte Ruh; Drum geb ich gern ihm den Gesellen!!!!!!\n"
+ "zu, Der reizt und wirkt und muss als Teufel schaffen. Doch ihr, die echten!!!!!!\n"
+ "Goettersoehne, Erfreut euch der lebendig reichen Schoene! Das Werdende, das!!!!!!\n"
+ "ewig wirkt und lebt, Umfass euch mit der Liebe holden Schranken, Und was!!!!!!\n"
+ "in schwankender Erscheinung schwebt, Befestigt mit dauernden Gedanken!!!!!!!\n"
+ "(Der Himmel schliesst, die Erzengel verteilen sich.)!!!!!!\n"
+ "MEPHISTOPHELES (allein): Von Zeit zu Zeit seh ich den Alten gern, Und!!!!!!\n"
+ "huete mich, mit ihm zu brechen. Es ist gar huebsch von einem grossen Herrn,!!!!!!\n"
+ "So menschlich mit dem Teufel selbst zu sprechen.!!!!!!";
}
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.cme.v20191029.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class VideoTrackItem extends AbstractModel{
/**
* 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
*/
@SerializedName("SourceType")
@Expose
private String SourceType;
/**
* 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
*/
@SerializedName("SourceMedia")
@Expose
private String SourceMedia;
/**
* 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
*/
@SerializedName("SourceMediaStartTime")
@Expose
private Float SourceMediaStartTime;
/**
* 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
*/
@SerializedName("Duration")
@Expose
private Float Duration;
/**
* 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
*/
@SerializedName("XPos")
@Expose
private String XPos;
/**
* 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
*/
@SerializedName("YPos")
@Expose
private String YPos;
/**
* 视频原点位置,取值有:
<li>Center:坐标原点为中心位置,如画布中心。</li>
默认值 :Center。
*/
@SerializedName("CoordinateOrigin")
@Expose
private String CoordinateOrigin;
/**
* 视频片段的高度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Height 为画布高度的百分比大小,如 10% 表示 Height 为画布高度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Height 单位为像素,如 100px 表示 Height 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
@SerializedName("Height")
@Expose
private String Height;
/**
* 视频片段的宽度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Width 为画布宽度的百分比大小,如 10% 表示 Width 为画布宽度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Width 单位为像素,如 100px 表示 Width 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
@SerializedName("Width")
@Expose
private String Width;
/**
* Get 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
* @return SourceType 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
*/
public String getSourceType() {
return this.SourceType;
}
/**
* Set 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
* @param SourceType 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
*/
public void setSourceType(String SourceType) {
this.SourceType = SourceType;
}
/**
* Get 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
* @return SourceMedia 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
*/
public String getSourceMedia() {
return this.SourceMedia;
}
/**
* Set 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
* @param SourceMedia 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
*/
public void setSourceMedia(String SourceMedia) {
this.SourceMedia = SourceMedia;
}
/**
* Get 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
* @return SourceMediaStartTime 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
*/
public Float getSourceMediaStartTime() {
return this.SourceMediaStartTime;
}
/**
* Set 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
* @param SourceMediaStartTime 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
*/
public void setSourceMediaStartTime(Float SourceMediaStartTime) {
this.SourceMediaStartTime = SourceMediaStartTime;
}
/**
* Get 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
* @return Duration 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
*/
public Float getDuration() {
return this.Duration;
}
/**
* Set 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
* @param Duration 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
*/
public void setDuration(Float Duration) {
this.Duration = Duration;
}
/**
* Get 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
* @return XPos 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
*/
public String getXPos() {
return this.XPos;
}
/**
* Set 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
* @param XPos 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
*/
public void setXPos(String XPos) {
this.XPos = XPos;
}
/**
* Get 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
* @return YPos 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
*/
public String getYPos() {
return this.YPos;
}
/**
* Set 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
* @param YPos 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
*/
public void setYPos(String YPos) {
this.YPos = YPos;
}
/**
* Get 视频原点位置,取值有:
<li>Center:坐标原点为中心位置,如画布中心。</li>
默认值 :Center。
* @return CoordinateOrigin 视频原点位置,取值有:
<li>Center:坐标原点为中心位置,如画布中心。</li>
默认值 :Center。
*/
public String getCoordinateOrigin() {
return this.CoordinateOrigin;
}
/**
* Set 视频原点位置,取值有:
<li>Center:坐标原点为中心位置,如画布中心。</li>
默认值 :Center。
* @param CoordinateOrigin 视频原点位置,取值有:
<li>Center:坐标原点为中心位置,如画布中心。</li>
默认值 :Center。
*/
public void setCoordinateOrigin(String CoordinateOrigin) {
this.CoordinateOrigin = CoordinateOrigin;
}
/**
* Get 视频片段的高度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Height 为画布高度的百分比大小,如 10% 表示 Height 为画布高度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Height 单位为像素,如 100px 表示 Height 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
* @return Height 视频片段的高度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Height 为画布高度的百分比大小,如 10% 表示 Height 为画布高度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Height 单位为像素,如 100px 表示 Height 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
public String getHeight() {
return this.Height;
}
/**
* Set 视频片段的高度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Height 为画布高度的百分比大小,如 10% 表示 Height 为画布高度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Height 单位为像素,如 100px 表示 Height 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
* @param Height 视频片段的高度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Height 为画布高度的百分比大小,如 10% 表示 Height 为画布高度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Height 单位为像素,如 100px 表示 Height 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
public void setHeight(String Height) {
this.Height = Height;
}
/**
* Get 视频片段的宽度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Width 为画布宽度的百分比大小,如 10% 表示 Width 为画布宽度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Width 单位为像素,如 100px 表示 Width 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
* @return Width 视频片段的宽度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Width 为画布宽度的百分比大小,如 10% 表示 Width 为画布宽度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Width 单位为像素,如 100px 表示 Width 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
public String getWidth() {
return this.Width;
}
/**
* Set 视频片段的宽度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Width 为画布宽度的百分比大小,如 10% 表示 Width 为画布宽度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Width 单位为像素,如 100px 表示 Width 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
* @param Width 视频片段的宽度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Width 为画布宽度的百分比大小,如 10% 表示 Width 为画布宽度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Width 单位为像素,如 100px 表示 Width 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
public void setWidth(String Width) {
this.Width = Width;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "SourceType", this.SourceType);
this.setParamSimple(map, prefix + "SourceMedia", this.SourceMedia);
this.setParamSimple(map, prefix + "SourceMediaStartTime", this.SourceMediaStartTime);
this.setParamSimple(map, prefix + "Duration", this.Duration);
this.setParamSimple(map, prefix + "XPos", this.XPos);
this.setParamSimple(map, prefix + "YPos", this.YPos);
this.setParamSimple(map, prefix + "CoordinateOrigin", this.CoordinateOrigin);
this.setParamSimple(map, prefix + "Height", this.Height);
this.setParamSimple(map, prefix + "Width", this.Width);
}
}
|
package com.google.android.gms.internal.ads;
public final class sy extends ez {
public sy(tx txVar, String str, String str2, xp xpVar, int i2, int i3) {
super(txVar, str, str2, xpVar, i2, 3);
}
/* access modifiers changed from: protected */
@Override // com.google.android.gms.internal.ads.ez
public final void a() {
synchronized (this.f4244e) {
gx gxVar = new gx((String) this.f4245f.invoke(null, this.f4241b.a()));
synchronized (this.f4244e) {
this.f4244e.f6028e = Long.valueOf(gxVar.f4456b);
this.f4244e.d0 = Long.valueOf(gxVar.f4457c);
}
}
}
}
|
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.webservices;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Tests for {@link WebServicesProperties}.
*
* @author Madhura Bhave
*/
public class WebServicesPropertiesTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private WebServicesProperties properties;
@Test
public void pathMustNotBeEmpty() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("");
}
@Test
public void pathMustHaveLengthGreaterThanOne() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("/");
}
@Test
public void customPathMustBeginWithASlash() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must start with '/'");
this.properties.setPath("custom");
}
}
|
package com.watson.propert.tycoon.game.bord;
import com.watson.propert.tycoon.game.entitys.Player;
/** Action that from Cards and Square need implement this interface */
public interface Action {
void run(Player player);
}
|
package com.battlelancer.seriesguide.jobs.episodes;
import android.content.Context;
import androidx.annotation.NonNull;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.provider.SgEpisode2Numbers;
import com.battlelancer.seriesguide.provider.SgRoomDatabase;
import java.util.List;
public class ShowCollectedJob extends ShowBaseJob {
private final boolean isCollected;
public ShowCollectedJob(long showId, boolean isCollected) {
super(showId, isCollected ? 1 : 0, JobAction.EPISODE_COLLECTION);
this.isCollected = isCollected;
}
@Override
protected boolean applyDatabaseChanges(@NonNull Context context) {
int rowsUpdated = SgRoomDatabase.getInstance(context).sgEpisode2Helper()
.updateCollectedOfShowExcludeSpecials(getShowId(), isCollected);
return rowsUpdated >= 0; // -1 means error.
}
@NonNull
@Override
protected List<SgEpisode2Numbers> getEpisodesForNetworkJob(@NonNull Context context) {
return SgRoomDatabase.getInstance(context).sgEpisode2Helper()
.getEpisodeNumbersOfShow(getShowId());
}
@Override
protected int getPlaysForNetworkJob(int plays) {
return plays; // Collected change does not change plays.
}
@NonNull
@Override
public String getConfirmationText(Context context) {
return context.getString(isCollected
? R.string.action_collection_add : R.string.action_collection_remove);
}
}
|
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.ibiosim.gui.modelEditor.gcm;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.SBase;
import org.sbml.jsbml.Species;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.annotation.AnnotationUtility;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.annotation.SBOLAnnotation;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.parser.BioModel;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.SBMLutilities;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.GlobalConstants;
import edu.utah.ece.async.ibiosim.dataModels.util.exceptions.BioSimException;
import edu.utah.ece.async.ibiosim.gui.Gui;
import edu.utah.ece.async.ibiosim.gui.modelEditor.sbmlcore.MySpecies;
import edu.utah.ece.async.ibiosim.gui.modelEditor.sbol.SBOLField2;
import edu.utah.ece.async.ibiosim.gui.modelEditor.schematic.ModelEditor;
import edu.utah.ece.async.ibiosim.gui.modelEditor.schematic.Utils;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.PropertyField;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.PropertyList;
/**
*
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class PromoterPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 5873800942710657929L;
private String[] options = { "Ok", "Cancel" };
private HashMap<String, PropertyField> fields = null;
private SBOLField2 sbolField;
private String selected = "";
private BioModel bioModel = null;
private boolean paramsOnly;
private ModelEditor modelEditor = null;
private Species promoter = null;
private Reaction production = null;
private PropertyList speciesList;
private JComboBox compartBox = null;
private JTextField iIndex = null;
public PromoterPanel(String selected, BioModel bioModel, PropertyList speciesList, boolean paramsOnly, BioModel refGCM,
ModelEditor modelEditor) {
super(new GridLayout(paramsOnly?7:13, 1));
this.selected = selected;
this.bioModel = bioModel;
this.paramsOnly = paramsOnly;
this.modelEditor = modelEditor;
this.speciesList = speciesList;
fields = new HashMap<String, PropertyField>();
Model model = bioModel.getSBMLDocument().getModel();
promoter = model.getSpecies(selected);
PropertyField field = null;
// ID field
String dimInID = SBMLutilities.getDimensionString(promoter);
field = new PropertyField(GlobalConstants.ID, promoter.getId() + dimInID, null, null, Utility.IDDimString, paramsOnly, "default", false);
fields.put(GlobalConstants.ID, field);
if (!paramsOnly) add(field);
// Name field
field = new PropertyField(GlobalConstants.NAME, promoter.getName(), null, null, Utility.NAMEstring, paramsOnly, "default", false);
fields.put(GlobalConstants.NAME, field);
if (!paramsOnly) add(field);
// Type field
JPanel tempPanel = new JPanel();
JLabel tempLabel = new JLabel(GlobalConstants.PORTTYPE);
typeBox = new JComboBox(types);
//typeBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(typeBox);
if (!paramsOnly) add(tempPanel);
if (bioModel.isInput(promoter.getId())) {
typeBox.setSelectedItem(GlobalConstants.INPUT);
} else if (bioModel.isOutput(promoter.getId())) {
typeBox.setSelectedItem(GlobalConstants.OUTPUT);
} else {
typeBox.setSelectedItem(GlobalConstants.INTERNAL);
}
production = bioModel.getProductionReaction(selected);
// compartment field
tempPanel = new JPanel();
tempLabel = new JLabel("Compartment");
compartBox = MySpecies.createCompartmentChoices(bioModel);
compartBox.setSelectedItem(promoter.getCompartment());
compartBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(compartBox);
if (!paramsOnly) add(tempPanel);
// indices field
tempPanel = new JPanel(new GridLayout(1, 2));
iIndex = new JTextField(20);
String freshIndex = SBMLutilities.getIndicesString(promoter, "compartment");
iIndex.setText(freshIndex);
tempPanel.add(new JLabel("Compartment Indices"));
tempPanel.add(iIndex);
if (!paramsOnly) add(tempPanel);
// promoter count
String origString = "default";
String defaultValue = bioModel.getParameter(GlobalConstants.PROMOTER_COUNT_STRING);
String formatString = Utility.NUMstring;
if (paramsOnly) {
if (refGCM.getSBMLDocument().getModel().getSpecies(promoter.getId()).getInitialAmount() !=
model.getParameter(GlobalConstants.PROMOTER_COUNT_STRING).getValue()) {
defaultValue = ""+refGCM.getSBMLDocument().getModel().getSpecies(promoter.getId()).getInitialAmount();
origString = "custom";
}
formatString = Utility.SWEEPstring;
}
field = new PropertyField(GlobalConstants.PROMOTER_COUNT_STRING,
bioModel.getParameter(GlobalConstants.PROMOTER_COUNT_STRING), origString,
defaultValue, formatString, paramsOnly, origString, false);
String sweep = AnnotationUtility.parseSweepAnnotation(promoter);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (!defaultValue.equals(""+promoter.getInitialAmount())) {
field.setValue(""+promoter.getInitialAmount());
field.setCustom();
}
fields.put(GlobalConstants.PROMOTER_COUNT_STRING, field);
add(field);
// RNAP binding
origString = "default";
defaultValue = bioModel.getParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING) + "/" +
bioModel.getParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
formatString = Utility.SLASHstring;
if (paramsOnly) {
/*
defaultValue = refGCM.getParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING)+"/"+
refGCM.getParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING); */
if (production != null) {
Reaction refProd = refGCM.getSBMLDocument().getModel().getReaction(production.getId());
LocalParameter ko_f = refProd.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING);
LocalParameter ko_r = refProd.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
if (ko_f != null && ko_r != null) {
defaultValue = ko_f.getValue()+"/"+ko_r.getValue();
origString = "custom";
}
}
formatString = Utility.SLASHSWEEPstring;
}
field = new PropertyField(GlobalConstants.RNAP_BINDING_STRING, defaultValue, origString, defaultValue, formatString, paramsOnly,
origString, false);
if (production != null) {
LocalParameter ko_f = production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING);
LocalParameter ko_r = production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
sweep = AnnotationUtility.parseSweepAnnotation(ko_f);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (ko_f != null && ko_r != null && !defaultValue.equals(ko_f.getValue()+"/"+ko_r.getValue())) {
field.setValue(ko_f.getValue()+"/"+ko_r.getValue());
field.setCustom();
}
}
fields.put(GlobalConstants.RNAP_BINDING_STRING, field);
add(field);
// Activated RNAP binding
origString = "default";
defaultValue = bioModel.getParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING) + "/" +
bioModel.getParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING);
formatString = Utility.SLASHstring;
if (paramsOnly) {
/*
defaultValue = refGCM.getParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING) + "/" +
refGCM.getParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING); */
if (production != null) {
Reaction refProd = refGCM.getSBMLDocument().getModel().getReaction(production.getId());
LocalParameter kao_f = refProd.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING);
LocalParameter kao_r = refProd.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING);
if (kao_f != null && kao_r != null) {
defaultValue = kao_f.getValue()+"/"+kao_r.getValue();
origString = "custom";
}
}
formatString = Utility.SLASHSWEEPstring;
}
field = new PropertyField(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING, defaultValue, origString, defaultValue,
formatString, paramsOnly, origString, false);
if (production != null) {
LocalParameter kao_f = production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING);
LocalParameter kao_r = production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING);
sweep = AnnotationUtility.parseSweepAnnotation(kao_f);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (kao_f != null && kao_r != null && !defaultValue.equals(kao_f.getValue()+"/"+kao_r.getValue())) {
field.setValue(kao_f.getValue()+"/"+kao_r.getValue());
field.setCustom();
}
}
fields.put(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING, field);
add(field);
// kocr
origString = "default";
defaultValue = bioModel.getParameter(GlobalConstants.OCR_STRING);
formatString = Utility.NUMstring;
if (paramsOnly) {
//defaultValue = refGCM.getParameter(GlobalConstants.OCR_STRING);
if (production != null) {
Reaction refProd = refGCM.getSBMLDocument().getModel().getReaction(production.getId());
LocalParameter ko = refProd.getKineticLaw().getLocalParameter(GlobalConstants.OCR_STRING);
if (ko != null) {
defaultValue = ko.getValue()+"";
origString = "custom";
}
}
formatString = Utility.SWEEPstring;
}
field = new PropertyField(GlobalConstants.OCR_STRING, bioModel.getParameter(GlobalConstants.OCR_STRING),
origString, defaultValue, formatString, paramsOnly, origString, false);
if (production != null) {
LocalParameter ko = production.getKineticLaw().getLocalParameter(GlobalConstants.OCR_STRING);
sweep = AnnotationUtility.parseSweepAnnotation(ko);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (ko != null && !defaultValue.equals(ko.getValue()+"")) {
field.setValue(ko.getValue()+"");
field.setCustom();
}
}
fields.put(GlobalConstants.OCR_STRING, field);
add(field);
// kbasal
origString = "default";
defaultValue = bioModel.getParameter(GlobalConstants.KBASAL_STRING);
formatString = Utility.NUMstring;
if (paramsOnly) {
if (production != null) {
Reaction refProd = refGCM.getSBMLDocument().getModel().getReaction(production.getId());
LocalParameter kb = refProd.getKineticLaw().getLocalParameter(GlobalConstants.KBASAL_STRING);
if (kb != null) {
defaultValue = kb.getValue()+"";
origString = "custom";
}
}
formatString = Utility.SWEEPstring;
}
field = new PropertyField(GlobalConstants.KBASAL_STRING, bioModel.getParameter(GlobalConstants.KBASAL_STRING),
origString, defaultValue, Utility.SWEEPstring, paramsOnly, origString, false);
if (production != null) {
LocalParameter kb = production.getKineticLaw().getLocalParameter(GlobalConstants.KBASAL_STRING);
sweep = AnnotationUtility.parseSweepAnnotation(kb);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (kb != null && !defaultValue.equals(kb.getValue()+"")) {
field.setValue(kb.getValue()+"");
field.setCustom();
}
}
fields.put(GlobalConstants.KBASAL_STRING, field);
add(field);
// kactived production
origString = "default";
defaultValue = bioModel.getParameter(GlobalConstants.ACTIVATED_STRING);
formatString = Utility.NUMstring;
if (paramsOnly) {
if (production != null) {
Reaction refProd = refGCM.getSBMLDocument().getModel().getReaction(production.getId());
LocalParameter ka = refProd.getKineticLaw().getLocalParameter(GlobalConstants.ACTIVATED_STRING);
if (ka != null) {
defaultValue = ka.getValue()+"";
origString = "custom";
}
}
formatString = Utility.SWEEPstring;
}
field = new PropertyField(GlobalConstants.ACTIVATED_STRING, bioModel.getParameter(GlobalConstants.ACTIVATED_STRING),
origString, defaultValue, formatString, paramsOnly, origString, false);
if (production != null) {
LocalParameter ka = production.getKineticLaw().getLocalParameter(GlobalConstants.ACTIVATED_STRING);
sweep = AnnotationUtility.parseSweepAnnotation(ka);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (ka != null && !defaultValue.equals(ka.getValue()+"")) {
field.setValue(ka.getValue()+"");
field.setCustom();
}
}
fields.put(GlobalConstants.ACTIVATED_STRING, field);
add(field);
// stoichiometry
origString = "default";
defaultValue = bioModel.getParameter(GlobalConstants.STOICHIOMETRY_STRING);
formatString = Utility.NUMstring;
if (paramsOnly) {
if (production != null) {
Reaction refProd = refGCM.getSBMLDocument().getModel().getReaction(production.getId());
LocalParameter np = refProd.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING);
if (np != null) {
defaultValue = np.getValue()+"";
origString = "custom";
}
}
formatString = Utility.SWEEPstring;
}
field = new PropertyField(GlobalConstants.STOICHIOMETRY_STRING, bioModel.getParameter(GlobalConstants.STOICHIOMETRY_STRING),
origString, defaultValue, formatString, paramsOnly, origString, false);
if (production != null) {
LocalParameter np = production.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING);
sweep = AnnotationUtility.parseSweepAnnotation(np);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (np != null && !defaultValue.equals(np.getValue()+"")) {
field.setValue(np.getValue()+"");
field.setCustom();
}
}
fields.put(GlobalConstants.STOICHIOMETRY_STRING, field);
add(field);
// Parse out SBOL annotations and add to SBOL field
if (!paramsOnly) {
// Field for annotating promoter with SBOL DNA components
List<URI> sbolURIs = new LinkedList<URI>();
String sbolStrand = AnnotationUtility.parseSBOLAnnotation(production, sbolURIs);
if (sbolURIs.size()>0 && sbolField.getSBOLObjSBOTerm().equals(GlobalConstants.SBO_DNA_SEGMENT))
{
SBOLAnnotation sbolAnnot = new SBOLAnnotation(selected, sbolURIs, sbolStrand);
sbolAnnot.createSBOLElementsDescription(GlobalConstants.SBOL_COMPONENTDEFINITION,
sbolField.getSBOLURIs().iterator().next());
if(!AnnotationUtility.setSBOLAnnotation(promoter, sbolAnnot))
{
JOptionPane.showMessageDialog(Gui.frame,
"Invalid XML in SBML file",
"Error occurred while annotating SBML element " + SBMLutilities.getId(promoter) + " with SBOL.",
JOptionPane.ERROR_MESSAGE);
}
else
{
AnnotationUtility.removeSBOLAnnotation(production);
}
}
else
{
sbolStrand = AnnotationUtility.parseSBOLAnnotation(promoter, sbolURIs);
}
sbolField = new SBOLField2(sbolURIs, sbolStrand, GlobalConstants.SBOL_COMPONENTDEFINITION, modelEditor,
3, false);
add(sbolField);
}
String oldName = null;
oldName = selected;
boolean display = false;
while (!display) {
display = openGui(oldName);
}
}
private boolean checkValues() {
for (PropertyField f : fields.values()) {
if (!f.isValidValue()) {
return false;
}
}
return true;
}
private boolean openGui(String oldName) {
int value = JOptionPane.showOptionDialog(Gui.frame, this,
"Promoter Editor", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
boolean valueCheck = checkValues();
if (!valueCheck) {
JOptionPane.showMessageDialog(Gui.frame, "Illegal values entered.", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
String[] idDims = new String[]{""};
String[] dimensionIds = new String[]{""};
String[] dex = new String[]{""};
idDims = Utils.checkSizeParameters(bioModel.getSBMLDocument(),
fields.get(GlobalConstants.ID).getValue(), false);
if(idDims==null)return false;
dimensionIds = SBMLutilities.getDimensionIds("",idDims.length-1);
String id = selected;
if (!paramsOnly) {
if (oldName == null) {
if (bioModel.isSIdInUse(idDims[0])) {
JOptionPane.showMessageDialog(Gui.frame, "Id already exists.", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
else if (!oldName.equals(idDims[0])) {
if (bioModel.isSIdInUse(idDims[0])) {
JOptionPane.showMessageDialog(Gui.frame, "Id already exists.", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
id = idDims[0];
promoter.setName(fields.get(GlobalConstants.NAME).getValue());
SBMLutilities.createDimensions(promoter, dimensionIds, idDims);
SBase variable = SBMLutilities.getElementBySId(bioModel.getSBMLDocument(), (String)compartBox.getSelectedItem());
dex = Utils.checkIndices(iIndex.getText(), variable, bioModel.getSBMLDocument(), dimensionIds, "compartment", idDims, null, null);
if(dex==null)return false;
SBMLutilities.addIndices(promoter, "compartment", dex, 1);
SBMLutilities.addIndices(production, "compartment", dex, 1);
}
promoter.setCompartment((String)compartBox.getSelectedItem());
production.setCompartment((String)compartBox.getSelectedItem());
String speciesType = typeBox.getSelectedItem().toString();
boolean onPort = (speciesType.equals(GlobalConstants.INPUT)||speciesType.equals(GlobalConstants.OUTPUT));
promoter.setSBOTerm(GlobalConstants.SBO_PROMOTER_BINDING_REGION);
PropertyField f = fields.get(GlobalConstants.PROMOTER_COUNT_STRING);
if (f.getValue().startsWith("(")) {
promoter.setInitialAmount(1.0);
if(!AnnotationUtility.setSweepAnnotation(promoter, f.getValue()))
{
JOptionPane.showMessageDialog(Gui.frame, "Invalid XML Operation", "Error occurred while annotating SBML element "
+ SBMLutilities.getId(promoter), JOptionPane.ERROR_MESSAGE);
}
} else {
promoter.setInitialAmount(Double.parseDouble(f.getValue()));
}
String kaStr = null;
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.STOICHIOMETRY_STRING);
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.OCR_STRING);
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.KBASAL_STRING);
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.ACTIVATED_STRING);
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.FORWARD_RNAP_BINDING_STRING);
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING);
production.getKineticLaw().getListOfLocalParameters().remove(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING);
f = fields.get(GlobalConstants.ACTIVATED_STRING);
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
kaStr = f.getValue();
}
String npStr = null;
f = fields.get(GlobalConstants.STOICHIOMETRY_STRING);
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
npStr = f.getValue();
}
String koStr = null;
f = fields.get(GlobalConstants.OCR_STRING);
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
koStr = f.getValue();
}
String kbStr = null;
f = fields.get(GlobalConstants.KBASAL_STRING);
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
kbStr = f.getValue();
}
String KoStr = null;
f = fields.get(GlobalConstants.RNAP_BINDING_STRING);
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
KoStr = f.getValue();
}
String KaoStr = null;
f = fields.get(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING);
if (f.getState() == null || f.getState().equals(f.getStates()[1])) {
KaoStr = f.getValue();
}
bioModel.createProductionReaction(selected,kaStr,npStr,koStr,kbStr,KoStr,KaoStr,onPort,idDims);
if (!paramsOnly) {
// rename all the influences that use this promoter if name was changed
if (selected != null && oldName != null && !oldName.equals(id)) {
try {
bioModel.changePromoterId(oldName, id);
} catch (BioSimException e) {
JOptionPane.showMessageDialog(Gui.frame, e.getTitle(), e.getMessage(),
JOptionPane.ERROR_MESSAGE);
}
this.secondToLastUsedPromoter = oldName;
promoterNameChange = true;
}
// Add SBOL annotation to promoter
if (sbolField.getSBOLURIs().size() > 0)
{
if(sbolField.isSBOLSBOSet() && !sbolField.getSBOLObjSBOTerm().equals(GlobalConstants.SBO_DNA_SEGMENT))
{
JOptionPane.showMessageDialog(Gui.frame,
"You are not allowed to annotate a promoter that does not have SBOL component type DNA.",
"Prohibited SBOL Annotation Type",
JOptionPane.WARNING_MESSAGE);
}
else
{
if (!production.isSetMetaId() || production.getMetaId().equals(""))
SBMLutilities.setDefaultMetaID(bioModel.getSBMLDocument(), production,
bioModel.getMetaIDIndex());
//try
//{
// TODO: removed this since changing id based on SBOL field could cause name conflicts
//bioModel.changePromoterId(id, SBMLutilities.getUniqueSBMLId(sbolField.getSBOLObjID(), bioModel));
setSBOLAnnotation(promoter);
//}
//catch (BioSimException e)
//{
// JOptionPane.showMessageDialog(Gui.frame, e.getTitle(), e.getMessage(),
// JOptionPane.ERROR_MESSAGE);
//}
}
} else
AnnotationUtility.removeSBOLAnnotation(promoter);
bioModel.createDirPort(promoter.getId(),speciesType);
this.lastUsedPromoter = id;
}
speciesList.removeItem(selected);
speciesList.removeItem(selected + " Modified");
speciesList.addItem(id);
speciesList.setSelectedValue(id, true);
modelEditor.refresh();
modelEditor.setDirty(true);
} else if (value == JOptionPane.NO_OPTION) {
return true;
}
return true;
}
/**
* Perform annotation on the SBML element with the SBOL object that was selected from SBOL association.
* @param sbmlElement - The SBML element to set the SBOL annotation on.
*/
private void setSBOLAnnotation(SBase sbmlElement)
{
SBOLAnnotation sbolAnnot = new SBOLAnnotation(sbmlElement.getMetaId(),
sbolField.getSBOLURIs(), sbolField.getSBOLStrand());
sbolAnnot.createSBOLElementsDescription(GlobalConstants.SBOL_COMPONENTDEFINITION,
sbolField.getSBOLURIs().iterator().next());
if(!AnnotationUtility.setSBOLAnnotation(sbmlElement, sbolAnnot))
{
JOptionPane.showMessageDialog(Gui.frame,
"Error occurred while annotating SBML element " + sbmlElement.getId() + " with SBOL.",
"Invalid XML in SBML file",
JOptionPane.ERROR_MESSAGE);
}
if(sbolField.isSBOLNameSet())
{
sbmlElement.setName(sbolField.getSBOLObjName());
}
if(sbolField.isSBOLSBOSet())
{
sbmlElement.setSBOTerm(sbolField.getSBOLObjSBOTerm());
}
}
public String updates() {
String updates = "";
if (paramsOnly) {
if (fields.get(GlobalConstants.PROMOTER_COUNT_STRING).getState().equals(fields.get(GlobalConstants.PROMOTER_COUNT_STRING).getStates()[1])) {
updates += selected + "/" + GlobalConstants.PROMOTER_COUNT_STRING + " "
+ fields.get(GlobalConstants.PROMOTER_COUNT_STRING).getValue();
}
if (fields.get(GlobalConstants.RNAP_BINDING_STRING).getState()
.equals(fields.get(GlobalConstants.RNAP_BINDING_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += selected + "/" + GlobalConstants.RNAP_BINDING_STRING + " "
+ fields.get(GlobalConstants.RNAP_BINDING_STRING).getValue();
}
if (fields.get(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING).getState()
.equals(fields.get(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += selected + "/" + GlobalConstants.ACTIVATED_RNAP_BINDING_STRING + " "
+ fields.get(GlobalConstants.ACTIVATED_RNAP_BINDING_STRING).getValue();
}
if (fields.get(GlobalConstants.OCR_STRING).getState().equals(fields.get(GlobalConstants.OCR_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += selected + "/" + GlobalConstants.OCR_STRING + " "
+ fields.get(GlobalConstants.OCR_STRING).getValue();
}
if (fields.get(GlobalConstants.STOICHIOMETRY_STRING).getState().equals(fields.get(GlobalConstants.STOICHIOMETRY_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += selected + "/" + GlobalConstants.STOICHIOMETRY_STRING + " "
+ fields.get(GlobalConstants.STOICHIOMETRY_STRING).getValue();
}
if (fields.get(GlobalConstants.KBASAL_STRING).getState().equals(fields.get(GlobalConstants.KBASAL_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += selected + "/" + GlobalConstants.KBASAL_STRING + " "
+ fields.get(GlobalConstants.KBASAL_STRING).getValue();
}
if (fields.get(GlobalConstants.ACTIVATED_STRING).getState().equals(fields.get(GlobalConstants.ACTIVATED_STRING).getStates()[1])) {
if (!updates.equals("")) {
updates += "\n";
}
updates += selected + "/" + GlobalConstants.ACTIVATED_STRING + " "
+ fields.get(GlobalConstants.ACTIVATED_STRING).getValue();
}
if (updates.equals("")) {
updates += selected + "/";
}
}
return updates;
}
// Provide a public way to query what the last used (or created) promoter was.
private String lastUsedPromoter;
public String getLastUsedPromoter(){return lastUsedPromoter;}
private String secondToLastUsedPromoter;
public String getSecondToLastUsedPromoter(){return secondToLastUsedPromoter;}
private boolean promoterNameChange = false;
public boolean wasPromoterNameChanged(){return promoterNameChange;}
private static final String[] types = new String[] { GlobalConstants.INPUT, GlobalConstants.INTERNAL,
GlobalConstants.OUTPUT};
private JComboBox typeBox = null;
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == compartBox){
if (bioModel.isArray((String)compartBox.getSelectedItem())) {
iIndex.setEnabled(true);
} else {
iIndex.setText("");
iIndex.setEnabled(false);
}
}
}
}
|
package org.basex.query.value.item;
import static org.basex.data.DataText.*;
import org.basex.query.expr.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* String item ({@code xs:string}, {@code xs:normalizedString}, {@code xs:language},
* etc.).
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public class Str extends AStr {
/** Zero-length string. */
public static final Str ZERO = new Str(Token.EMPTY);
/** String data. */
final byte[] val;
/**
* Constructor.
* @param v value
*/
private Str(final byte[] v) {
this(v, AtomType.STR);
}
/**
* Constructor.
* @param v value
* @param t data type
*/
public Str(final byte[] v, final AtomType t) {
super(t);
val = v;
}
/**
* Returns an instance of this class.
* @param v value
* @return instance
*/
public static Str get(final byte[] v) {
return v.length == 0 ? ZERO : new Str(v);
}
/**
* Returns an instance of this class.
* @param v object (will be converted to token)
* @return instance
*/
public static Str get(final Object v) {
return get(Token.token(v.toString()));
}
@Override
public final byte[] string(final InputInfo ii) {
return val;
}
/**
* Returns the string value.
* @return string value
*/
public final byte[] string() {
return val;
}
@Override
public final boolean sameAs(final Expr cmp) {
if(!(cmp instanceof Str)) return false;
final Str i = (Str) cmp;
return type == i.type && Token.eq(val, i.val);
}
@Override
public final String toJava() {
return Token.string(val);
}
@Override
public final String toString() {
final ByteList tb = new ByteList();
tb.add('"');
for(final byte v : val) {
if(v == '&') tb.add(E_AMP);
else tb.add(v);
if(v == '"') tb.add(v);
}
return tb.add('"').toString();
}
}
|
package senntyou.sbs.mbg.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class AdminRolePermissionRelation implements Serializable {
private Long id;
private Long roleId;
private Long permissionId;
/**
* 创建时间
*
* @mbg.generated
*/
@ApiModelProperty(value = "创建时间")
private Date createTime;
/**
* 更新时间
*
* @mbg.generated
*/
@ApiModelProperty(value = "更新时间")
private Date updateTime;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getPermissionId() {
return permissionId;
}
public void setPermissionId(Long permissionId) {
this.permissionId = permissionId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", roleId=").append(roleId);
sb.append(", permissionId=").append(permissionId);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
package top.jfunc.http.component;
import top.jfunc.http.request.HttpRequest;
import java.io.IOException;
/**
* 封装真正执行的一步
* @see RequestExecutor
* @author xiongshiyan at 2020/1/6 , contact me with email yanshixiong@126.com or phone 15208384257
*/
@Deprecated
public interface RequestSender<Request , Response> {
/**
* Request发起请求,得到响应Response
* @param request Request
* @param httpRequest HttpRequest
* @return Response
* @throws IOException IOException
*/
Response send(Request request , HttpRequest httpRequest) throws IOException;
}
|
package org.gradle.fairy.tale.formula;
import org.gradle.actors.Actor;
import org.gradle.actors.Group;
import org.gradle.fairy.tale.Tale;
import org.gradle.fairy.tale.formula.events.Event;
import org.gradle.fairy.tale.formula.events.IntransativeEvent;
import org.gradle.fairy.tale.formula.events.TransitiveEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Represents a fairy tale.
*/
public class FairyTale implements Tale {
private final List<Actor> actors;
private final List<Event> events;
private FairyTale(List<Actor> actors, List<Event> events) {
this.actors = actors;
this.events = events;
}
@Override
public void tell() {
StringBuilder builder = new StringBuilder("Once upon a time, there lived ");
for (int i=0; i < actors.size(); i++) {
if (i == actors.size() - 1 && i != 0) {
builder.append("and ");
}
builder.append(actors.get(i));
if (i != actors.size() - 1 && actors.size() > 1) {
builder.append(", ");
}
}
builder.append(".").append(System.getProperty("line.separator"));
for (Event event : events) {
builder.append(event).append(System.getProperty("line.separator"));
}
builder.append("And they all lived happily ever after.")
.append(System.getProperty("line.separator"))
.append(System.getProperty("line.separator"));
System.out.print(builder.toString());
}
public static Weaver getWeaver() {
return new Weaver(new HashSet<>(), new HashSet<>(), new ArrayList<>());
}
public static class Weaver {
private final Set<Actor> actorSet;
private final Set<Actor> groupActors;
private final List<Event> events;
private Weaver(Set<Actor> actorSet, Set<Actor> groupActors, List<Event> events) {
this.actorSet = actorSet;
this.groupActors = groupActors;
this.events = events;
}
public Tale weave() {
List<Actor> actors = new ArrayList<>();
actors.addAll(actorSet);
return new FairyTale(actors, events);
}
public Weaver record(Actor actor, String action) {
addActorOrGroup(actor);
events.add(new IntransativeEvent(actor, action));
return this;
}
public Weaver record(Actor actor, String action, Actor object) {
addActorOrGroup(actor);
addActorOrGroup(object);
events.add(new TransitiveEvent(actor, action, object));
return this;
}
private void addActorOrGroup(Actor actor) {
if (actor instanceof Group) {
for(Actor a : (Group) actor) {
actorSet.remove(a);
groupActors.add(a);
}
}
if (!groupActors.contains(actor)) {
actorSet.add(actor);
}
}
}
}
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.directconnect.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.directconnect.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DirectConnectGatewayAttachment JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DirectConnectGatewayAttachmentJsonUnmarshaller implements Unmarshaller<DirectConnectGatewayAttachment, JsonUnmarshallerContext> {
public DirectConnectGatewayAttachment unmarshall(JsonUnmarshallerContext context) throws Exception {
DirectConnectGatewayAttachment directConnectGatewayAttachment = new DirectConnectGatewayAttachment();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("directConnectGatewayId", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setDirectConnectGatewayId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("virtualInterfaceId", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setVirtualInterfaceId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("virtualInterfaceRegion", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setVirtualInterfaceRegion(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("virtualInterfaceOwnerAccount", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setVirtualInterfaceOwnerAccount(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("attachmentState", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setAttachmentState(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("attachmentType", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setAttachmentType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("stateChangeError", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setStateChangeError(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return directConnectGatewayAttachment;
}
private static DirectConnectGatewayAttachmentJsonUnmarshaller instance;
public static DirectConnectGatewayAttachmentJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DirectConnectGatewayAttachmentJsonUnmarshaller();
return instance;
}
}
|
// Template Source: IBaseEntityReferenceRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.AndroidForWorkTrustedRootCertificate;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.models.extensions.AndroidForWorkTrustedRootCertificate;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Android For Work Trusted Root Certificate Reference Request Builder.
*/
public interface IAndroidForWorkTrustedRootCertificateReferenceRequestBuilder extends IRequestBuilder {
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the IAndroidForWorkTrustedRootCertificateReferenceRequest instance
*/
IAndroidForWorkTrustedRootCertificateReferenceRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions);
/**
* Creates the request with specific options instead of the existing options
*
* @param requestOptions the options for this request
* @return the IAndroidForWorkTrustedRootCertificateReferenceRequest instance
*/
IAndroidForWorkTrustedRootCertificateReferenceRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions);
}
|
/**************************************************************
*
* 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 storagetesting;
public interface StorageTest
{
boolean test();
}
|
/*
* MIT License
*
* Copyright (c) 2018 octopusdownloader
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.octopus.dialogs.newdownload;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.stage.Stage;
import org.octopus.alerts.CommonAlerts;
import org.octopus.downloads.DownloadInfo;
public class AddNewDownloadDialog extends Dialog<DownloadInfo> {
private ButtonType downloadButtonType;
private AddNewDownloadController controller;
public AddNewDownloadDialog() {
setTitle("Add new download");
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/scenes/dialogs/new-download-dialog.fxml"));
Parent root = loader.load();
controller = loader.getController();
controller.setRoot((Stage) getDialogPane().getScene().getWindow());
downloadButtonType = new ButtonType("Download", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
getDialogPane().getButtonTypes().addAll(downloadButtonType, cancelButtonType);
getDialogPane().setContent(root);
} catch (Exception e) {
Alert alert = CommonAlerts.StackTraceAlert("Error", "Something went wrong", e.getMessage(), e);
alert.showAndWait();
System.exit(1);
}
// TODO validation
setResultConverter(buttonType -> {
if (buttonType == downloadButtonType) {
return new DownloadInfo(controller.getAddress(), controller.getBaseDirectory(), controller.getName());
}
return null;
});
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.vector.expressions;
import java.util.Arrays;
import org.apache.hadoop.hive.ql.exec.vector.ColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.metadata.HiveException;
/**
* This expression evaluates to true if the given input columns is null.
* The boolean output is stored in the specified output column.
*/
public class IsNull extends VectorExpression {
private static final long serialVersionUID = 1L;
private final int colNum;
public IsNull(int colNum, int outputColumnNum) {
super(outputColumnNum);
this.colNum = colNum;
}
public IsNull() {
super();
// Dummy final assignments.
colNum = -1;
}
@Override
public void evaluate(VectorizedRowBatch batch) throws HiveException {
if (childExpressions != null) {
super.evaluateChildren(batch);
}
ColumnVector inputColVector = batch.cols[colNum];
int[] sel = batch.selected;
boolean[] inputIsNull = inputColVector.isNull;
int n = batch.size;
LongColumnVector outputColVector = (LongColumnVector) batch.cols[outputColumnNum];
long[] outputVector = outputColVector.vector;
boolean[] outputIsNull = outputColVector.isNull;
if (n <= 0) {
// Nothing to do, this is EOF
return;
}
// We do not need to do a column reset since we are carefully changing the output.
outputColVector.isRepeating = false;
if (inputColVector.noNulls) {
outputColVector.isRepeating = true;
outputIsNull[0] = false;
outputVector[0] = 0;
} else if (inputColVector.isRepeating) {
outputColVector.isRepeating = true;
outputIsNull[0] = false;
outputVector[0] = inputIsNull[0] ? 1 : 0;
} else {
/*
* Since we have a result for all rows, we don't need to do conditional NULL maintenance or
* turn off noNulls..
*/
if (batch.selectedInUse) {
for (int j = 0; j != n; j++) {
int i = sel[j];
outputIsNull[i] = false;
outputVector[i] = inputIsNull[i] ? 1 : 0;
}
} else {
Arrays.fill(outputIsNull, 0, n, false);
for (int i = 0; i != n; i++) {
outputVector[i] = inputIsNull[i] ? 1 : 0;
}
}
}
}
@Override
public String vectorExpressionParameters() {
return getColumnParamString(0, colNum);
}
@Override
public VectorExpressionDescriptor.Descriptor getDescriptor() {
VectorExpressionDescriptor.Builder b = new VectorExpressionDescriptor.Builder();
b.setMode(VectorExpressionDescriptor.Mode.PROJECTION)
.setNumArguments(1)
.setArgumentTypes(
VectorExpressionDescriptor.ArgumentType.ALL_FAMILY)
.setInputExpressionTypes(
VectorExpressionDescriptor.InputExpressionType.COLUMN);
return b.build();
}
}
|
package ink.cashflow.abstractfactory.abztract;
public abstract class AbstractWhiteHuman implements Human {
@Override
public void cry() {
System.out.println("白色人种会哭");
}
@Override
public void laugh() {
System.out.println("白色人种会大笑,侵略的笑声");
}
@Override
public void talk() {
System.out.println("白色人种会说话,一般都是但是单字节!");
}
}
|
/*
* Copyright (c) 2020, 2021 Microsoft Corporation
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Amadeus - initial API and implementation
*
*/
package org.eclipse.dataspaceconnector.iam.daps;
import org.eclipse.dataspaceconnector.common.annotations.IntegrationTest;
import org.eclipse.dataspaceconnector.core.security.fs.FsCertificateResolver;
import org.eclipse.dataspaceconnector.core.security.fs.FsPrivateKeyResolver;
import org.eclipse.dataspaceconnector.junit.launcher.EdcExtension;
import org.eclipse.dataspaceconnector.junit.launcher.MockVault;
import org.eclipse.dataspaceconnector.spi.EdcException;
import org.eclipse.dataspaceconnector.spi.iam.IdentityService;
import org.eclipse.dataspaceconnector.spi.security.CertificateResolver;
import org.eclipse.dataspaceconnector.spi.security.PrivateKeyResolver;
import org.eclipse.dataspaceconnector.spi.security.Vault;
import org.eclipse.dataspaceconnector.spi.system.ConfigurationExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Map;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
@IntegrationTest
@ExtendWith(EdcExtension.class)
class DapsIntegrationTest {
private static final String AUDIENCE_IDS_CONNECTORS_ALL = "idsc:IDS_CONNECTORS_ALL";
private static final String CLIENT_ID = "68:99:2E:D4:13:2D:FD:3A:66:6B:85:DE:FB:98:2E:2D:FD:E7:83:D7";
private static final String CLIENT_KEYSTORE_KEY_ALIAS = "1";
private static final String CLIENT_KEYSTORE_PASSWORD = "1234";
private static final String DAPS_URL = "http://localhost:4567";
private final Map<String, String> configuration = Map.of(
"edc.oauth.token.url", DAPS_URL + "/token",
"edc.oauth.client.id", CLIENT_ID,
"edc.oauth.provider.audience", AUDIENCE_IDS_CONNECTORS_ALL,
"edc.oauth.provider.jwks.url", DAPS_URL + "/.well-known/jwks.json",
"edc.oauth.public.key.alias", CLIENT_KEYSTORE_KEY_ALIAS,
"edc.oauth.private.key.alias", CLIENT_KEYSTORE_KEY_ALIAS
);
private static KeyStore readKeystoreFromResources(String fileName, String type, String password) {
var url = Thread.currentThread().getContextClassLoader().getResource(fileName);
Objects.requireNonNull(url);
try {
var ks = KeyStore.getInstance(type);
var fis = new FileInputStream(url.getFile());
ks.load(fis, password.toCharArray());
return ks;
} catch (Exception e) {
throw new EdcException("Failed to load keystore: " + e);
}
}
@Test
void retrieveTokenAndValidate(IdentityService identityService) {
var tokenResult = identityService.obtainClientCredentials("idsc:IDS_CONNECTOR_ATTRIBUTES_ALL");
assertThat(tokenResult.succeeded()).isTrue();
var verificationResult = identityService.verifyJwtToken(tokenResult.getContent().getToken(), AUDIENCE_IDS_CONNECTORS_ALL);
assertThat(verificationResult.succeeded()).isTrue();
}
@BeforeEach
protected void before(EdcExtension extension) {
KeyStore clientKeystore = readKeystoreFromResources("keystore.p12", "PKCS12", CLIENT_KEYSTORE_PASSWORD);
extension.registerSystemExtension(ConfigurationExtension.class, (ConfigurationExtension) configuration::get);
extension.registerServiceMock(Vault.class, new MockVault());
extension.registerServiceMock(PrivateKeyResolver.class, new FsPrivateKeyResolver(CLIENT_KEYSTORE_PASSWORD, clientKeystore));
extension.registerServiceMock(CertificateResolver.class, new FsCertificateResolver(clientKeystore));
}
}
|
package pl.allegro.tech.hermes.integration.auth;
import avro.shaded.com.google.common.collect.Lists;
import com.google.common.io.Files;
import io.undertow.security.impl.BasicAuthenticationMechanism;
import io.undertow.util.StatusCodes;
import org.assertj.core.description.Description;
import org.assertj.core.description.TextDescription;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import pl.allegro.tech.hermes.api.Topic;
import pl.allegro.tech.hermes.common.config.ConfigFactory;
import pl.allegro.tech.hermes.common.config.Configs;
import pl.allegro.tech.hermes.frontend.HermesFrontend;
import pl.allegro.tech.hermes.frontend.server.auth.AuthenticationConfiguration;
import pl.allegro.tech.hermes.integration.IntegrationTest;
import pl.allegro.tech.hermes.test.helper.builder.TopicBuilder;
import pl.allegro.tech.hermes.test.helper.config.MutableConfigFactory;
import pl.allegro.tech.hermes.test.helper.endpoint.HermesPublisher;
import pl.allegro.tech.hermes.test.helper.message.TestMessage;
import pl.allegro.tech.hermes.test.helper.util.Ports;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
import static pl.allegro.tech.hermes.integration.auth.SingleUserAwareIdentityManager.getHeadersWithAuthentication;
import static pl.allegro.tech.hermes.integration.test.HermesAssertions.assertThat;
public class TopicAuthorisationTest extends IntegrationTest {
public static final int FRONTEND_PORT = Ports.nextAvailable();
public static final String FRONTEND_URL = "http://127.0.0.1:" + FRONTEND_PORT;
private static final String USERNAME = "someUser";
private static final String PASSWORD = "somePassword123";
private static final String MESSAGE = TestMessage.of("hello", "world").body();
private static final String USERNAME2 = "foobar";
protected HermesPublisher publisher;
private HermesFrontend hermesFrontend;
@BeforeClass
public void setup() throws Exception {
ConfigFactory configFactory = new MutableConfigFactory()
.overrideProperty(Configs.FRONTEND_PORT, FRONTEND_PORT)
.overrideProperty(Configs.FRONTEND_SSL_ENABLED, false)
.overrideProperty(Configs.FRONTEND_AUTHENTICATION_MODE, "pro_active")
.overrideProperty(Configs.FRONTEND_AUTHENTICATION_ENABLED, true)
.overrideProperty(Configs.MESSAGES_LOCAL_STORAGE_DIRECTORY, Files.createTempDir().getAbsolutePath());
AuthenticationConfiguration authConfig = new AuthenticationConfiguration(
exchange -> false,
Lists.newArrayList(new BasicAuthenticationMechanism("basicAuthRealm")),
new SingleUserAwareIdentityManager(USERNAME, PASSWORD));
hermesFrontend = HermesFrontend.frontend()
.withBinding(configFactory, ConfigFactory.class)
.withAuthenticationConfiguration(authConfig)
.build();
hermesFrontend.start();
publisher = new HermesPublisher(FRONTEND_URL);
operations.buildTopic("someGroup", "topicWithAuthorization");
}
@AfterClass
public void tearDown() throws InterruptedException {
hermesFrontend.stop();
}
@Test
public void shouldPublishWhenAuthenticated() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("disabled.authenticated")
.build(),
TopicBuilder.topic("enabled.authenticated_1Publisher")
.withPublisher(USERNAME)
.withAuthEnabled()
.build(),
TopicBuilder.topic("enabled.authenticated_2Publishers")
.withPublisher(USERNAME)
.withPublisher(USERNAME2)
.withAuthEnabled()
.build(),
TopicBuilder.topic("required.authenticated_1Publisher")
.withPublisher(USERNAME)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build(),
TopicBuilder.topic("required.authenticated_2Publishers")
.withPublisher(USERNAME)
.withPublisher(USERNAME2)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build()
);
topics.forEach(operations::buildTopic);
Map<String, String> headers = getHeadersWithAuthentication(USERNAME, PASSWORD);
topics.forEach(topic -> {
// when
Response response = publisher.publish(topic.getQualifiedName(), MESSAGE, headers);
// then
assertThat(response.getStatusInfo().getFamily()).as(description(topic)).isEqualTo(SUCCESSFUL);
});
}
@Test
public void shouldPublishAsGuestWhenAuthIsNotRequired() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("disabled.guest")
.build(),
TopicBuilder.topic("enabled.guest_0Publishers")
.withAuthEnabled()
.build(),
TopicBuilder.topic("enabled.guest_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.build()
);
topics.forEach(operations::buildTopic);
topics.forEach(topic -> {
// when
Response response = publisher.publish(topic.getQualifiedName(), MESSAGE);
// then
assertThat(response.getStatusInfo().getFamily()).as(description(topic)).isEqualTo(SUCCESSFUL);
});
}
@Test
public void shouldNotPublishAsGuestWhenAuthIsRequired() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("required.guest_0Publishers")
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build(),
TopicBuilder.topic("required.guest_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build()
);
topics.forEach(operations::buildTopic);
topics.forEach(topic -> {
// when
Response response = publisher.publish(topic.getQualifiedName(), MESSAGE);
// then
assertThat(response.getStatus()).as(description(topic)).isEqualTo(StatusCodes.FORBIDDEN);
});
}
@Test
public void shouldNotPublishWithoutPermissionWhenAuthenticated() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("enabled.authenticated_no_permission_0Publishers")
.withAuthEnabled()
.build(),
TopicBuilder.topic("enabled.authenticated_no_permission_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.build(),
TopicBuilder.topic("required.authenticated_no_permission_0Publishers")
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build(),
TopicBuilder.topic("required.authenticated_no_permission_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build()
);
topics.forEach(operations::buildTopic);
Map<String, String> headers = getHeadersWithAuthentication(USERNAME, PASSWORD);
topics.forEach(topic -> {
// when
Response response = publisher.publish(topic.getQualifiedName(), MESSAGE, headers);
// then
assertThat(response.getStatus()).as(description(topic)).isEqualTo(StatusCodes.FORBIDDEN);
});
}
private Description description(Topic topic) {
return new TextDescription("topic=%s", topic.getQualifiedName());
}
}
|
/*
* Copyright 2013, The Sporting Exchange Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// Originally from UpdatedComponentTests/StandardValidation/REST/Rest_Post_MissingMandatory_ListOfComplex_JSON.xls;
package com.betfair.cougar.tests.updatedcomponenttests.standardvalidation.rest;
import com.betfair.testing.utils.cougar.misc.XMLHelpers;
import com.betfair.testing.utils.cougar.assertions.AssertionUtils;
import com.betfair.testing.utils.cougar.beans.HttpCallBean;
import com.betfair.testing.utils.cougar.beans.HttpResponseBean;
import com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum;
import com.betfair.testing.utils.cougar.manager.AccessLogRequirement;
import com.betfair.testing.utils.cougar.manager.CougarManager;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
/**
* Ensure that the correct fault is returned when, a Rest(JSON) Post operation is performed against Cougar, passing a List of complex object in the post body, where the complex object contained in the list has a mandatory field missing
*/
public class RestPostMissingMandatoryListOfComplexJSONTest {
@Test
public void doTest() throws Exception {
// Set up the Http Call Bean to make the request
CougarManager cougarManager1 = CougarManager.getInstance();
HttpCallBean getNewHttpCallBean1 = cougarManager1.getNewHttpCallBean("87.248.113.14");
cougarManager1 = cougarManager1;
// Turn detailed faults off
cougarManager1.setCougarFaultControllerJMXMBeanAttrbiute("DetailedFaults", "false");
getNewHttpCallBean1.setOperationName("listOfComplexOperation");
getNewHttpCallBean1.setServiceName("baseline", "cougarBaseline");
getNewHttpCallBean1.setVersion("v2");
// Set the body param to a list of complex objects where one of the entries is missing mandatory fields
Map map2 = new HashMap();
map2.put("RESTJSON","{\"inputList\": [{\"ComplexObject\":{}}]}");
getNewHttpCallBean1.setPostQueryObjects(map2);
// Get current time for getting log entries later
Timestamp getTimeAsTimeStamp7 = new Timestamp(System.currentTimeMillis());
// Make REST JSON call to the operation requesting an XML response
cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTJSON, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.XML);
// Make REST JSON call to the operation requesting a JSON response
cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTJSON, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.JSON);
// Create the expected response as an XML document (Fault)
XMLHelpers xMLHelpers4 = new XMLHelpers();
Document createAsDocument12 = xMLHelpers4.getXMLObjectFromString("<fault><faultcode>Client</faultcode><faultstring>DSC-0018</faultstring><detail/></fault>");
// Convert the expected response to REST types for comparison with actual responses
Map<CougarMessageProtocolRequestTypeEnum, Object> convertResponseToRestTypes13 = cougarManager1.convertResponseToRestTypes(createAsDocument12, getNewHttpCallBean1);
// Check the 2 responses are as expected (Bad Request)
HttpResponseBean response5 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONXML);
AssertionUtils.multiAssertEquals(convertResponseToRestTypes13.get(CougarMessageProtocolRequestTypeEnum.RESTXML), response5.getResponseObject());
AssertionUtils.multiAssertEquals((int) 400, response5.getHttpStatusCode());
AssertionUtils.multiAssertEquals("Bad Request", response5.getHttpStatusText());
HttpResponseBean response6 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONJSON);
AssertionUtils.multiAssertEquals(convertResponseToRestTypes13.get(CougarMessageProtocolRequestTypeEnum.RESTJSON), response6.getResponseObject());
AssertionUtils.multiAssertEquals((int) 400, response6.getHttpStatusCode());
AssertionUtils.multiAssertEquals("Bad Request", response6.getHttpStatusText());
// generalHelpers.pauseTest(500L);
// Check the log entries are as expected
cougarManager1.verifyAccessLogEntriesAfterDate(getTimeAsTimeStamp7, new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/listOfComplexOperation", "BadRequest"),new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/listOfComplexOperation", "BadRequest") );
}
}
|
package com.tamsiree.rxkit;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author tamsiree
* @date 2016/1/24
*/
public class RxBarTool {
/**
* 隐藏状态栏
* <p>也就是设置全屏,一定要在setContentView之前调用,否则报错</p>
* <p>此方法Activity可以继承AppCompatActivity</p>
* <p>启动的时候状态栏会显示一下再隐藏,比如QQ的欢迎界面</p>
* <p>在配置文件中Activity加属性android:theme="@android:style/Theme.NoTitleBar.Fullscreen"</p>
* <p>如加了以上配置Activity不能继承AppCompatActivity,会报错</p>
*
* @param activity activity
*/
public static void hideStatusBar(Activity activity) {
noTitle(activity);
FLAG_FULLSCREEN(activity);
}
/**
* 设置透明状态栏(api大于19方可使用)
* <p>可在Activity的onCreat()中调用</p>
* <p>需在顶部控件布局中加入以下属性让内容出现在状态栏之下</p>
* <p>android:clipToPadding="true"</p>
* <p>android:fitsSystemWindows="true"</p>
*
* @param activity activity
*/
public static void setTransparentStatusBar(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明状态栏
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); //透明导航栏
}
}
/**
* 隐藏Title
* 一定要在setContentView之前调用,否则报错
*
* @param activity
*/
public static void setNoTitle(Activity activity) {
activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
public static void noTitle(Activity activity) {
setNoTitle(activity);
}
/**
* 全屏
* 也就是设置全屏,一定要在setContentView之前调用,否则报错
*
* @param activity
*/
public static void FLAG_FULLSCREEN(Activity activity) {
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
/**
* 获取状态栏高度
*
* @param context 上下文
* @return 状态栏高度
*/
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* 判断状态栏是否存在
*
* @param activity activity
* @return {@code true}: 存在<br>{@code false}: 不存在
*/
public static boolean isStatusBarExists(Activity activity) {
WindowManager.LayoutParams params = activity.getWindow().getAttributes();
return (params.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
/**
* 获取ActionBar高度
*
* @param activity activity
* @return ActionBar高度
*/
public static int getActionBarHeight(Activity activity) {
TypedValue tv = new TypedValue();
if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
return TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
}
return 0;
}
/**
* 显示通知栏
* <p>需添加权限 {@code <uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>}</p>
*
* @param context 上下文
* @param isSettingPanel {@code true}: 打开设置<br>{@code false}: 打开通知
*/
public static void showNotificationBar(Context context, boolean isSettingPanel) {
String methodName = (Build.VERSION.SDK_INT <= 16) ? "expand"
: (isSettingPanel ? "expandSettingsPanel" : "expandNotificationsPanel");
invokePanels(context, methodName);
}
/**
* 隐藏通知栏
* <p>需添加权限 {@code <uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>}</p>
*
* @param context 上下文
*/
public static void hideNotificationBar(Context context) {
String methodName = (Build.VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels";
invokePanels(context, methodName);
}
/**
* 反射唤醒通知栏
*
* @param context 上下文
* @param methodName 方法名
*/
private static void invokePanels(Context context, String methodName) {
try {
Object service = context.getSystemService("statusbar");
Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");
Method expand = statusBarManager.getMethod(methodName);
expand.invoke(service);
} catch (Exception e) {
e.printStackTrace();
}
}
//==============================================================================================以下设置状态栏相关
/**
* 需要在布局中加入
android:clipToPadding="true"
android:fitsSystemWindows="true"
* 这两行属性
*/
/**
* 修改状态栏为全透明
*
* @param activity
*/
@TargetApi(19)
public static void transparencyBar(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = activity.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
/**
* 修改状态栏颜色,支持4.4以上版本
*
* @param activity
* @param colorId
*/
public static void setStatusBarColor(Activity activity, int colorId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(activity.getResources().getColor(colorId));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//使用SystemBarTint库使4.4版本状态栏变色,需要先将状态栏设置为透明
transparencyBar(activity);
SystemBarTintManager tintManager = new SystemBarTintManager(activity);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(colorId);
}
}
/**
* 设置状态栏黑色字体图标,
* 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
*
* @param activity
* @return 1:MIUUI 2:Flyme 3:android6.0
*/
public static int StatusBarLightMode(Activity activity) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (MIUISetStatusBarLightMode(activity.getWindow(), true)) {
result = 1;
} else if (FlymeSetStatusBarLightMode(activity.getWindow(), true)) {
result = 2;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
result = 3;
}
}
return result;
}
/**
* 已知系统类型时,设置状态栏黑色字体图标。
* 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
*
* @param activity
* @param type 1:MIUUI 2:Flyme 3:android6.0
*/
public static void StatusBarLightMode(Activity activity, int type) {
if (type == 1) {
MIUISetStatusBarLightMode(activity.getWindow(), true);
} else if (type == 2) {
FlymeSetStatusBarLightMode(activity.getWindow(), true);
} else if (type == 3) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
/**
* 清除MIUI或flyme或6.0以上版本状态栏黑色字体
*/
public static void StatusBarDarkMode(Activity activity, int type) {
if (type == 1) {
MIUISetStatusBarLightMode(activity.getWindow(), false);
} else if (type == 2) {
FlymeSetStatusBarLightMode(activity.getWindow(), false);
} else if (type == 3) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
/**
* 设置状态栏图标为深色和魅族特定的文字风格
* 可以用来判断是否为Flyme用户
*
* @param window 需要设置的窗口
* @param dark 是否把状态栏字体及图标颜色设置为深色
* @return boolean 成功执行返回true
*/
public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
boolean result = false;
if (window != null) {
try {
WindowManager.LayoutParams lp = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class
.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(lp);
if (dark) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(lp, value);
window.setAttributes(lp);
result = true;
} catch (Exception e) {
}
}
return result;
}
/**
* 设置状态栏字体图标为深色,需要MIUIV6以上
*
* @param window 需要设置的窗口
* @param dark 是否把状态栏字体及图标颜色设置为深色
* @return boolean 成功执行返回true
*/
public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
boolean result = false;
if (window != null) {
Class clazz = window.getClass();
try {
int darkModeFlag = 0;
Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
if (dark) {
extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
} else {
extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
}
result = true;
} catch (Exception e) {
}
}
return result;
}
//==============================================================================================以上为设置状态栏相关
}
|
/*
* Copyright (C) 2010-2021 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.provisioning.impl.shadows;
import static com.evolveum.midpoint.util.MiscUtil.stateCheck;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.schema.processor.ShadowCoordinatesQualifiedObjectDelta;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.PropertyValueFilter;
import com.evolveum.midpoint.provisioning.impl.ProvisioningContext;
import com.evolveum.midpoint.provisioning.impl.ProvisioningContextFactory;
import com.evolveum.midpoint.provisioning.impl.ShadowCaretaker;
import com.evolveum.midpoint.provisioning.impl.shadows.manager.ShadowManager;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.ResourceShadowCoordinates;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.annotation.Experimental;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
/**
* Implements various methods of `applyDefinition` kind.
*/
@Experimental
@Component
class DefinitionsHelper {
@Autowired
@Qualifier("cacheRepositoryService")
private RepositoryService repositoryService;
@Autowired private ShadowCaretaker shadowCaretaker;
@Autowired protected ShadowManager shadowManager;
@Autowired private ProvisioningContextFactory ctxFactory;
public void applyDefinition(ObjectDelta<ShadowType> delta, @Nullable ShadowType repoShadow,
Task task, OperationResult result) throws SchemaException, ObjectNotFoundException,
CommunicationException, ConfigurationException, ExpressionEvaluationException {
PrismObject<ShadowType> shadow = null;
ResourceShadowCoordinates coordinates = null;
if (delta.isAdd()) {
shadow = delta.getObjectToAdd();
} else if (delta.isModify()) {
if (delta instanceof ShadowCoordinatesQualifiedObjectDelta) {
// This one does not have OID, it has to be specially processed
coordinates = ((ShadowCoordinatesQualifiedObjectDelta<?>) delta).getCoordinates();
} else {
String shadowOid = delta.getOid();
if (shadowOid == null) {
if (repoShadow == null) {
throw new IllegalArgumentException("No OID in object delta " + delta
+ " and no externally-supplied shadow is present as well.");
}
shadow = repoShadow.asPrismObject();
} else {
// TODO consider fetching only when really necessary
shadow = repositoryService.getObject(delta.getObjectTypeClass(), shadowOid, null, result);
}
}
} else {
// Delete delta, nothing to do at all
return;
}
ProvisioningContext ctx;
if (shadow == null) {
stateCheck(coordinates != null, "No shadow nor coordinates");
ctx = ctxFactory.createForCoordinates(coordinates, task, result);
} else {
ctx = ctxFactory.createForShadow(shadow, task, result);
}
shadowCaretaker.applyAttributesDefinition(ctx, delta);
}
public void applyDefinition(PrismObject<ShadowType> shadow, Task task, OperationResult parentResult)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
ExpressionEvaluationException {
ProvisioningContext ctx = ctxFactory.createForShadow(shadow, task, parentResult);
shadowCaretaker.applyAttributesDefinition(ctx, shadow);
}
public void applyDefinition(ObjectQuery query, Task task, OperationResult result)
throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException,
ExpressionEvaluationException {
ProvisioningContext ctx = ctxFactory.createForCoordinates(
ObjectQueryUtil.getCoordinates(query.getFilter()),
task, result);
applyDefinition(ctx, query);
}
void applyDefinition(ProvisioningContext ctx, ObjectQuery query)
throws SchemaException {
if (query == null) {
return;
}
ObjectFilter filter = query.getFilter();
if (filter == null) {
return;
}
com.evolveum.midpoint.prism.query.Visitor visitor = subFilter -> {
if (subFilter instanceof PropertyValueFilter) {
PropertyValueFilter<?> valueFilter = (PropertyValueFilter<?>) subFilter;
ItemDefinition<?> definition = valueFilter.getDefinition();
if (definition instanceof ResourceAttributeDefinition) {
return; // already has a resource-related definition
}
if (!ShadowType.F_ATTRIBUTES.equivalent(valueFilter.getParentPath())) {
return;
}
QName attributeName = valueFilter.getElementName();
ResourceAttributeDefinition<?> attributeDefinition =
ctx.getObjectDefinitionRequired().findAttributeDefinition(attributeName);
if (attributeDefinition == null) {
throw new TunnelException(
new SchemaException("No definition for attribute " + attributeName + " in query " + query));
}
//noinspection unchecked,rawtypes
valueFilter.setDefinition((ResourceAttributeDefinition) attributeDefinition);
}
};
try {
filter.accept(visitor);
} catch (TunnelException te) {
throw (SchemaException) te.getCause();
}
}
}
|
package Chapter03.P74_CalculatingAge.src.modern.challenge;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
System.out.println("Before JDK 8:");
Calendar startDate = Calendar.getInstance();
startDate.set(1977, 10, 2);
Calendar endDate = Calendar.getInstance();
endDate.setTime(new Date());
int yearsc = endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR);
if (yearsc > 0) {
if (startDate.get(Calendar.MONTH) > endDate.get(Calendar.MONTH)
|| (startDate.get(Calendar.MONTH) == endDate.get(Calendar.MONTH)
&& startDate.get(Calendar.DAY_OF_MONTH) > endDate.get(Calendar.DAY_OF_MONTH))) {
yearsc--;
}
}
System.out.println(yearsc + "y");
System.out.println("\nStarting with JDK 8");
LocalDate startLocalDate = LocalDate.of(1977, 11, 2);
LocalDate endLocalDate = LocalDate.now();
long years = ChronoUnit.YEARS.between(startLocalDate, endLocalDate);
System.out.println(years + "y ");
Period periodBetween = Period.between(startLocalDate, endLocalDate);
System.out.println(periodBetween.getYears() + "y "
+ periodBetween.getMonths() + "m "
+ periodBetween.getDays() + "d");
}
}
|
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
public class Consumer implements Runnable {
private List<String> buffer;
private String color;
private ReentrantLock queue;
public Consumer(List<String> buffer, String color,ReentrantLock queue){
this.buffer = buffer;
this.color = color;
this.queue = queue;
}
@Override
public void run(){
while (true){
queue.lock();
try{
if (buffer.isEmpty())
continue;
if (buffer.get(0).equals("EOF")) {
System.out.println(color + "Exiting...");
break;
}
else
System.out.println(color + "Removed " + buffer.remove(0));
} finally{
queue.unlock();
}
}
}
}
|
package egree4j.http;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.NameValuePair;
/**
* Class that unwraps a map into usable lists to be sent as request headers
* or URL parameters in a GET or POST.
*
* @author Johan
*
*/
public class RequestParameterMapper {
/**
* Unwraps the given Map of key-value pairs into an array of NameValuePairs
* that can be sent in a GET or POST.
*
* @param map Map with key value pairs.
* @return Array of parameters extracted from the map.
*/
public static NameValuePair[] unwrap(Map<String, String> map) {
if (map == null) {
return new NameValuePair[0];
}
NameValuePair[] parameters = new NameValuePair[map.size()];
int idx = 0;
Iterator<Entry<String, String>> values = map.entrySet().iterator();
while (values.hasNext()) {
Entry<String, String> value = values.next();
parameters[idx++] = new RequestParameter(
value.getKey(), value.getValue());
}
return parameters;
}
}
|
// Copyright 2018 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.rules.cpp;
import static com.google.devtools.build.lib.packages.BuildType.NODEP_LABEL;
import static com.google.devtools.build.lib.packages.Type.BOOLEAN;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.Actions;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.Allowlist;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.LicensesProvider;
import com.google.devtools.build.lib.analysis.LicensesProvider.TargetLicense;
import com.google.devtools.build.lib.analysis.LicensesProviderImpl;
import com.google.devtools.build.lib.analysis.MiddlemanProvider;
import com.google.devtools.build.lib.analysis.PackageSpecificationProvider;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitionMode;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.platform.ToolchainInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.License;
import com.google.devtools.build.lib.packages.NativeProvider;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.rules.cpp.CcToolchain.AdditionalBuildVariablesComputer;
import com.google.devtools.build.lib.syntax.Location;
/**
* Provider encapsulating all the information from the cc_toolchain rule that affects creation of
* {@link CcToolchainProvider}
*/
public class CcToolchainAttributesProvider extends ToolchainInfo implements HasCcToolchainLabel {
public static final NativeProvider<CcToolchainAttributesProvider> PROVIDER =
new NativeProvider<CcToolchainAttributesProvider>(
CcToolchainAttributesProvider.class, "CcToolchainAttributesInfo") {};
private final boolean supportsParamFiles;
private final boolean supportsHeaderParsing;
private final NestedSet<Artifact> allFiles;
private final NestedSet<Artifact> allFilesMiddleman;
private final NestedSet<Artifact> compilerFiles;
private final NestedSet<Artifact> compilerFilesWithoutIncludes;
private final NestedSet<Artifact> stripFiles;
private final NestedSet<Artifact> objcopyFiles;
private final NestedSet<Artifact> asFiles;
private final NestedSet<Artifact> arFiles;
private final NestedSet<Artifact> linkerFiles;
private final NestedSet<Artifact> dwpFiles;
private final Label libcTopAttribute;
private final NestedSet<Artifact> libc;
private final NestedSet<Artifact> libcMiddleman;
private final TransitiveInfoCollection libcTop;
private final NestedSet<Artifact> targetLibc;
private final NestedSet<Artifact> targetLibcMiddleman;
private final TransitiveInfoCollection targetLibcTop;
private final NestedSet<Artifact> fullInputsForCrosstool;
private final NestedSet<Artifact> fullInputsForLink;
private final NestedSet<Artifact> coverage;
private final String compiler;
private final String cpu;
private final Artifact ifsoBuilder;
private final Artifact linkDynamicLibraryTool;
private final TransitiveInfoCollection fdoOptimize;
private final ImmutableList<Artifact> fdoOptimizeArtifacts;
private final FdoPrefetchHintsProvider fdoPrefetch;
private final TransitiveInfoCollection moduleMap;
private final Artifact moduleMapArtifact;
private final Artifact zipper;
private final String purposePrefix;
private final String runtimeSolibDirBase;
private final LicensesProvider licensesProvider;
private final Label toolchainType;
private final AdditionalBuildVariablesComputer additionalBuildVariablesComputer;
private final CcToolchainConfigInfo ccToolchainConfigInfo;
private final String toolchainIdentifier;
private final FdoProfileProvider fdoOptimizeProvider;
private final FdoProfileProvider fdoProfileProvider;
private final FdoProfileProvider csFdoProfileProvider;
private final FdoProfileProvider xfdoProfileProvider;
private final Label ccToolchainLabel;
private final TransitiveInfoCollection staticRuntimeLib;
private final TransitiveInfoCollection dynamicRuntimeLib;
private final PackageSpecificationProvider allowlistForLayeringCheck;
public CcToolchainAttributesProvider(
RuleContext ruleContext,
boolean isAppleToolchain,
AdditionalBuildVariablesComputer additionalBuildVariablesComputer) {
super(ImmutableMap.of(), Location.BUILTIN);
this.ccToolchainLabel = ruleContext.getLabel();
this.toolchainIdentifier = ruleContext.attributes().get("toolchain_identifier", Type.STRING);
if (ruleContext.getFragment(CppConfiguration.class).removeCpuCompilerCcToolchainAttributes()
&& (ruleContext.attributes().isAttributeValueExplicitlySpecified("cpu")
|| ruleContext.attributes().isAttributeValueExplicitlySpecified("compiler"))) {
ruleContext.ruleError(
"attributes 'cpu' and 'compiler' have been deprecated, please remove them. See "
+ "https://github.com/bazelbuild/bazel/issues/7075 for details.");
}
this.cpu = ruleContext.attributes().get("cpu", Type.STRING);
this.compiler = ruleContext.attributes().get("compiler", Type.STRING);
this.supportsParamFiles = ruleContext.attributes().get("supports_param_files", BOOLEAN);
this.supportsHeaderParsing = ruleContext.attributes().get("supports_header_parsing", BOOLEAN);
this.allFiles =
ruleContext
.getPrerequisite("all_files", TransitionMode.HOST)
.getProvider(FileProvider.class)
.getFilesToBuild();
this.allFilesMiddleman = getMiddlemanOrFiles(ruleContext, "all_files");
this.compilerFiles = getMiddlemanOrFiles(ruleContext, "compiler_files");
this.compilerFilesWithoutIncludes =
getOptionalMiddlemanOrFiles(ruleContext, "compiler_files_without_includes");
this.stripFiles = getMiddlemanOrFiles(ruleContext, "strip_files");
this.objcopyFiles = getMiddlemanOrFiles(ruleContext, "objcopy_files");
this.asFiles = getOptionalMiddlemanOrFiles(ruleContext, "as_files");
this.arFiles = getOptionalMiddlemanOrFiles(ruleContext, "ar_files");
this.linkerFiles = getMiddlemanOrFiles(ruleContext, "linker_files");
this.dwpFiles = getMiddlemanOrFiles(ruleContext, "dwp_files");
this.libcMiddleman =
getOptionalMiddlemanOrFiles(
ruleContext, CcToolchainRule.LIBC_TOP_ATTR, TransitionMode.TARGET);
this.libc = getOptionalFiles(ruleContext, CcToolchainRule.LIBC_TOP_ATTR, TransitionMode.TARGET);
this.libcTop =
ruleContext.getPrerequisite(CcToolchainRule.LIBC_TOP_ATTR, TransitionMode.TARGET);
this.targetLibcMiddleman =
getOptionalMiddlemanOrFiles(
ruleContext, CcToolchainRule.TARGET_LIBC_TOP_ATTR, TransitionMode.TARGET);
this.targetLibc =
getOptionalFiles(ruleContext, CcToolchainRule.TARGET_LIBC_TOP_ATTR, TransitionMode.TARGET);
this.targetLibcTop =
ruleContext.getPrerequisite(CcToolchainRule.TARGET_LIBC_TOP_ATTR, TransitionMode.TARGET);
this.libcTopAttribute = ruleContext.attributes().get("libc_top", BuildType.LABEL);
this.fullInputsForCrosstool =
NestedSetBuilder.<Artifact>stableOrder()
.addTransitive(allFilesMiddleman)
.addTransitive(libcMiddleman)
.build();
this.fullInputsForLink =
fullInputsForLink(ruleContext, linkerFiles, libcMiddleman, isAppleToolchain);
NestedSet<Artifact> coverageFiles = getOptionalMiddlemanOrFiles(ruleContext, "coverage_files");
if (coverageFiles.isEmpty()) {
this.coverage = Preconditions.checkNotNull(this.allFiles);
} else {
this.coverage = coverageFiles;
}
this.ifsoBuilder =
ruleContext.getPrerequisiteArtifact("$interface_library_builder", TransitionMode.HOST);
this.linkDynamicLibraryTool =
ruleContext.getPrerequisiteArtifact("$link_dynamic_library_tool", TransitionMode.HOST);
this.fdoProfileProvider =
ruleContext.getPrerequisite(
CcToolchainRule.FDO_PROFILE_ATTR, TransitionMode.TARGET, FdoProfileProvider.PROVIDER);
this.csFdoProfileProvider =
ruleContext.getPrerequisite(
CcToolchainRule.CSFDO_PROFILE_ATTR, TransitionMode.TARGET, FdoProfileProvider.PROVIDER);
this.xfdoProfileProvider =
ruleContext.getPrerequisite(
CcToolchainRule.XFDO_PROFILE_ATTR, TransitionMode.TARGET, FdoProfileProvider.PROVIDER);
this.fdoOptimizeProvider =
ruleContext.getPrerequisite(
CcToolchainRule.FDO_OPTIMIZE_ATTR, TransitionMode.TARGET, FdoProfileProvider.PROVIDER);
this.fdoOptimize =
ruleContext.getPrerequisite(CcToolchainRule.FDO_OPTIMIZE_ATTR, TransitionMode.TARGET);
this.fdoOptimizeArtifacts =
ruleContext
.getPrerequisiteArtifacts(CcToolchainRule.FDO_OPTIMIZE_ATTR, TransitionMode.TARGET)
.list();
this.fdoPrefetch =
ruleContext.getPrerequisite(
":fdo_prefetch_hints", TransitionMode.TARGET, FdoPrefetchHintsProvider.PROVIDER);
this.moduleMap = ruleContext.getPrerequisite("module_map", TransitionMode.HOST);
this.moduleMapArtifact = ruleContext.getPrerequisiteArtifact("module_map", TransitionMode.HOST);
this.zipper = ruleContext.getPrerequisiteArtifact(":zipper", TransitionMode.HOST);
this.purposePrefix = Actions.escapeLabel(ruleContext.getLabel()) + "_";
this.runtimeSolibDirBase = "_solib_" + "_" + Actions.escapeLabel(ruleContext.getLabel());
this.staticRuntimeLib =
ruleContext.getPrerequisite("static_runtime_lib", TransitionMode.TARGET);
this.dynamicRuntimeLib =
ruleContext.getPrerequisite("dynamic_runtime_lib", TransitionMode.TARGET);
this.ccToolchainConfigInfo =
ruleContext.getPrerequisite(
CcToolchainRule.TOOLCHAIN_CONFIG_ATTR,
TransitionMode.TARGET,
CcToolchainConfigInfo.PROVIDER);
// If output_license is specified on the cc_toolchain rule, override the transitive licenses
// with that one. This is necessary because cc_toolchain is used in the target configuration,
// but it is sort-of-kind-of a tool, but various parts of it are linked into the output...
// ...so we trust the judgment of the author of the cc_toolchain rule to figure out what
// licenses should be propagated to C++ targets.
// TODO(elenairina): Remove this and use Attribute.Builder.useOutputLicenses() on the
// :cc_toolchain attribute instead.
final License outputLicense =
ruleContext.getRule().getToolOutputLicense(ruleContext.attributes());
if (outputLicense != null && !outputLicense.equals(License.NO_LICENSE)) {
final NestedSet<TargetLicense> license =
NestedSetBuilder.create(
Order.STABLE_ORDER, new TargetLicense(ruleContext.getLabel(), outputLicense));
this.licensesProvider =
new LicensesProviderImpl(
license, new TargetLicense(ruleContext.getLabel(), outputLicense));
} else {
this.licensesProvider = null;
}
// TODO(b/65835260): Remove this conditional once j2objc can learn the toolchain type.
if (ruleContext.attributes().has(CcToolchain.CC_TOOLCHAIN_TYPE_ATTRIBUTE_NAME)) {
this.toolchainType =
ruleContext.attributes().get(CcToolchain.CC_TOOLCHAIN_TYPE_ATTRIBUTE_NAME, NODEP_LABEL);
} else {
this.toolchainType = null;
}
this.additionalBuildVariablesComputer = additionalBuildVariablesComputer;
this.allowlistForLayeringCheck =
Allowlist.fetchPackageSpecificationProvider(
ruleContext, CcToolchain.ALLOWED_LAYERING_CHECK_FEATURES_ALLOWLIST);
}
public String getCpu() {
return cpu;
}
public boolean isSupportsParamFiles() {
return supportsParamFiles;
}
public String getPurposePrefix() {
return purposePrefix;
}
public String getRuntimeSolibDirBase() {
return runtimeSolibDirBase;
}
public FdoPrefetchHintsProvider getFdoPrefetch() {
return fdoPrefetch;
}
public String getToolchainIdentifier() {
return toolchainIdentifier;
}
public Label getToolchainType() {
return toolchainType;
}
public CcToolchainConfigInfo getCcToolchainConfigInfo() {
return ccToolchainConfigInfo;
}
public ImmutableList<Artifact> getFdoOptimizeArtifacts() {
return fdoOptimizeArtifacts;
}
public LicensesProvider getLicensesProvider() {
return licensesProvider;
}
public TransitiveInfoCollection getStaticRuntimeLib() {
return staticRuntimeLib;
}
public TransitiveInfoCollection getDynamicRuntimeLib() {
return dynamicRuntimeLib;
}
public boolean isSupportsHeaderParsing() {
return supportsHeaderParsing;
}
public AdditionalBuildVariablesComputer getAdditionalBuildVariablesComputer() {
return additionalBuildVariablesComputer;
}
public NestedSet<Artifact> getAllFiles() {
return allFiles;
}
public NestedSet<Artifact> getAllFilesMiddleman() {
return allFilesMiddleman;
}
public NestedSet<Artifact> getCompilerFiles() {
return compilerFiles;
}
public NestedSet<Artifact> getStripFiles() {
return stripFiles;
}
public NestedSet<Artifact> getObjcopyFiles() {
return objcopyFiles;
}
public TransitiveInfoCollection getFdoOptimize() {
return fdoOptimize;
}
public Artifact getLinkDynamicLibraryTool() {
return linkDynamicLibraryTool;
}
public TransitiveInfoCollection getModuleMap() {
return moduleMap;
}
public NestedSet<Artifact> getAsFiles() {
return asFiles;
}
public NestedSet<Artifact> getArFiles() {
return arFiles;
}
public TransitiveInfoCollection getLibcTop() {
return libcTop;
}
public NestedSet<Artifact> getLinkerFiles() {
return linkerFiles;
}
public NestedSet<Artifact> getDwpFiles() {
return dwpFiles;
}
public FdoProfileProvider getFdoOptimizeProvider() {
return fdoOptimizeProvider;
}
public Artifact getModuleMapArtifact() {
return moduleMapArtifact;
}
public NestedSet<Artifact> getFullInputsForCrosstool() {
return fullInputsForCrosstool;
}
public FdoProfileProvider getFdoProfileProvider() {
return fdoProfileProvider;
}
public FdoProfileProvider getCSFdoProfileProvider() {
return csFdoProfileProvider;
}
public FdoProfileProvider getXFdoProfileProvider() {
return xfdoProfileProvider;
}
public Artifact getZipper() {
return zipper;
}
public NestedSet<Artifact> getFullInputsForLink() {
return fullInputsForLink;
}
public Label getCcToolchainLabel() {
return ccToolchainLabel;
}
public NestedSet<Artifact> getCoverage() {
return coverage;
}
public NestedSet<Artifact> getCompilerFilesWithoutIncludes() {
return compilerFilesWithoutIncludes;
}
public NestedSet<Artifact> getLibc() {
return libc;
}
public NestedSet<Artifact> getTargetLibc() {
return targetLibc;
}
public TransitiveInfoCollection getTargetLibcTop() {
return targetLibcTop;
}
public Label getLibcTopLabel() {
return getLibcTop() == null ? null : getLibcTop().getLabel();
}
public Label getTargetLibcTopLabel() {
return getTargetLibcTop() == null ? null : getTargetLibcTop().getLabel();
}
public Label getLibcTopAttribute() {
return libcTopAttribute;
}
public String getCompiler() {
return compiler;
}
public Artifact getIfsoBuilder() {
return ifsoBuilder;
}
public PackageSpecificationProvider getAllowlistForLayeringCheck() {
return allowlistForLayeringCheck;
}
private static NestedSet<Artifact> getMiddlemanOrFiles(RuleContext context, String attribute) {
return getMiddlemanOrFiles(context, attribute, TransitionMode.HOST);
}
private static NestedSet<Artifact> getMiddlemanOrFiles(
RuleContext context, String attribute, TransitionMode mode) {
TransitiveInfoCollection dep = context.getPrerequisite(attribute, mode);
MiddlemanProvider middlemanProvider = dep.getProvider(MiddlemanProvider.class);
// We use the middleman if we can (if the dep is a filegroup), otherwise, just the regular
// filesToBuild (e.g. if it is a simple input file)
return middlemanProvider != null
? middlemanProvider.getMiddlemanArtifact()
: dep.getProvider(FileProvider.class).getFilesToBuild();
}
private static NestedSet<Artifact> getOptionalMiddlemanOrFiles(
RuleContext context, String attribute) {
return getOptionalMiddlemanOrFiles(context, attribute, TransitionMode.HOST);
}
private static NestedSet<Artifact> getOptionalMiddlemanOrFiles(
RuleContext context, String attribute, TransitionMode mode) {
TransitiveInfoCollection dep = context.getPrerequisite(attribute, mode);
return dep != null
? getMiddlemanOrFiles(context, attribute, mode)
: NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
private static NestedSet<Artifact> getOptionalFiles(
RuleContext ruleContext, String attribute, TransitionMode mode) {
TransitiveInfoCollection dep = ruleContext.getPrerequisite(attribute, mode);
return dep != null
? dep.getProvider(FileProvider.class).getFilesToBuild()
: NestedSetBuilder.emptySet(Order.STABLE_ORDER);
}
/**
* Returns the allFiles-derived link action inputs for a given rule. Adds the given set of
* artifacts as extra inputs.
*/
private static NestedSet<Artifact> fullInputsForLink(
RuleContext ruleContext,
NestedSet<Artifact> link,
NestedSet<Artifact> libcMiddleman,
boolean isAppleToolchain) {
NestedSetBuilder<Artifact> builder =
NestedSetBuilder.<Artifact>stableOrder().addTransitive(link).addTransitive(libcMiddleman);
if (!isAppleToolchain) {
builder
.add(
ruleContext.getPrerequisiteArtifact(
"$interface_library_builder", TransitionMode.HOST))
.add(
ruleContext.getPrerequisiteArtifact(
"$link_dynamic_library_tool", TransitionMode.HOST));
}
return builder.build();
}
}
/**
* Temporary interface to cover common interface of {@link CcToolchainAttributesProvider} and {@link
* CcToolchainProvider}.
*/
// TODO(b/113849758): Remove once behavior is migrated.
interface HasCcToolchainLabel {
Label getCcToolchainLabel();
}
|
package com.mine.violet.controller.front;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mine.violet.commonutils.R;
import com.mine.violet.entity.Blog;
import com.mine.violet.entity.vo.BlogQuery;
import com.mine.violet.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/adminservice/front/blog")
public class FrontBlogController {
@Autowired
private BlogService blogService; //博客
@PostMapping("/updateViews/{id}")
public R updateViews(@PathVariable String id){
Blog blog = blogService.getById(id);
blog.setViews(blog.getViews()+1);
blogService.updateById(blog);
return R.ok();
}
//1 前台分页查询博客
@GetMapping("/pageList/{current}/{limit}")
public R pageList(@PathVariable long current, @PathVariable long limit){
// 创建page对象
Page<Blog> blogPage = new Page<>(current,limit);
//构建条件
QueryWrapper<Blog> wrapper = new QueryWrapper<>();
//排序
wrapper.orderByDesc("gmt_create");
blogService.page(blogPage,wrapper);
long total = blogPage.getTotal(); //总记录数
List<Blog> records = blogPage.getRecords();
Map map = new HashMap<>();
map.put("total",total);
map.put("rows",records);
return R.ok().data(map);
}
//2 根据id查询博客内容
@GetMapping("/getBlogById/{id}")
public R getBlogById(@PathVariable String id){
Blog blog = blogService.getById(id);
return R.ok().data("blog",blog);
}
//3 前台查询作者自己的博客
@PostMapping("/pageListById/{current}/{limit}/{id}")
public R pageListById(@PathVariable long current, @PathVariable long limit,
@PathVariable String id,
@RequestBody(required = false) BlogQuery blogQuery){
// 创建page对象
Page<Blog> blogPage = new Page<>(current,limit);
//构建条件
QueryWrapper<Blog> wrapper = new QueryWrapper<>();
String title = blogQuery.getTitle();
String status = blogQuery.getStatus();
if(!StringUtils.isEmpty(title)){
// 构建条件
wrapper.like("title",title);
}
if(!StringUtils.isEmpty(status)){
// 构建条件
wrapper.eq("status",status);
}
wrapper.eq("author_id",id);
//排序
wrapper.orderByDesc("gmt_create");
blogService.page(blogPage,wrapper);
long total = blogPage.getTotal(); //总记录数
List<Blog> records = blogPage.getRecords();
Map map = new HashMap<>();
map.put("total",total);
map.put("rows",records);
System.out.println("=========");
System.out.println(id);
System.out.println(map);
return R.ok().data(map);
}
//4 根据博客id删除博客
@DeleteMapping("/{blogId}")
public R deleteBlog(@PathVariable String blogId){
blogService.removeById(blogId);
return R.ok();
}
}
|
/*
* Licensed to the Hipparchus project under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The Hipparchus project licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.hipparchus.ode.nonstiff;
import org.hipparchus.ode.EquationsMapper;
import org.hipparchus.ode.ODEStateAndDerivative;
/**
* This class implements the 3/8 fourth order Runge-Kutta
* integrator for Ordinary Differential Equations.
*
* <p>This method is an explicit Runge-Kutta method, its Butcher-array
* is the following one :
* <pre>
* 0 | 0 0 0 0
* 1/3 | 1/3 0 0 0
* 2/3 |-1/3 1 0 0
* 1 | 1 -1 1 0
* |--------------------
* | 1/8 3/8 3/8 1/8
* </pre>
* </p>
*
* @see EulerIntegrator
* @see ClassicalRungeKuttaIntegrator
* @see GillIntegrator
* @see MidpointIntegrator
* @see LutherIntegrator
*/
public class ThreeEighthesIntegrator extends RungeKuttaIntegrator {
/** Simple constructor.
* Build a 3/8 integrator with the given step.
* @param step integration step
*/
public ThreeEighthesIntegrator(final double step) {
super("3/8", step);
}
/** {@inheritDoc} */
@Override
public double[] getC() {
return new double[] {
1.0 / 3.0, 2.0 / 3.0, 1.0
};
}
/** {@inheritDoc} */
@Override
public double[][] getA() {
return new double[][] {
{ 1.0 / 3.0 },
{ -1.0 / 3.0, 1.0 },
{ 1.0, -1.0, 1.0 }
};
}
/** {@inheritDoc} */
@Override
public double[] getB() {
return new double[] {
1.0 / 8.0, 3.0 / 8.0, 3.0 / 8.0, 1.0 / 8.0
};
}
/** {@inheritDoc} */
@Override
protected ThreeEighthesStateInterpolator
createInterpolator(final boolean forward, double[][] yDotK,
final ODEStateAndDerivative globalPreviousState,
final ODEStateAndDerivative globalCurrentState,
final EquationsMapper mapper) {
return new ThreeEighthesStateInterpolator(forward, yDotK,
globalPreviousState, globalCurrentState,
globalPreviousState, globalCurrentState,
mapper);
}
}
|
/**
* 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.oozie.local;
import org.apache.oozie.CoordinatorEngine;
import org.apache.oozie.DagEngine;
import org.apache.oozie.LocalOozieClient;
import org.apache.oozie.LocalOozieClientCoord;
import org.apache.oozie.client.OozieClient;
import org.apache.oozie.service.CallbackService;
import org.apache.oozie.service.CoordinatorEngineService;
import org.apache.oozie.service.DagEngineService;
import org.apache.oozie.service.Services;
import org.apache.oozie.service.XLogService;
import org.apache.oozie.servlet.CallbackServlet;
import org.apache.oozie.test.EmbeddedServletContainer;
import org.apache.oozie.util.ParamChecker;
import org.apache.oozie.util.XLog;
/**
* LocalOozie runs workflows in an embedded Oozie instance . <p/> LocalOozie is meant for development/debugging purposes
* only.
*/
public class LocalOozie {
private static EmbeddedServletContainer container;
private static boolean localOozieActive = false;
/**
* Start LocalOozie.
*
* @throws Exception if LocalOozie could not be started.
*/
public synchronized static void start() throws Exception {
if (localOozieActive) {
throw new IllegalStateException("LocalOozie is already initialized");
}
String log4jFile = System.getProperty(XLogService.LOG4J_FILE, null);
String oozieLocalLog = System.getProperty("oozielocal.log", null);
if (log4jFile == null) {
System.setProperty(XLogService.LOG4J_FILE, "localoozie-log4j.properties");
}
if (oozieLocalLog == null) {
System.setProperty("oozielocal.log", "./oozielocal.log");
}
localOozieActive = true;
new Services().init();
if (log4jFile != null) {
System.setProperty(XLogService.LOG4J_FILE, log4jFile);
}
else {
System.getProperties().remove(XLogService.LOG4J_FILE);
}
if (oozieLocalLog != null) {
System.setProperty("oozielocal.log", oozieLocalLog);
}
else {
System.getProperties().remove("oozielocal.log");
}
container = new EmbeddedServletContainer("oozie");
container.addServletEndpoint("/callback", CallbackServlet.class);
container.start();
String callbackUrl = container.getServletURL("/callback");
Services.get().getConf().set(CallbackService.CONF_BASE_URL, callbackUrl);
XLog.getLog(LocalOozie.class).info("LocalOozie started callback set to [{0}]", callbackUrl);
}
/**
* Stop LocalOozie.
*/
public synchronized static void stop() {
RuntimeException thrown = null;
try {
if (container != null) {
container.stop();
}
}
catch (RuntimeException ex) {
thrown = ex;
}
container = null;
XLog.getLog(LocalOozie.class).info("LocalOozie stopped");
try {
Services.get().destroy();
}
catch (RuntimeException ex) {
if (thrown != null) {
thrown = ex;
}
}
localOozieActive = false;
if (thrown != null) {
throw thrown;
}
}
/**
* Return a {@link org.apache.oozie.client.OozieClient} for LocalOozie. <p/> The returned instance is configured
* with the user name of the JVM (the value of the system property 'user.name'). <p/> The following methods of the
* client are NOP in the returned instance: {@link org.apache.oozie.client.OozieClient#validateWSVersion}, {@link
* org.apache.oozie.client.OozieClient#setHeader}, {@link org.apache.oozie.client.OozieClient#getHeader}, {@link
* org.apache.oozie.client.OozieClient#removeHeader}, {@link org.apache.oozie.client.OozieClient#getHeaderNames} and
* {@link org.apache.oozie.client.OozieClient#setSafeMode}.
*
* @return a {@link org.apache.oozie.client.OozieClient} for LocalOozie.
*/
public static OozieClient getClient() {
return getClient(System.getProperty("user.name"));
}
/**
* Return a {@link org.apache.oozie.client.OozieClient} for LocalOozie.
* <p/>
* The returned instance is configured with the user name of the JVM (the
* value of the system property 'user.name').
* <p/>
* The following methods of the client are NOP in the returned instance:
* {@link org.apache.oozie.client.OozieClient#validateWSVersion},
* {@link org.apache.oozie.client.OozieClient#setHeader},
* {@link org.apache.oozie.client.OozieClient#getHeader},
* {@link org.apache.oozie.client.OozieClient#removeHeader},
* {@link org.apache.oozie.client.OozieClient#getHeaderNames} and
* {@link org.apache.oozie.client.OozieClient#setSafeMode}.
*
* @return a {@link org.apache.oozie.client.OozieClient} for LocalOozie.
*/
public static OozieClient getCoordClient() {
return getClientCoord(System.getProperty("user.name"));
}
/**
* Return a {@link org.apache.oozie.client.OozieClient} for LocalOozie configured for a given user.
* <p/>
* The following methods of the client are NOP in the returned instance: {@link org.apache.oozie.client.OozieClient#validateWSVersion},
* {@link org.apache.oozie.client.OozieClient#setHeader}, {@link org.apache.oozie.client.OozieClient#getHeader}, {@link org.apache.oozie.client.OozieClient#removeHeader},
* {@link org.apache.oozie.client.OozieClient#getHeaderNames} and {@link org.apache.oozie.client.OozieClient#setSafeMode}.
*
* @param user user name to use in LocalOozie for running workflows.
* @return a {@link org.apache.oozie.client.OozieClient} for LocalOozie configured for the given user.
*/
public static OozieClient getClient(String user) {
if (!localOozieActive) {
throw new IllegalStateException("LocalOozie is not initialized");
}
ParamChecker.notEmpty(user, "user");
DagEngine dagEngine = Services.get().get(DagEngineService.class).getDagEngine(user, "undef");
return new LocalOozieClient(dagEngine);
}
/**
* Return a {@link org.apache.oozie.client.OozieClient} for LocalOozie
* configured for a given user.
* <p/>
* The following methods of the client are NOP in the returned instance:
* {@link org.apache.oozie.client.OozieClient#validateWSVersion},
* {@link org.apache.oozie.client.OozieClient#setHeader},
* {@link org.apache.oozie.client.OozieClient#getHeader},
* {@link org.apache.oozie.client.OozieClient#removeHeader},
* {@link org.apache.oozie.client.OozieClient#getHeaderNames} and
* {@link org.apache.oozie.client.OozieClient#setSafeMode}.
*
* @param user user name to use in LocalOozie for running coordinator.
* @return a {@link org.apache.oozie.client.OozieClient} for LocalOozie
* configured for the given user.
*/
public static OozieClient getClientCoord(String user) {
if (!localOozieActive) {
throw new IllegalStateException("LocalOozie is not initialized");
}
ParamChecker.notEmpty(user, "user");
CoordinatorEngine coordEngine = Services.get().get(CoordinatorEngineService.class).getCoordinatorEngine(user,
"undef");
return new LocalOozieClientCoord(coordEngine);
}
}
|
/*
Copyright 2021 Terrarier2111
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 de.terrarier.netlistening.internal;
import de.terrarier.netlistening.api.compression.VarIntUtil;
import de.terrarier.netlistening.impl.ApplicationImpl;
import de.terrarier.netlistening.util.ByteBufUtilExtension;
import io.netty.buffer.ByteBuf;
import org.jetbrains.annotations.ApiStatus;
/**
* @author Terrarier2111
* @since 1.0
*/
@ApiStatus.Internal
public final class InternalUtil {
private InternalUtil() {
throw new UnsupportedOperationException("This class may not be instantiated!");
}
public static void writeInt(@AssumeNotNull ApplicationImpl application, @AssumeNotNull ByteBuf buffer, int value) {
ByteBufUtilExtension.correctSize(buffer, getSize(application, value), application.getBuffer());
writeIntUnchecked(application, buffer, value);
}
public static void writeIntUnchecked(@AssumeNotNull ApplicationImpl application, @AssumeNotNull ByteBuf buffer,
int value) {
if (application.getCompressionSetting().isVarIntCompression()) {
VarIntUtil.writeVarInt(value, buffer);
} else {
buffer.writeInt(value);
}
}
public static int readInt(@AssumeNotNull ApplicationImpl application, @AssumeNotNull ByteBuf buffer)
throws CancelReadSignal {
if (application.getCompressionSetting().isVarIntCompression()) {
return VarIntUtil.getVarInt(buffer);
}
if (buffer.readableBytes() < 4) {
throw VarIntUtil.FOUR_BYTES;
}
return buffer.readInt();
}
static int getSize(@AssumeNotNull ApplicationImpl application, int value) {
return application.getCompressionSetting().isVarIntCompression() ? VarIntUtil.varIntSize(value) : 4;
}
public static int singleOctetIntSize(@AssumeNotNull ApplicationImpl application) {
return application.getCompressionSetting().isVarIntCompression() ? 1 : 4;
}
}
|
package org.firstinspires.ftc.teamcode.autos;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
@Autonomous
// basic autonomous that moves forward 10 inches, waits 5 seconds, turns around, then drives back
public class ThreeMarkerDuckBlue extends ThreeMarkerDuck {
@Override
public void runOpMode() {
super.coeff = -1;
super.runOpMode();
return;
}
}
|
package org.motechproject.mots.domain.enums;
public enum Status {
DRAFT,
RELEASED,
PREVIOUS_VERSION
}
|
/**
* maps4cim - a real world map generator for CiM 2
* Copyright 2013 Sebastian Straub
*
* 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 de.nx42.maps4cim.objects;
import java.io.IOException;
import java.io.OutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract definition of the binary footer to use for the current map.
*
* Contains all objects that are placed on the current map, like roads,
* buildings, trees, etc.
* As with the header, it is also possible to just insert a static footer from
* an empty map with no objects at all. This is implemented in
* {@link StaticGameObjects}.
*
* @author Sebastian Straub <sebastian-straub@gmx.net>
*/
public abstract class GameObjects {
private static Logger log = LoggerFactory.getLogger(GameObjects.class);
/**
* Generates the bytes that shall be written in the file footer.
* @return the footer bytes
* @throws IOException if some stored binaries can't be accessed
*/
public abstract byte[] generateGameObjects() throws IOException;
/**
* Calls the generateGameObjects function and writes the result to the
* specified stream
* @param out the OutputStream to write
* @throws IOException see {@link GameObjects#generateGameObjects()}
*/
public void writeTo(OutputStream out) throws IOException {
byte[] objects = generateGameObjects();
log.info("Writing game objects (postfix)...");
out.write(objects);
}
}
|
package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.SimpleShopInfo;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: ant.merchant.expand.shop.batchquery response.
*
* @author auto create
* @since 1.0, 2021-12-22 00:26:33
*/
public class AntMerchantExpandShopBatchqueryResponse extends AlipayResponse {
private static final long serialVersionUID = 3415247688726119456L;
/**
* 当前页码
*/
@ApiField("page_no")
private Long pageNo;
/**
* 分页数量
*/
@ApiField("page_size")
private Long pageSize;
/**
* 线下门店的列表;有可能为空
*/
@ApiListField("shops")
@ApiField("simple_shop_info")
private List<SimpleShopInfo> shops;
/**
* 按照分页数量拆分,分解出来的页数
*/
@ApiField("total_page")
private Long totalPage;
/**
* 所有线下门店数量
*/
@ApiField("total_size")
private Long totalSize;
public void setPageNo(Long pageNo) {
this.pageNo = pageNo;
}
public Long getPageNo( ) {
return this.pageNo;
}
public void setPageSize(Long pageSize) {
this.pageSize = pageSize;
}
public Long getPageSize( ) {
return this.pageSize;
}
public void setShops(List<SimpleShopInfo> shops) {
this.shops = shops;
}
public List<SimpleShopInfo> getShops( ) {
return this.shops;
}
public void setTotalPage(Long totalPage) {
this.totalPage = totalPage;
}
public Long getTotalPage( ) {
return this.totalPage;
}
public void setTotalSize(Long totalSize) {
this.totalSize = totalSize;
}
public Long getTotalSize( ) {
return this.totalSize;
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class P09StudentsEnrolledIn2014Or2015 {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
Map<String, List<Integer>> students = new LinkedHashMap<>();
while (true) {
String line = bf.readLine();
if ("END".equalsIgnoreCase(line)) {
break;
}
List<String> tokens = Arrays.stream(line.split("\\s+"))
.filter(s -> (s != null && !s.isEmpty())).collect(Collectors.toList());
if (tokens.isEmpty()) {
return;
}
String facultyNumber = tokens.get(0);
List<Integer> grades = tokens.subList(1, tokens.size()).stream()
.map(Integer::valueOf).collect(Collectors.toList());
students.put(facultyNumber, grades);
}
students.entrySet().stream()
.filter(s -> (s.getKey().endsWith("14") || s.getKey().endsWith("15")))
.forEach(s -> System.out.println(Arrays.toString(s.getValue().toArray())
.replaceAll("[\\[\\],]", "")));
}
}
|
package neighbors.handler.renting;
import lombok.RequiredArgsConstructor;
import neighbors.entity.Advert;
import neighbors.entity.User;
import neighbors.enums.AdvertType;
import neighbors.enums.CategoryCommand;
import neighbors.enums.bot.State;
import neighbors.enums.bot.Text;
import neighbors.handler.Handler;
import neighbors.repository.UserRepository;
import neighbors.service.AdvertService;
import neighbors.utils.TelegramUtils;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.PartialBotApiMethod;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import java.io.Serializable;
import java.util.List;
@Component
@RequiredArgsConstructor
public class RentSetCategoryHandler implements Handler {
private final UserRepository userRepository;
private final AdvertService advertService;
@Override
public List<PartialBotApiMethod<? extends Serializable>> handle(User user, String message) {
SendMessage sendMessage = TelegramUtils.createMessageTemplate(user);
Advert advert = advertService.saveAdvert(user, AdvertType.RENT);
user.setCurrentAdvert(advert.getId());
userRepository.save(user);
advertService.setAdvertCategory(advert, message);
sendMessage.setText(Text.REQUEST_RENTING_OUT_NAME);
user.setState(State.RENTING_SET_NAME);
userRepository.save(user);
return List.of(sendMessage);
}
@Override
public List<State> operatedBotState() {
return List.of(State.RENTING_SELECT_CATEGORY);
}
@Override
public List<String> operatedCallBackQuery() {
return List.of(CategoryCommand.CLOTHES, CategoryCommand.OTHER, CategoryCommand.REPAIR_THINGS);
}
}
|
package ucsal.ed.atividade03;
import java.util.Objects;
import ucsal.ed.atividade02.interfaces.Lista;
public class ListaImpl<T> implements Lista<T> {
private static Object[] objetos = {};
private static final Object[] EMPETY = {};
public ListaImpl(int tamanho) {
if(tamanho < 0) {
throw new RuntimeException("Valor negativo não suportado!");
} else {
objetos = new Object[tamanho];
}
}
public ListaImpl() {
}
@Override
public T consultar(T t) {
for (Object o : objetos) {
if(Objects.nonNull(o) && o.equals(t)) {
return t;
}
}
System.out.println(t.toString() + " não existe!");
return null;
}
@Override
public void incluir(T t) {
if(Objects.isNull(t)) {
throw new RuntimeException("Não é possível incluir um professor que não existe!");
}
if (estaCheio()) crescer();
objetos[obterIndexInclusao()] = t;
}
@Override
public void remover(T t) {
boolean existe = false;
for (int i = 0; i < objetos.length; i++) {
Object o = objetos[i];
if(Objects.nonNull(t) && o.equals(t)) {
objetos[i] = null;
diminuir();
existe = true;
}
}
if(!existe) {
System.out.println(t.toString() + " não existe!");
}
}
@Override
public int obterTamanho() {
return objetos.length;
}
@Override
public void limpar() {
objetos = EMPETY;
}
private static int obterIndexInclusao() {
int index = 0;
for(int i = 0; i < objetos.length; i++) {
if(Objects.isNull(objetos[i])) {
index = i;
break;
}
}
return index;
}
private static boolean estaCheio() {
boolean estaCheio = true;
for(Object o : objetos) {
if(Objects.isNull(o)) {
estaCheio = false;
}
}
return estaCheio;
}
private static void crescer() {
int tamanho = objetos.length;
Object[] novo = new Object[tamanho + 1];
for(int i = 0; i < tamanho; i++) {
novo[i] = objetos[i];
}
objetos = novo;
}
private static void diminuir() {
Object[] novo = new Object[objetos.length - 1];
int index = 0;
for (Object o : objetos) {
if(Objects.nonNull(o)) {
novo[index] = o;
index++;
}
}
objetos = novo;
}
}
|
package com.sunny.mvvmbilibili.ui.login;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import com.sunny.mvvmbilibili.R;
import com.sunny.mvvmbilibili.databinding.ActivityLoginBinding;
import com.sunny.mvvmbilibili.injection.qualifier.ActivityContext;
import com.sunny.mvvmbilibili.ui.base.BaseActivity;
import com.sunny.mvvmbilibili.ui.home.HomeActivity;
import javax.inject.Inject;
/**
* The type Login activity.
* Created by Zhou zejin on 2017/8/4.
*/
public class LoginActivity extends BaseActivity implements LoginMvvmView {
@Inject @ActivityContext Context mContext;
@Inject LoginViewModel mViewModel;
private ActivityLoginBinding mBinding;
public static Intent getStartIntent(Context context) {
Intent intent = new Intent(context, LoginActivity.class);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModel.attachView(this);
}
@Override
public void initComponent() {
activityComponent().inject(this);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
mBinding.setViewmodel(mViewModel);
setContentView(mBinding.getRoot());
}
@Override
protected void onDestroy() {
mViewModel.detachView();
super.onDestroy();
}
/*****
* MVVM View methods implementation
*****/
@Override
public void closeView() {
finish();
}
@Override
public void goHomeView() {
startActivity(HomeActivity.getStartIntent(mContext));
}
}
|
/*
* Copyright (c) 2008-2017, 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.concurrent.lock.operations;
import com.hazelcast.concurrent.lock.LockDataSerializerHook;
import com.hazelcast.concurrent.lock.LockStoreImpl;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.BackupAwareOperation;
import com.hazelcast.spi.Notifier;
import com.hazelcast.spi.ObjectNamespace;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.WaitNotifyKey;
import com.hazelcast.spi.impl.MutatingOperation;
import java.io.IOException;
import static java.lang.Boolean.TRUE;
public class UnlockOperation extends AbstractLockOperation implements Notifier, BackupAwareOperation, MutatingOperation {
private boolean force;
private boolean shouldNotify;
public UnlockOperation() {
}
public UnlockOperation(ObjectNamespace namespace, Data key, long threadId) {
super(namespace, key, threadId);
}
public UnlockOperation(ObjectNamespace namespace, Data key, long threadId, boolean force) {
super(namespace, key, threadId);
this.force = force;
}
public UnlockOperation(ObjectNamespace namespace, Data key, long threadId, boolean force, long referenceId) {
super(namespace, key, threadId);
this.force = force;
this.setReferenceCallId(referenceId);
}
@Override
public void run() throws Exception {
if (force) {
forceUnlock();
} else {
unlock();
}
}
protected final void unlock() {
LockStoreImpl lockStore = getLockStore();
boolean unlocked = lockStore.unlock(key, getCallerUuid(), threadId, getReferenceCallId());
response = unlocked;
if (!unlocked) {
// we can not check for retry here, hence just throw the exception
String ownerInfo = lockStore.getOwnerInfo(key);
throw new IllegalMonitorStateException("Current thread is not owner of the lock! -> " + ownerInfo);
}
}
protected final void forceUnlock() {
LockStoreImpl lockStore = getLockStore();
response = lockStore.forceUnlock(key);
}
@Override
public void afterRun() throws Exception {
LockStoreImpl lockStore = getLockStore();
AwaitOperation awaitOperation = lockStore.pollExpiredAwaitOp(key);
if (awaitOperation != null) {
awaitOperation.runExpired();
}
shouldNotify = awaitOperation == null;
}
@Override
public Operation getBackupOperation() {
UnlockBackupOperation operation = new UnlockBackupOperation(namespace, key, threadId,
getCallerUuid(), force);
operation.setReferenceCallId(getReferenceCallId());
return operation;
}
@Override
public boolean shouldBackup() {
return TRUE.equals(response);
}
@Override
public boolean shouldNotify() {
return shouldNotify;
}
@Override
public final WaitNotifyKey getNotifiedKey() {
LockStoreImpl lockStore = getLockStore();
return lockStore.getNotifiedKey(key);
}
@Override
public int getId() {
return LockDataSerializerHook.UNLOCK;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeBoolean(force);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
force = in.readBoolean();
}
}
|
package hr.fer.zemris.calcite.rewriter;
import org.apache.calcite.schema.SchemaFactory;
/**
* Hello world!
*
*/
public class JDBCProxy
{
public static void main( String[] args )
{
System.out.println( args[0] );
}
}
|
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.modules.aa.service;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.aa.dao.PaperDao;
import com.jeesite.modules.aa.entity.CarInfo;
import com.jeesite.modules.aa.entity.Paper;
import com.jeesite.modules.aa.vo.HomePageVO;
import com.jeesite.modules.common.entity.Exam;
import com.jeesite.modules.common.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 试卷Service
* @author lvchangwei
* @version 2019-07-16
*/
@Service
@Transactional(readOnly=true)
public class PaperService extends CrudService<PaperDao, Paper> {
@Autowired
private PaperDao paperDao;
@Autowired
private ExamService examService;
/**
* 获取单条数据
* @param paper
* @return
*/
@Override
public Paper get(Paper paper) {
return super.get(paper);
}
/**
* 查询分页数据
* @param paper 查询条件
* @return
*/
@Override
public Page<Paper> findPage(Paper paper) {
return super.findPage(paper);
}
/**
* 保存数据(插入或更新)
* @param paper
*/
@Override
@Transactional(readOnly=false)
public void save(Paper paper) {
super.save(paper);
}
/**
* 更新状态
* @param paper
*/
@Override
@Transactional(readOnly=false)
public void updateStatus(Paper paper) {
super.updateStatus(paper);
}
/**
* 删除数据
* @param paper
*/
@Override
@Transactional(readOnly=false)
public void delete(Paper paper) {
super.delete(paper);
}
/**
* 查询试卷列表
* @return
*/
public List<Paper> findPaper(Paper paper) {
return paperDao.findPaper(paper);
}
/**
* 加载首页界面(教师端)
*/
public List<CarInfo> loadHomePageTea(HomePageVO homePageVO) {
Map<String,String> hs = new HashMap<>();
hs.put("queryCriteria",homePageVO.getQueryCriteria());
hs.put("sort",homePageVO.getSort());
return paperDao.findPaperBySortTea(hs);
}
/**
* @description: 加载考试信息
* @param: [exam]
* @return: com.jeesite.modules.common.entity.Exam
* @author: Jiangyf
* @date: 2019/8/10
* @time: 16:37
*/
public List<Exam> findExamForCheck(Exam exam) {
return examService.findExamForCheck(exam);
}
public List<Paper> selectExamPaperList(Paper paper) {
return dao.selectExamPaperList(paper);
}
@Transactional
public void deletePaper(String id) {
String[] idList = id.split(",");
dao.deletePaper(idList);
}
}
|
package cc.shinichi.library.view.listener;
import android.view.View;
/**
* @author 工藤
* @email gougou@16fan.com
* cc.shinichi.library.view.listener
* create at 2018/12/19 16:24
* description:
*/
public interface OnBigImageLongClickListener {
/**
* 长按事件
*/
boolean onLongClick(View view, int position);
}
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 6