hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e15493645ffca11656cb7539d3c347bc46ac760
4,269
java
Java
src/main/java/com/dmken/oss/plenum/ui/session/PlenumSession.java
fdamken/plenum
7d7f6dd6a9ee9ad84cc638dc0cfefd850b5ea18d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/dmken/oss/plenum/ui/session/PlenumSession.java
fdamken/plenum
7d7f6dd6a9ee9ad84cc638dc0cfefd850b5ea18d
[ "Apache-2.0" ]
null
null
null
src/main/java/com/dmken/oss/plenum/ui/session/PlenumSession.java
fdamken/plenum
7d7f6dd6a9ee9ad84cc638dc0cfefd850b5ea18d
[ "Apache-2.0" ]
null
null
null
28.844595
125
0.649801
9,038
/*- * #%L * Plenum Manager * %% * Copyright (C) 2017 Fabian Damken * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dmken.oss.plenum.ui.session; import java.beans.PropertyChangeSupport; import java.io.Serializable; import org.springframework.stereotype.Component; import com.dmken.oss.plenum.model.Plenum; import com.dmken.oss.plenum.ui.util.UIUtil; import com.dmken.oss.plenum.ui.view.PlenumView; import com.dmken.oss.plenum.ui.window.LoginModal; import com.vaadin.spring.annotation.UIScope; import com.vaadin.ui.UI; import lombok.Getter; /** * Bean containing session data for the currently viewed plenum. * */ @UIScope @Component("plenumSession") public class PlenumSession implements Serializable { /** * The serial version UID. * */ private static final long serialVersionUID = 993953148901491895L; /** * Name used for events in the {@link #propertyChangeSupport} for * {@link #plenum}. * */ public static final String PROPERTY_PLENUM = "property_plenum"; /** * Name used for events in the {@link #propertyChangeSupport} for * {@link #authenticated}. * */ public static final String PROPERTY_AUTHENTICATED = "property_authenticated"; /** * The property change support. * */ @Getter private final transient PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); /** * The plenum that is currently displayed to the user. Can be * <code>null</code> if the user does not view a plenum. * */ @Getter private Plenum plenum; /** * Whether the user is authenticated/authorized to see the plenum data (e.g. * he has entered the password or the plenum has no password). * */ @Getter private boolean authenticated; /** * Opens the login window for the current plenum in the given {@link UI}. * * @param ui * {@link UI}. */ public void openLoginWindow(final UI ui) { UIUtil.openRedirectWindow(new LoginModal(passwd -> { if (this.authenticate(passwd)) { ui.getNavigator().navigateTo(PlenumView.NAME); return true; } return false; }), ui); } /** * Checks the given password and sets {@link #authenticated} to * <code>true</code> if it is correct. Otherwise <code>false</code>. * * @param password * The password to check * @return The new value of {@link #authenticated}. */ public boolean authenticate(final String password) { if (this.plenum == null) { throw new IllegalStateException("Plenum is not initilized!"); } this.setAuthenticated(this.plenum.getPassword() == null || this.plenum.getPassword().equals(password)); return this.authenticated; } /** * Sets {@link #plenum}. * * @param plenum * The {@link #plenum} to set. */ public void setPlenum(final Plenum plenum) { final Plenum oldPlenum = this.plenum; this.plenum = plenum; this.propertyChangeSupport.firePropertyChange(PlenumSession.PROPERTY_PLENUM, oldPlenum, this.plenum); this.authenticate(null); } /** * Sets {@link #authenticated}. * * @param authenticated * The {@link #authenticated} to set. */ public void setAuthenticated(final boolean authenticated) { final boolean oldAuthenticated = this.authenticated; this.authenticated = authenticated; this.propertyChangeSupport.firePropertyChange(PlenumSession.PROPERTY_AUTHENTICATED, oldAuthenticated, authenticated); } }
3e1549ec94a4f958b240863f7e361df6dcc9468b
3,358
java
Java
examples/group-data-mongo/data-mongo-aggregate/src/test/java/io/rxmicro/examples/data/mongo/aggregate/DataRepository_UnitTest.java
rxmicro/rxmicro-usage
0a34f063cb3f63171f69555ce595405160262848
[ "Apache-2.0" ]
null
null
null
examples/group-data-mongo/data-mongo-aggregate/src/test/java/io/rxmicro/examples/data/mongo/aggregate/DataRepository_UnitTest.java
rxmicro/rxmicro-usage
0a34f063cb3f63171f69555ce595405160262848
[ "Apache-2.0" ]
2
2021-11-06T10:52:06.000Z
2021-11-06T10:52:06.000Z
examples/group-data-mongo/data-mongo-aggregate/src/test/java/io/rxmicro/examples/data/mongo/aggregate/DataRepository_UnitTest.java
rxmicro/rxmicro-usage
0a34f063cb3f63171f69555ce595405160262848
[ "Apache-2.0" ]
null
null
null
35.347368
109
0.681954
9,039
/* * Copyright (c) 2020. https://rxmicro.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rxmicro.examples.data.mongo.aggregate; import com.mongodb.reactivestreams.client.MongoDatabase; import io.rxmicro.examples.data.mongo.aggregate.model.Report; import io.rxmicro.test.Alternative; import io.rxmicro.test.junit.BeforeThisTest; import io.rxmicro.test.junit.RxMicroComponentTest; import io.rxmicro.test.mockito.junit.InitMocks; import io.rxmicro.test.mockito.mongo.AggregateOperationMock; import org.bson.Document; import org.junit.jupiter.api.Test; import org.mockito.Mock; import java.math.BigDecimal; import java.util.List; import java.util.Map; import static io.rxmicro.examples.data.mongo.aggregate.DataRepository.COLLECTION_NAME; import static io.rxmicro.examples.data.mongo.aggregate.model.Role.CEO; import static io.rxmicro.test.mockito.mongo.MongoMockFactory.prepareMongoOperationMocks; import static java.util.Objects.requireNonNull; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @InitMocks @RxMicroComponentTest(DataRepository.class) final class DataRepository_UnitTest { private static final AggregateOperationMock AGGREGATE_OPERATION_MOCK = new AggregateOperationMock.Builder() .addPipeline("{ $group : { _id: '$role', total : { $sum: '$balance'}} }") .addPipeline("{ $sort: {total: -1, _id: -1} }") .build(); private DataRepository dataRepository; @Mock @Alternative private MongoDatabase mongoDatabase; void prepareAggregateSuccess() { prepareMongoOperationMocks( mongoDatabase, COLLECTION_NAME, AGGREGATE_OPERATION_MOCK, new Document(Map.of( "_id", "CEO", "total", new BigDecimal("70000.00") )) ); } @Test @BeforeThisTest(method = "prepareAggregateSuccess") void aggregateSuccess() { final List<Report> reports = requireNonNull(dataRepository.aggregate().collectList().block()); assertEquals( List.of(new Report(CEO, new BigDecimal("70000.00"))), reports ); } void prepareAggregateFailed() { prepareMongoOperationMocks( mongoDatabase, COLLECTION_NAME, AGGREGATE_OPERATION_MOCK, new RuntimeException("error") ); } @Test @BeforeThisTest(method = "prepareAggregateFailed") void aggregateFailed() { final RuntimeException exception = assertThrows(RuntimeException.class, () -> dataRepository.aggregate().collectList().block()); assertEquals("error", exception.getMessage()); } }
3e154a2c4f90f4a699000207f8d500bde41ee105
4,886
java
Java
src/main/java/ru/lanbilling/webservice/wsdl/SoapRoute.java
kanonirov/lanb-client
bfe333cf41998e806f9c74ad257c6f2d7e013ba1
[ "MIT" ]
null
null
null
src/main/java/ru/lanbilling/webservice/wsdl/SoapRoute.java
kanonirov/lanb-client
bfe333cf41998e806f9c74ad257c6f2d7e013ba1
[ "MIT" ]
null
null
null
src/main/java/ru/lanbilling/webservice/wsdl/SoapRoute.java
kanonirov/lanb-client
bfe333cf41998e806f9c74ad257c6f2d7e013ba1
[ "MIT" ]
null
null
null
30.347826
116
0.585346
9,040
package ru.lanbilling.webservice.wsdl; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for soapRoute complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="soapRoute"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="routeid" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/&gt; * &lt;element name="operid" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/&gt; * &lt;element name="number" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="comment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "soapRoute", propOrder = { "routeid", "operid", "number", "comment" }) @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public class SoapRoute { @XmlElement(defaultValue = "0") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected Long routeid; @XmlElement(defaultValue = "0") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected Long operid; @XmlElement(defaultValue = "") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected String number; @XmlElement(defaultValue = "") @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") protected String comment; /** * Gets the value of the routeid property. * * @return * possible object is * {@link Long } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public Long getRouteid() { return routeid; } /** * Sets the value of the routeid property. * * @param value * allowed object is * {@link Long } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setRouteid(Long value) { this.routeid = value; } /** * Gets the value of the operid property. * * @return * possible object is * {@link Long } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public Long getOperid() { return operid; } /** * Sets the value of the operid property. * * @param value * allowed object is * {@link Long } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setOperid(Long value) { this.operid = value; } /** * Gets the value of the number property. * * @return * possible object is * {@link String } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public String getNumber() { return number; } /** * Sets the value of the number property. * * @param value * allowed object is * {@link String } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setNumber(String value) { this.number = value; } /** * Gets the value of the comment property. * * @return * possible object is * {@link String } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public String getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link String } * */ @Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11") public void setComment(String value) { this.comment = value; } }
3e154a7ebacb14bcbf768215a3fdab9954ec85ed
1,065
java
Java
kafka/src/main/java/com/me/kafka/partitioner/MyPartitioner.java
zzzzzzzs/Kafka_self_study
ff5f2aa14af1d9b1c5567f44b045b6a3e8a7b586
[ "MIT" ]
null
null
null
kafka/src/main/java/com/me/kafka/partitioner/MyPartitioner.java
zzzzzzzs/Kafka_self_study
ff5f2aa14af1d9b1c5567f44b045b6a3e8a7b586
[ "MIT" ]
null
null
null
kafka/src/main/java/com/me/kafka/partitioner/MyPartitioner.java
zzzzzzzs/Kafka_self_study
ff5f2aa14af1d9b1c5567f44b045b6a3e8a7b586
[ "MIT" ]
null
null
null
18.684211
119
0.57277
9,041
package com.me.kafka.partitioner; import org.apache.kafka.clients.producer.Partitioner; import org.apache.kafka.common.Cluster; import java.util.Map; /** * 自定义分区器 * 参考DefaultPartitioner * 需要实现Partitioner接口 */ public class MyPartitioner implements Partitioner { /** * 计算当前消息的分区号 * @param topic 主题 * @param key 消息的key * @param keyBytes 序列化后的key * @param value 消息的value * @param valueBytes 序列化后的value * @param cluster * @return * * * 模拟实现: * 使用second主题, 有两个分区 * 消息带有atguigu的,去往0号分区 * 其他的消息去往1号分区 */ @Override public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { if(value.toString().contains("atguigu")){ return 0 ; }else{ return 1 ; } } /** * 关闭资源 */ @Override public void close() { } /** * 读取配置的 * @param configs */ @Override public void configure(Map<String, ?> configs) { } }
3e154afbad0a1987b67551530d23e5e8212b9b7d
875
java
Java
plugins/dnd-viewer/src/main/java/org/nakedobjects/plugins/dnd/viewer/view/form/WindowExpandableFormSpecification.java
Corpus-2021/nakedobjects-4.0.0
37ee250d4c8da969eac76749420064ca4c918e8e
[ "Apache-2.0" ]
null
null
null
plugins/dnd-viewer/src/main/java/org/nakedobjects/plugins/dnd/viewer/view/form/WindowExpandableFormSpecification.java
Corpus-2021/nakedobjects-4.0.0
37ee250d4c8da969eac76749420064ca4c918e8e
[ "Apache-2.0" ]
null
null
null
plugins/dnd-viewer/src/main/java/org/nakedobjects/plugins/dnd/viewer/view/form/WindowExpandableFormSpecification.java
Corpus-2021/nakedobjects-4.0.0
37ee250d4c8da969eac76749420064ca4c918e8e
[ "Apache-2.0" ]
1
2021-02-22T15:40:05.000Z
2021-02-22T15:40:05.000Z
31.25
93
0.722286
9,042
package org.nakedobjects.plugins.dnd.viewer.view.form; import org.nakedobjects.plugins.dnd.View; import org.nakedobjects.plugins.dnd.ViewRequirement; import org.nakedobjects.plugins.dnd.viewer.border.ExpandableViewBorder; public class WindowExpandableFormSpecification extends WindowFormSpecification { @Override public View decorateSubview(View subview) { if (subview.getContent().isObject() || subview.getContent().isCollection()) { return super.decorateSubview(new ExpandableViewBorder(subview)); } else { return super.decorateSubview(subview); } } protected int collectionRequirement() { return ViewRequirement.CLOSED | ViewRequirement.SUBVIEW | ViewRequirement.EXPANDABLE; } public String getName() { return "Expanding Form"; } } // Copyright (c) Naked Objects Group Ltd.
3e154bab2826a82e55e8c89e739801c167c8c34c
38,405
java
Java
Android/nertcvoiceroom/src/main/java/com/netease/yunxin/nertc/nertcvoiceroom/model/impl/NERtcVoiceRoomImpl.java
sunkeding/NEChatroom
0f15eb5914fd12d7ea4981de23cb99665fd44682
[ "MIT" ]
29
2020-10-20T09:05:50.000Z
2021-03-17T11:25:18.000Z
Android/nertcvoiceroom/src/main/java/com/netease/yunxin/nertc/nertcvoiceroom/model/impl/NERtcVoiceRoomImpl.java
sunkeding/NEChatroom
0f15eb5914fd12d7ea4981de23cb99665fd44682
[ "MIT" ]
2
2021-04-01T08:50:55.000Z
2021-12-28T07:55:51.000Z
Android/nertcvoiceroom/src/main/java/com/netease/yunxin/nertc/nertcvoiceroom/model/impl/NERtcVoiceRoomImpl.java
sunkeding/NEChatroom
0f15eb5914fd12d7ea4981de23cb99665fd44682
[ "MIT" ]
14
2020-08-31T06:09:13.000Z
2021-02-23T09:27:13.000Z
34.077196
156
0.583049
9,043
package com.netease.yunxin.nertc.nertcvoiceroom.model.impl; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import androidx.annotation.NonNull; import com.blankj.utilcode.util.GsonUtils; import com.netease.yunxin.kit.alog.ALog; import com.netease.lava.nertc.sdk.NERtcConstants; import com.netease.lava.nertc.sdk.NERtcEx; import com.netease.lava.nertc.sdk.NERtcOption; import com.netease.lava.nertc.sdk.NERtcParameters; import com.netease.lava.nertc.sdk.stats.NERtcAudioVolumeInfo; import com.netease.lava.nertc.sdk.video.NERtcRemoteVideoStreamType; import com.netease.nimlib.sdk.InvocationFuture; import com.netease.nimlib.sdk.NIMClient; import com.netease.nimlib.sdk.Observer; import com.netease.nimlib.sdk.RequestCallback; import com.netease.nimlib.sdk.StatusCode; import com.netease.nimlib.sdk.chatroom.ChatRoomMessageBuilder; import com.netease.nimlib.sdk.chatroom.ChatRoomService; import com.netease.nimlib.sdk.chatroom.ChatRoomServiceObserver; import com.netease.nimlib.sdk.chatroom.model.ChatRoomInfo; import com.netease.nimlib.sdk.chatroom.model.ChatRoomKickOutEvent; import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember; import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage; import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment; import com.netease.nimlib.sdk.chatroom.model.ChatRoomQueueChangeAttachment; import com.netease.nimlib.sdk.chatroom.model.ChatRoomStatusChangeData; import com.netease.nimlib.sdk.chatroom.model.ChatRoomTempMuteAddAttachment; import com.netease.nimlib.sdk.chatroom.model.ChatRoomTempMuteRemoveAttachment; import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData; import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomResultData; import com.netease.nimlib.sdk.msg.MsgService; import com.netease.nimlib.sdk.msg.MsgServiceObserve; import com.netease.nimlib.sdk.msg.attachment.MsgAttachment; import com.netease.nimlib.sdk.msg.constant.ChatRoomQueueChangeType; import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum; import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum; import com.netease.nimlib.sdk.msg.model.CustomNotification; import com.netease.nimlib.sdk.util.Entry; import com.netease.yunxin.nertc.nertcvoiceroom.model.Anchor; import com.netease.yunxin.nertc.nertcvoiceroom.model.Audience; import com.netease.yunxin.nertc.nertcvoiceroom.model.AudioPlay; import com.netease.yunxin.nertc.nertcvoiceroom.model.NERtcVoiceRoom; import com.netease.yunxin.nertc.nertcvoiceroom.model.NERtcVoiceRoomDef.AccountMapper; import com.netease.yunxin.nertc.nertcvoiceroom.model.NERtcVoiceRoomDef.RoomCallback; import com.netease.yunxin.nertc.nertcvoiceroom.model.PushTypeSwitcher; import com.netease.yunxin.nertc.nertcvoiceroom.model.StreamTaskControl; import com.netease.yunxin.nertc.nertcvoiceroom.model.VoiceRoomInfo; import com.netease.yunxin.nertc.nertcvoiceroom.model.VoiceRoomMessage; import com.netease.yunxin.nertc.nertcvoiceroom.model.VoiceRoomSeat; import com.netease.yunxin.nertc.nertcvoiceroom.model.VoiceRoomSeat.Status; import com.netease.yunxin.nertc.nertcvoiceroom.model.VoiceRoomUser; import com.netease.yunxin.nertc.nertcvoiceroom.model.custom.CloseRoomAttach; import com.netease.yunxin.nertc.nertcvoiceroom.model.custom.CustomAttachParser; import com.netease.yunxin.nertc.nertcvoiceroom.model.custom.CustomAttachmentType; import com.netease.yunxin.nertc.nertcvoiceroom.model.custom.MusicControl; import com.netease.yunxin.nertc.nertcvoiceroom.model.custom.StreamRestarted; import com.netease.yunxin.nertc.nertcvoiceroom.model.ktv.MusicSing; import com.netease.yunxin.nertc.nertcvoiceroom.model.ktv.SEI; import com.netease.yunxin.nertc.nertcvoiceroom.model.ktv.impl.MusicSingImpl; import com.netease.yunxin.nertc.nertcvoiceroom.util.SuccessCallback; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.netease.yunxin.nertc.nertcvoiceroom.model.NERtcVoiceRoomDef.RoomAudioQuality; public class NERtcVoiceRoomImpl extends NERtcVoiceRoomInner { private static final String LOG_TAG = NERtcVoiceRoomImpl.class.getSimpleName(); private static NERtcVoiceRoomImpl sInstance; public static synchronized NERtcVoiceRoom sharedInstance(Context context) { if (sInstance == null) { sInstance = new NERtcVoiceRoomImpl(context.getApplicationContext()); } return sInstance; } public static synchronized void destroySharedInstance() { if (sInstance != null) { sInstance.destroy(); sInstance = null; } } private final Context context; /** * 音视频引擎 */ private NERtcEx engine; /** * 聊天室服务 */ private ChatRoomService chatRoomService; /** * 房间信息 */ private VoiceRoomInfo voiceRoomInfo; private RoomQuery roomQuery; /** * 用户信息 */ private VoiceRoomUser user; /** * 点歌服务 */ private MusicSing musicSing; /** * 主播模式 */ private boolean anchorMode; /** * 房间静音状态 */ private boolean muteRoomAudio; /** * 耳返状态 */ private boolean enableEarBack; /** * 采集音量,默认100 */ private int audioCaptureVolume = 100; /** * 房间状态回调 */ private RoomCallback roomCallback; private final List<VoiceRoomSeat> seats = new ArrayList<>(); private boolean initial = false; /** * 音视频引擎回调 */ private final NERtcCallbackExImpl callback = new NERtcCallbackExImpl() { @Override public void onJoinChannel(int result, long channelId, long elapsed) { if (anchorMode && voiceRoomInfo.isSupportCDN()) { getStreamTaskControl().addStreamTask(accountToVoiceUid(user.account), voiceRoomInfo.getStreamConfig().pushUrl); } ALog.e("NERtcVoiceRoomImpl", "join channel result code is " + result); onEnterRoom(result == NERtcConstants.ErrorCode.OK || result == NERtcConstants.ErrorCode.ENGINE_ERROR_ROOM_ALREADY_JOINED); //设置之前保存的采集音量 engine.adjustRecordingSignalVolume(audioCaptureVolume); } /** * CDN 模式下添加对应用户的混流设置 * @param uid 用户id */ @Override public void onUserJoined(long uid) { if (!voiceRoomInfo.isSupportCDN()) { return; } if (anchorMode) { getStreamTaskControl().addMixStreamUser(uid); } } /** * CDN 模式下 移除对应用户的混流设置 * @param uid 用户id * @param reason 该用户离开原因{@link com.netease.lava.nertc.sdk.NERtcConstants.ErrorCode} */ @Override public void onUserLeave(long uid, int reason) { if (!voiceRoomInfo.isSupportCDN()) { return; } if (anchorMode) { getStreamTaskControl().removeMixStreamUser(uid); } } @Override public void onLeaveChannel(int result) { ALog.e("NERtcVoiceRoomImpl", "leave channel result code is " + result); if (anchorMode || !initial || !voiceRoomInfo.isSupportCDN()) { onLeaveRoom(); } } /** * 通知混音状态 * 0 播放完成 * 1 播放出错 */ @Override public void onAudioMixingStateChanged(int reason) { if (audioPlay != null) { audioPlay.onAudioMixingStateChanged(reason); } } @Override public void onAudioMixingTimestampUpdate(long timestampMs) { musicSing.receiveSEIMsg(timestampMs); String seiString = GsonUtils.toJson(new SEI(timestampMs)); engine.sendSEIMsg(seiString); } @Override public void onRecvSEIMsg(long l, String s) { SEI sei = GsonUtils.fromJson(s, SEI.class); musicSing.receiveSEIMsg(sei.audio_mixing_pos); } /** * 通知音效播放完成 */ @Override public void onAudioEffectFinished(int effectId) { if (audioPlay != null) { audioPlay.onAudioEffectFinished(effectId); } } @Override public void onUserVideoStart(long uid, int maxProfile) { super.onUserVideoStart(uid, maxProfile); engine.subscribeRemoteVideoStream(uid, NERtcRemoteVideoStreamType.kNERtcRemoteVideoStreamTypeHigh, true); } /** * 通知房间内用户语音音量,可以知道,“谁”正在说话 */ @Override public void onRemoteAudioVolumeIndication(NERtcAudioVolumeInfo[] volumeArray, int totalVolume) { Map<Long, Integer> volumes = new HashMap<>(); for (NERtcAudioVolumeInfo volumeInfo : volumeArray) { volumes.put(volumeInfo.uid, volumeInfo.volume); } updateVolumes(volumes); } @Override public void onDisconnect(int reason) { ALog.e("NERtcVoiceRoomImpl", "disconnected from RTC room. reason is " + reason); leaveRoom(); onLeaveRoom(); } }; private final AnchorImpl anchor = new AnchorImpl(this); private final AudienceImpl audience = new AudienceImpl(this); private AudioPlayImpl audioPlay; private StreamTaskControl streamTaskControl; private PushTypeSwitcher switcher; private final Observer<List<ChatRoomMessage>> messageObserver = new Observer<List<ChatRoomMessage>>() { @Override public void onEvent(List<ChatRoomMessage> chatRoomMessages) { if (chatRoomMessages == null || chatRoomMessages.isEmpty()) { return; } if (voiceRoomInfo == null) { return; } final String roomId = voiceRoomInfo.getRoomId(); for (ChatRoomMessage message : chatRoomMessages) { if (message.getSessionType() != SessionTypeEnum.ChatRoom || !message.getSessionId().equals(roomId)) { continue; } MsgAttachment attachment = message.getAttachment(); if (attachment instanceof ChatRoomNotificationAttachment) { onNotification((ChatRoomNotificationAttachment) attachment); continue; } if (message.getMsgType() == MsgTypeEnum.text) { onTextMessage(message); continue; } if (attachment instanceof CloseRoomAttach) { if (roomCallback != null) { roomCallback.onRoomDismiss(); } return; } if (attachment instanceof StreamRestarted) { audience.restartAudioOrNot(); return; } if (attachment instanceof MusicControl) { MusicControl musicControl = (MusicControl) attachment; int type = musicControl.getType(); if (roomCallback != null) { VoiceRoomMessage msg = VoiceRoomMessage.createEventMessage( getMessageTextBuilder().musicEvent(musicControl.operator, type == CustomAttachmentType.MUSIC_PAUSE)); roomCallback.onVoiceRoomMessage(msg); roomCallback.onMusicStateChange(type); } } } } }; private final Observer<ChatRoomKickOutEvent> kickOutObserver = new Observer<ChatRoomKickOutEvent>() { @Override public void onEvent(ChatRoomKickOutEvent event) { if (voiceRoomInfo == null) { return; } final String roomId = voiceRoomInfo.getRoomId(); if (!roomId.equals(event.getRoomId())) { return; } if (roomCallback != null) { roomCallback.onRoomDismiss(); } } }; private final Observer<CustomNotification> customNotification = new Observer<CustomNotification>() { @Override public void onEvent(CustomNotification notification) { int command = SeatCommands.commandFrom(notification); VoiceRoomSeat seat = SeatCommands.seatFrom(notification); if (seat == null) { return; } anchor.command(command, seat); } }; Observer<ChatRoomStatusChangeData> onlineStatusObserver = new Observer<ChatRoomStatusChangeData>() { @Override public void onEvent(ChatRoomStatusChangeData change) { String roomId = voiceRoomInfo != null ? voiceRoomInfo.getRoomId() : ""; if (!roomId.equals(change.roomId)) { return; } if (change.status == StatusCode.LOGINED && musicSing != null) { musicSing.update(); } if (change.status.wontAutoLogin()) { // } } }; private static final int MSG_MEMBER_EXIT = 500; private static final Handler delayHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(@NonNull Message msg) { removeMessages(msg.what); if (msg.obj instanceof Runnable) { ((Runnable) msg.obj).run(); } } }; private NERtcVoiceRoomImpl(Context context) { this.context = context; NIMClient.getService(MsgService.class).registerCustomAttachmentParser(new CustomAttachParser()); chatRoomService = NIMClient.getService(ChatRoomService.class); engine = NERtcEx.getInstance(); } private void destroy() { if (engine != null) { engine.release(); } } /** * 恢复单例中非 长期有效对象内容为默认 */ private void restoreInstanceInfo() { muteRoomAudio = false; user = null; voiceRoomInfo = null; anchorMode = false; audioCaptureVolume = 100; } @Override public void init(String appKey, RoomCallback callback) { roomCallback = callback; NERtcOption option = new NERtcOption(); musicSing = MusicSing.shareInstance(); option.logLevel = NERtcConstants.LogLevel.DEBUG; try { engine.init(context, appKey, this.callback, option); } catch (Exception e) { e.printStackTrace(); } initial = true; } @Override public void setAudioQuality(int quality) { int scenario = NERtcConstants.AudioScenario.CHATROOM; int profile = NERtcConstants.AudioProfile.HIGH_QUALITY; if (quality == RoomAudioQuality.MUSIC_QUALITY) { scenario = NERtcConstants.AudioScenario.MUSIC; profile = NERtcConstants.AudioProfile.HIGH_QUALITY_STEREO; } engine.setAudioProfile(profile, scenario); } @Override public void initRoom(VoiceRoomInfo voiceRoomInfo, VoiceRoomUser user) { this.voiceRoomInfo = voiceRoomInfo; this.user = user; this.roomQuery = new RoomQuery(voiceRoomInfo, chatRoomService); anchor.initRoom(voiceRoomInfo); } @Override public void enterRoom(final boolean anchorMode) { this.anchorMode = anchorMode; EnterChatRoomData roomData = new EnterChatRoomData(voiceRoomInfo.getRoomId()); roomData.setNick(user.nick); roomData.setAvatar(user.avatar); InvocationFuture<EnterChatRoomResultData> future = anchorMode ? chatRoomService.enterChatRoom( roomData) : chatRoomService.enterChatRoomEx(roomData, 1); future.setCallback(new RequestCallback<EnterChatRoomResultData>() { @Override public void onSuccess(EnterChatRoomResultData param) { ALog.e("====>", "enter room success."); if (roomCallback != null) { roomCallback.onOnlineUserCount(param.getRoomInfo().getOnlineUserCount()); } if (!anchorMode) { audience.enterRoom(voiceRoomInfo, user, param); } else { anchor.enterRoom(); } Boolean mute = isAnchorMute(param.getRoomInfo()); if (mute != null) { if (roomCallback != null) { roomCallback.onAnchorMute(mute); } } if (anchorMode || !voiceRoomInfo.isSupportCDN()) { joinChannel(); } else { audience.getAudiencePlay().play(voiceRoomInfo.getStreamConfig().rtmpPullUrl); onEnterRoom(true); } initSeats(); initAnchorInfo(); initKtv(); } @Override public void onFailed(int code) { ALog.e("====>", "enter room fail."); if (roomCallback != null) { roomCallback.onEnterRoom(false); } destroy();// must destroy engine restoreInstanceInfo(); } @Override public void onException(Throwable exception) { ALog.e("====>", "enter room exception."); if (roomCallback != null) { roomCallback.onEnterRoom(false); } destroy();// must destroy engine restoreInstanceInfo(); } }); } @Override public void leaveRoom() { initial = false; delayHandler.removeMessages(MSG_MEMBER_EXIT); listen(false); Runnable runnable = new Runnable() { @Override public void run() { if (voiceRoomInfo != null) { ALog.e("====>", "leave room."); chatRoomService.exitChatRoom(voiceRoomInfo.getRoomId()); } if (anchorMode && voiceRoomInfo.isSupportCDN()) { getStreamTaskControl().removeStreamTask(); } int resultCode = engine.leaveChannel(); ALog.e("====>", "level channel code is " + resultCode); } }; if (anchorMode || !audience.leaveRoom(runnable)) { runnable.run(); } } @Override public void startLocalAudio() { engine.enableLocalAudio(true); } @Override public void stopLocalAudio() { engine.enableLocalAudio(false); } @Override public boolean muteLocalAudio(boolean mute) { engine.setRecordDeviceMute(mute); boolean muted = isLocalAudioMute(); if (anchorMode) { anchor.muteLocalAudio(muted); } else { audience.muteLocalAudio(muted); } if (roomCallback != null) { roomCallback.onMute(muted); } return muted; } @Override public boolean isLocalAudioMute() { return engine.isRecordDeviceMute(); } @Override public void setSpeaker(boolean useSpeaker) { engine.setSpeakerphoneOn(useSpeaker); } @Override public void setAudioCaptureVolume(int volume) { audioCaptureVolume = volume; engine.adjustRecordingSignalVolume(volume); } @Override public int getAudioCaptureVolume() { return audioCaptureVolume; } @Override public boolean muteRoomAudio(boolean mute) { muteRoomAudio = mute; engine.setPlayoutDeviceMute(mute); if (anchorMode) { anchor.muteRoomAudio(mute); } else if (voiceRoomInfo.isSupportCDN()) { audience.getAudiencePlay().setVolume(mute ? 0f : 1f); } return mute; } @Override public boolean isRoomAudioMute() { return muteRoomAudio; } @Override public boolean isEarBackEnable() { return enableEarBack; } @Override public void enableEarback(boolean enable) { this.enableEarBack = enable; engine.enableEarback(enable, 100); } @Override public void sendTextMessage(String text) { sendMessage(text, false); } @Override public AudioPlay getAudioPlay() { if (audioPlay == null) { audioPlay = new AudioPlayImpl(engine); } return audioPlay; } @Override public PushTypeSwitcher getPushTypeSwitcher() { if (switcher == null) { switcher = new PushTypeSwitcherImpl(context, engine, audience.getAudiencePlay()); } return switcher; } public StreamTaskControl getStreamTaskControl() { if (streamTaskControl == null) { streamTaskControl = new StreamTaskControlImpl(anchor, engine); } return streamTaskControl; } @Override public Anchor getAnchor() { return anchor; } @Override public Audience getAudience() { return audience; } @Override void updateSeat(VoiceRoomSeat seat) { this.seats.set(seat.getIndex(), seat); if (roomCallback != null) { roomCallback.updateSeat(seat); } if (!seat.isOn() &&(seat.getReason() == VoiceRoomSeat.Reason.ANCHOR_KICK || seat.getReason() == VoiceRoomSeat.Reason.LEAVE)&& anchorMode) { musicSing.leaveSet(seat.getUser(), false); } } @Override synchronized VoiceRoomSeat getSeat(int index) { return seats.get(index); } @Override void sendSeatEvent(VoiceRoomSeat seat, boolean enter) { sendMessage(getMessageTextBuilder().seatEvent(seat, enter), true); } @Override void sendSeatUpdate(VoiceRoomSeat seat, RequestCallback<Void> callback) { chatRoomService.updateQueue(voiceRoomInfo.getRoomId(), seat.getKey(), seat.toJsonString()).setCallback(callback); } @Override void fetchSeats(final RequestCallback<List<VoiceRoomSeat>> callback) { chatRoomService.fetchQueue(voiceRoomInfo.getRoomId()).setCallback(new RequestCallback<List<Entry<String, String>>>() { @Override public void onSuccess(List<Entry<String, String>> param) { if (callback != null) { List<VoiceRoomSeat> seats = createSeats(); if (param != null) { fillSeats(param, seats); } callback.onSuccess(seats); } } @Override public void onFailed(int code) { if (callback != null) { callback.onFailed(code); } } @Override public void onException(Throwable exception) { if (callback != null) { callback.onException(exception); } } }); } @Override boolean isInitial() { return initial; } private void listen(boolean on) { NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(customNotification, on); NIMClient.getService(ChatRoomServiceObserver.class).observeReceiveMessage(messageObserver, on); NIMClient.getService(ChatRoomServiceObserver.class).observeKickOutEvent(kickOutObserver, on); NIMClient.getService(ChatRoomServiceObserver.class).observeOnlineStatus(onlineStatusObserver, on); } private void onEnterRoom(boolean success) { if (success) { listen(true); // 打开扬声器 setSpeaker(true); // 打开耳返 enableEarback(false); // 设置音量汇报间隔 500ms engine.enableAudioVolumeIndication(true, 500); if (!anchorMode) { musicSing.update(); } } if (roomCallback != null) { roomCallback.onEnterRoom(success); } } private void onLeaveRoom() { if (audioPlay!=null){ audioPlay.reset(); } engine.release(); restoreInstanceInfo(); if (roomCallback != null) { roomCallback.onLeaveRoom(); } } private void joinChannel() { setAudioQuality(voiceRoomInfo.getAudioQuality()); setupParameters(); if (anchorMode) { startLocalAudio(); } else { stopLocalAudio(); } int result = engine.joinChannel(null, voiceRoomInfo.getRoomId(), accountToVoiceUid(user.account)); ALog.e("====>", "join channel code is " + result); if (result != 0) { if (roomCallback != null) { roomCallback.onEnterRoom(false); } } } private void setupParameters() { NERtcParameters parameters = new NERtcParameters(); parameters.setBoolean(NERtcParameters.KEY_AUTO_SUBSCRIBE_AUDIO, true); if (voiceRoomInfo.isSupportCDN()) { parameters.set(NERtcParameters.KEY_PUBLISH_SELF_STREAM, true); } NERtcEx.getInstance().setParameters(parameters); } private void updateRoomInfo() { chatRoomService.fetchRoomInfo(voiceRoomInfo.getRoomId()).setCallback(new SuccessCallback<ChatRoomInfo>() { @Override public void onSuccess(ChatRoomInfo param) { if (!anchorMode) { audience.updateRoomInfo(param); } if (roomCallback != null) { roomCallback.onOnlineUserCount(param.getOnlineUserCount()); } Boolean mute = isAnchorMute(param); if (mute != null) { if (roomCallback != null) { roomCallback.onAnchorMute(mute); } } } }); } private void initAnchorInfo() { if (anchorMode) { initAnchorInfo(user); return; } roomQuery.fetchMember(voiceRoomInfo.getCreatorAccount(), new SuccessCallback<ChatRoomMember>() { @Override public void onSuccess(ChatRoomMember chatRoomMember) { if (chatRoomMember != null) { initAnchorInfo(new VoiceRoomUser(chatRoomMember)); } } }); } private void initKtv() { musicSing.initRoom(chatRoomService, user, voiceRoomInfo.getRoomId()); musicSing.setAudienceInfo(anchorMode, audience); musicSing.setRoomCallback(roomCallback); } private void initAnchorInfo(VoiceRoomUser user) { if (roomCallback != null) { roomCallback.onAnchorInfo(user); } } private void initSeats() { if (anchorMode) { updateSeats(createSeats()); // return; } fetchSeats(new SuccessCallback<List<VoiceRoomSeat>>() { @Override public void onSuccess(List<VoiceRoomSeat> seats) { if (!anchorMode) { audience.initSeats(seats); } else { anchor.initSeats(seats); } updateSeats(seats); } }); } @Override public void refreshSeats() { initSeats(); } private void onNotification(final ChatRoomNotificationAttachment notification) { switch (notification.getType()) { case ChatRoomQueueChange: { ChatRoomQueueChangeAttachment queueChange = (ChatRoomQueueChangeAttachment) notification; onQueueChange(queueChange); break; } case ChatRoomMemberIn: { delayHandler.removeMessages(MSG_MEMBER_EXIT); updateRoomInfo(); sendRoomEvent(notification.getTargetNicks(), true); break; } case ChatRoomMemberExit: { delayHandler.sendMessageDelayed(delayHandler.obtainMessage(MSG_MEMBER_EXIT, new Runnable() { @Override public void run() { updateRoomInfo(); if (anchorMode) { anchor.memberExit(notification.getOperator()); } sendRoomEvent(notification.getTargetNicks(), false); } }), 500); break; } case ChatRoomRoomMuted: { if (!anchorMode) { audience.muteText(true); } break; } case ChatRoomRoomDeMuted: { if (!anchorMode) { roomQuery.fetchMember(user.account, new SuccessCallback<ChatRoomMember>() { @Override public void onSuccess(ChatRoomMember member) { if (member != null) { audience.updateMemberInfo(member); } } }); } break; } case ChatRoomMemberTempMuteAdd: { ChatRoomTempMuteAddAttachment muteAdd = (ChatRoomTempMuteAddAttachment) notification; if (!anchorMode) { if (muteAdd.getTargets().contains(user.account)) { audience.muteText(true); } } break; } case ChatRoomMemberTempMuteRemove: { ChatRoomTempMuteRemoveAttachment muteRemove = (ChatRoomTempMuteRemoveAttachment) notification; if (!anchorMode) { if (muteRemove.getTargets().contains(user.account)) { audience.muteText(false); } } break; } case ChatRoomInfoUpdated: { Boolean mute = isAnchorMute(notification); if (mute != null) { if (roomCallback != null) { roomCallback.onAnchorMute(mute); } } break; } } } private void onTextMessage(ChatRoomMessage message) { String content = message.getContent(); String nick = message.getChatRoomMessageExtension().getSenderNick(); VoiceRoomMessage msg = isEventMessage(message) ? VoiceRoomMessage.createEventMessage(content) : VoiceRoomMessage.createTextMessage(nick, content); if (roomCallback != null) { roomCallback.onVoiceRoomMessage(msg); } } private void onQueueChange(ChatRoomQueueChangeAttachment queueChange) { ALog.i(LOG_TAG, "onQueueChange: type = " + queueChange.getChatRoomQueueChangeType() + " key = " + queueChange.getKey() + " content = " + queueChange.getContent()); ChatRoomQueueChangeType type = queueChange.getChatRoomQueueChangeType(); if (type == ChatRoomQueueChangeType.DROP) { if (anchorMode) { anchor.clearSeats(); } else { audience.clearSeats(); } updateSeats(createSeats()); return; } if (type == ChatRoomQueueChangeType.OFFER || type == ChatRoomQueueChangeType.POLL) { String content = queueChange.getContent(); String key = queueChange.getKey(); if (TextUtils.isEmpty(content)) { return; } if (MusicSingImpl.isMusicKey(key)) { if (type == ChatRoomQueueChangeType.OFFER) { musicSing.addSongFromQueue(content); } else { musicSing.removeSongFromQueue(content); } } else if (type == ChatRoomQueueChangeType.OFFER) { VoiceRoomSeat seat = VoiceRoomSeat.fromJson(content); if (seat == null) { return; } VoiceRoomSeat currentSeat = getSeat(seat.getIndex()); if (currentSeat != null && currentSeat.isOn() && seat.getStatus() == Status.INIT && seat.getReason() == VoiceRoomSeat.Reason.CANCEL_APPLY) { if (!anchorMode){ audience.initSeats(seats); } return; } if (anchorMode) { if (anchor.seatChange(seat)) { updateSeat(seat); } } else { updateSeat(seat); audience.seatChange(seat); } } } } private void sendRoomEvent(List<String> nicks, boolean enter) { if (nicks == null || nicks.isEmpty()) { return; } for (String nick : nicks) { VoiceRoomMessage message = VoiceRoomMessage.createEventMessage( getMessageTextBuilder().roomEvent(nick, enter)); if (roomCallback != null) { roomCallback.onVoiceRoomMessage(message); } } } private void updateSeats(@NonNull List<VoiceRoomSeat> seats) { this.seats.clear(); this.seats.addAll(seats); if (roomCallback != null) { roomCallback.updateSeats(this.seats); } } private void updateVolumes(Map<Long, Integer> volumes) { if (roomCallback != null) { boolean enable = !isLocalAudioMute() && !isRoomAudioMute(); roomCallback.onAnchorVolume(enable ? getVolume(volumes, voiceRoomInfo.getCreatorAccount()) : 0); for (VoiceRoomSeat seat : seats) { roomCallback.onSeatVolume(seat, enable && seat.getStatus() == Status.ON ? getVolume(volumes, seat.getAccount()) : 0); } } } private void sendMessage(String text, boolean event) { if (voiceRoomInfo == null) { return; } ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage( voiceRoomInfo.getRoomId(), text); if (event) { Map<String, Object> remoteExtension = new HashMap<>(); remoteExtension.put(ChatRoomMsgExtKey.KEY_TYPE, ChatRoomMsgExtKey.TYPE_EVENT); message.setRemoteExtension(remoteExtension); } chatRoomService.sendMessage(message, false); if (roomCallback != null) { VoiceRoomMessage msg = event ? VoiceRoomMessage.createEventMessage(text) : VoiceRoomMessage.createTextMessage(user.nick, text); roomCallback.onVoiceRoomMessage(msg); } } private static int getVolume(Map<Long, Integer> volumes, String account) { long uid = accountToVoiceUid(account); if (uid <= 0) { return 0; } Integer volume = volumes.get(uid); return volume != null ? volume : 0; } public static Boolean isAnchorMute(ChatRoomInfo chatRoomInfo) { Map<String, Object> extension = chatRoomInfo.getExtension(); Object value = extension != null ? extension.get(ChatRoomInfoExtKey.ANCHOR_MUTE) : null; return value instanceof Integer ? (Integer) value == 1 : null; } public static Boolean isAnchorMute(ChatRoomNotificationAttachment attachment) { Map<String, Object> extension = attachment.getExtension(); Object value = extension != null ? extension.get(ChatRoomInfoExtKey.ANCHOR_MUTE) : null; return value instanceof Integer ? (Integer) value == 1 : null; } public static boolean isEventMessage(ChatRoomMessage message) { if (message.getMsgType() != MsgTypeEnum.text) { return false; } Map<String, Object> remoteExtension = message.getRemoteExtension(); Object value = remoteExtension != null ? remoteExtension.get(ChatRoomMsgExtKey.KEY_TYPE) : null; return value instanceof Integer && (Integer) value == ChatRoomMsgExtKey.TYPE_EVENT; } private static List<VoiceRoomSeat> createSeats() { int size = VoiceRoomSeat.SEAT_COUNT; List<VoiceRoomSeat> seats = new ArrayList<>(size); for (int i = 0; i < size; i++) { seats.add(new VoiceRoomSeat(i)); } return seats; } private static void fillSeats(@NonNull List<Entry<String, String>> entries, @NonNull List<VoiceRoomSeat> seats) { for (Entry<String, String> entry : entries) { if (!VoiceRoomSeat.isValidKey(entry.key)) { continue; } if (TextUtils.isEmpty(entry.value)) { continue; } VoiceRoomSeat seat = VoiceRoomSeat.fromJson(entry.value); if (seat == null) { continue; } int index = seat.getIndex(); if (index >= 0 && index < seats.size()) { seats.set(seat.getIndex(), seat); } } } private static AccountMapper accountMapper; private static long accountToVoiceUid(String account) { return accountMapper != null ? accountMapper.accountToVoiceUid(account) : -1; } public static void setAccountMapper(AccountMapper mapper) { accountMapper = mapper; } private static VoiceRoomMessage.MessageTextBuilder messageTextBuilder; public static VoiceRoomMessage.MessageTextBuilder getMessageTextBuilder() { if (messageTextBuilder != null) { return messageTextBuilder; } return VoiceRoomMessage.getDefaultMessageTextBuilder(); } public static void setMessageTextBuilder(VoiceRoomMessage.MessageTextBuilder messageTextBuilder) { NERtcVoiceRoomImpl.messageTextBuilder = messageTextBuilder; } }
3e154bb19c54b15ff7522dc86641570be3c45dd7
2,420
java
Java
Source/JNA/waffle-jna/src/main/java/waffle/windows/auth/impl/WindowsSecurityContextImpersonationContextImpl.java
amergey/waffle
0a0e6aa0a87b8753a72f1a4083a485d70e49faee
[ "MIT" ]
231
2016-11-23T14:52:42.000Z
2022-03-31T07:05:45.000Z
Source/JNA/waffle-jna/src/main/java/waffle/windows/auth/impl/WindowsSecurityContextImpersonationContextImpl.java
amergey/waffle
0a0e6aa0a87b8753a72f1a4083a485d70e49faee
[ "MIT" ]
310
2016-11-23T12:43:33.000Z
2022-03-29T23:12:13.000Z
Source/JNA/waffle-jna/src/main/java/waffle/windows/auth/impl/WindowsSecurityContextImpersonationContextImpl.java
PhaseEight/waffle
908df4729a5c300582b804abb237a1e7a4179253
[ "MIT" ]
104
2016-11-24T07:22:49.000Z
2022-03-22T02:05:06.000Z
36.666667
112
0.728099
9,044
/* * MIT License * * Copyright (c) 2010-2020 The Waffle Project Contributors: https://github.com/Waffle/waffle/graphs/contributors * * 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 waffle.windows.auth.impl; import com.sun.jna.platform.win32.Secur32; import com.sun.jna.platform.win32.Sspi.CtxtHandle; import com.sun.jna.platform.win32.Win32Exception; import com.sun.jna.platform.win32.WinError; import waffle.windows.auth.IWindowsImpersonationContext; /** * The Class WindowsSecurityContextImpersonationContextImpl. * * @author dblock[at]dblock[dot]org */ public class WindowsSecurityContextImpersonationContextImpl implements IWindowsImpersonationContext { /** The ctx. */ private final CtxtHandle ctx; /** * Instantiates a new windows security context impersonation context impl. * * @param newCtx * the new ctx */ public WindowsSecurityContextImpersonationContextImpl(final CtxtHandle newCtx) { final int rc = Secur32.INSTANCE.ImpersonateSecurityContext(newCtx); if (rc != WinError.SEC_E_OK) { throw new Win32Exception(rc); } this.ctx = newCtx; } @Override public void revertToSelf() { final int rc = Secur32.INSTANCE.RevertSecurityContext(this.ctx); if (rc != WinError.SEC_E_OK) { throw new Win32Exception(rc); } } }
3e154cd00bd4be6935edc0cac734b1df2073f207
783
java
Java
src/sudoku/state/model/UndoActionState.java
jhayn94/Sudoku
6c00a0416bbd9b278fd54f95c9590cf85c91e6df
[ "Unlicense" ]
null
null
null
src/sudoku/state/model/UndoActionState.java
jhayn94/Sudoku
6c00a0416bbd9b278fd54f95c9590cf85c91e6df
[ "Unlicense" ]
null
null
null
src/sudoku/state/model/UndoActionState.java
jhayn94/Sudoku
6c00a0416bbd9b278fd54f95c9590cf85c91e6df
[ "Unlicense" ]
null
null
null
29
102
0.786718
9,045
package sudoku.state.model; import sudoku.model.SudokuPuzzleValues; /** * This class updates the state of the application when the user invokes an * "undo", either through the keyboard or a button press in the UI. */ public class UndoActionState extends ResetFromModelState { public UndoActionState(final ApplicationModelState lastState) { super(lastState, false); } @Override public void onEnter() { if (!this.applicationStateHistory.isUndoStackEmpty()) { final SudokuPuzzleValues puzzleStateForUndo = this.applicationStateHistory.getPuzzleStateForUndo(); this.applicationStateHistory.addToRedoStack(this.sudokuPuzzleValues); this.sudokuPuzzleValues = puzzleStateForUndo; this.resetApplicationFromPuzzleState(); this.updateUndoRedoButtons(); } } }
3e154d4787fbc871818ee0fb2e1a3b027e387d5c
1,193
java
Java
samples/testsuite-xlt/src/scripting/testcases/assertNotVisible.java
andre-becker/XLT
174f9f467ab3094bcdbf80bcea818134a9d1180a
[ "Apache-2.0" ]
null
null
null
samples/testsuite-xlt/src/scripting/testcases/assertNotVisible.java
andre-becker/XLT
174f9f467ab3094bcdbf80bcea818134a9d1180a
[ "Apache-2.0" ]
null
null
null
samples/testsuite-xlt/src/scripting/testcases/assertNotVisible.java
andre-becker/XLT
174f9f467ab3094bcdbf80bcea818134a9d1180a
[ "Apache-2.0" ]
null
null
null
22.509434
78
0.662196
9,046
package scripting.testcases; import org.junit.After; import org.junit.Test; import com.xceptance.xlt.api.webdriver.XltDriver; import com.xceptance.xlt.api.engine.scripting.AbstractWebDriverScriptTestCase; import scripting.modules.Open_ExamplePage; /** * TODO: Add class description */ public class assertNotVisible extends AbstractWebDriverScriptTestCase { /** * Constructor. */ public assertNotVisible() { super(new XltDriver(true), "http://localhost:8080/"); } /** * Executes the test. * * @throws Throwable if anything went wrong */ @Test public void test() throws Throwable { final Open_ExamplePage _open_ExamplePage = new Open_ExamplePage(); _open_ExamplePage.execute(); assertNotVisible("id=in_visible_anchor_inv"); assertNotVisible("id=invisible_visibility"); assertNotVisible("id=invisible_visibility_style"); assertNotVisible("id=invisible_display"); assertNotVisible("id=invisible_hidden_input"); } /** * Clean up. */ @After public void after() { // Shutdown WebDriver. getWebDriver().quit(); } }
3e154db895c96e716399c136926d320ff1873c32
2,155
java
Java
supplier-api/src/main/java/co/yixiang/app/modular/member/service/impl/MemberServiceImpl.java
guchengwuyue/supplierShop
d95d3b792a8ee4e4d4efa4234acd20da94bd3c2c
[ "MIT" ]
142
2019-10-15T03:25:10.000Z
2022-03-25T16:04:24.000Z
supplier-api/src/main/java/co/yixiang/app/modular/member/service/impl/MemberServiceImpl.java
guchengwuyue/supplierShop
d95d3b792a8ee4e4d4efa4234acd20da94bd3c2c
[ "MIT" ]
7
2019-10-25T02:03:19.000Z
2022-02-11T09:04:22.000Z
supplier-api/src/main/java/co/yixiang/app/modular/member/service/impl/MemberServiceImpl.java
guchengwuyue/supplierShop
d95d3b792a8ee4e4d4efa4234acd20da94bd3c2c
[ "MIT" ]
71
2019-10-17T07:48:25.000Z
2022-03-01T09:51:41.000Z
37.155172
112
0.761021
9,047
package co.yixiang.app.modular.member.service.impl; import co.yixiang.app.common.persistence.dao.StoreCouponMapper; import co.yixiang.app.common.persistence.dao.StoreMemberMapper; import co.yixiang.app.common.persistence.model.StoreMember; import co.yixiang.app.modular.member.service.IMemberService; import co.yixiang.app.modular.shop.service.dto.CouponDTO; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import co.yixiang.app.common.persistence.dao.StoreCouponMapper; import co.yixiang.app.common.persistence.dao.StoreMemberMapper; import co.yixiang.app.common.persistence.model.StoreMember; import co.yixiang.app.modular.member.service.IMemberService; import co.yixiang.app.modular.member.service.dto.MemberDTO; import co.yixiang.app.modular.member.service.mapper.MemberMapper; import co.yixiang.app.modular.shop.service.dto.CouponDTO; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class MemberServiceImpl extends ServiceImpl<StoreMemberMapper, StoreMember> implements IMemberService { private final StoreMemberMapper storeMemberMapper; private final MemberMapper memberMapper; private final StoreCouponMapper storeCouponMapper; @Override public StoreMember login(String openid) { // 根据登陆账号获取数据库信息 StoreMember result = storeMemberMapper .selectOne(new QueryWrapper<StoreMember>().lambda() .eq(StoreMember::getOpenid, openid)); return result; //return null; } @Override public List<MemberDTO> memeberList() { return memberMapper.toDto(storeMemberMapper.selectList(null)); } @Override public List<CouponDTO> couponList(int userId, double orderTotalPrice) { return storeCouponMapper.couponList(userId,orderTotalPrice); } }
3e154dedb01f683c9fdfd7e910b7ca78716866cb
2,083
java
Java
core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java
hendisantika/spring-ldap
f6e01d895a7b7d94ffa83265d1e4b542bd93bf01
[ "Apache-2.0" ]
1
2017-02-22T04:10:15.000Z
2017-02-22T04:10:15.000Z
core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java
wilkinsona/spring-ldap
8f497aa8cdf0123a10496c9feee953beb0343f07
[ "Apache-2.0" ]
null
null
null
core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java
wilkinsona/spring-ldap
8f497aa8cdf0123a10496c9feee953beb0343f07
[ "Apache-2.0" ]
1
2019-07-07T05:33:08.000Z
2019-07-07T05:33:08.000Z
34.147541
75
0.714834
9,048
/* * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.ldap.filter; import com.gargoylesoftware.base.testing.EqualsTester; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Unit tests for the HardcodedFilter class. * * @author Ulrik Sandberg */ public class HardcodedFilterTest { @Test public void testHardcodedFilter() { HardcodedFilter filter = new HardcodedFilter("(foo=a*b)"); assertEquals("(foo=a*b)", filter.encode()); NotFilter notFilter = new NotFilter(new HardcodedFilter("(foo=a*b)")); assertEquals("(!(foo=a*b))", notFilter.encode()); AndFilter andFilter = new AndFilter(); andFilter.and(new HardcodedFilter("(foo=a*b)")); andFilter.and(new HardcodedFilter("(bar=a*b)")); assertEquals("(&(foo=a*b)(bar=a*b))", andFilter.encode()); andFilter = new AndFilter(); andFilter.and(new HardcodedFilter("(foo=a*b)")); andFilter.and(new NotFilter(new HardcodedFilter("(bar=a*b)"))); assertEquals("(&(foo=a*b)(!(bar=a*b)))", andFilter.encode()); } @Test public void testEquals() { String attribute = "(foo=a*b)"; HardcodedFilter originalObject = new HardcodedFilter(attribute); HardcodedFilter identicalObject = new HardcodedFilter(attribute); HardcodedFilter differentObject = new HardcodedFilter("(bar=a*b)"); HardcodedFilter subclassObject = new HardcodedFilter(attribute) { }; new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } }
3e154df621ae2873c55a64bad9b9191959fbe9d0
3,893
java
Java
aliyun-java-sdk-rds-v5/src/main/java/com/aliyuncs/v5/rds/model/v20140815/ModifyDBInstanceTDERequest.java
aliyun/aliyun-openapi-java-sdk-v5
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
[ "Apache-2.0" ]
4
2020-05-14T05:04:30.000Z
2021-08-20T11:08:46.000Z
aliyun-java-sdk-rds-v5/src/main/java/com/aliyuncs/v5/rds/model/v20140815/ModifyDBInstanceTDERequest.java
aliyun/aliyun-openapi-java-sdk-v5
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
[ "Apache-2.0" ]
2
2020-10-13T07:47:10.000Z
2021-06-04T02:42:57.000Z
aliyun-java-sdk-rds-v5/src/main/java/com/aliyuncs/v5/rds/model/v20140815/ModifyDBInstanceTDERequest.java
aliyun/aliyun-openapi-java-sdk-v5
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
[ "Apache-2.0" ]
null
null
null
24.484277
121
0.725918
9,049
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.v5.rds.model.v20140815; import com.aliyuncs.v5.RpcAcsRequest; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.rds.Endpoint; /** * @author auto create * @version */ public class ModifyDBInstanceTDERequest extends RpcAcsRequest<ModifyDBInstanceTDEResponse> { private Long resourceOwnerId; private String dBInstanceId; private String resourceOwnerAccount; private String ownerAccount; private String encryptionKey; private Long ownerId; private String dBName; private String roleArn; private String tDEStatus; public ModifyDBInstanceTDERequest() { super("Rds", "2014-08-15", "ModifyDBInstanceTDE", "rds"); setMethod(MethodType.POST); try { com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public Long getResourceOwnerId() { return this.resourceOwnerId; } public void setResourceOwnerId(Long resourceOwnerId) { this.resourceOwnerId = resourceOwnerId; if(resourceOwnerId != null){ putQueryParameter("ResourceOwnerId", resourceOwnerId.toString()); } } public String getDBInstanceId() { return this.dBInstanceId; } public void setDBInstanceId(String dBInstanceId) { this.dBInstanceId = dBInstanceId; if(dBInstanceId != null){ putQueryParameter("DBInstanceId", dBInstanceId); } } public String getResourceOwnerAccount() { return this.resourceOwnerAccount; } public void setResourceOwnerAccount(String resourceOwnerAccount) { this.resourceOwnerAccount = resourceOwnerAccount; if(resourceOwnerAccount != null){ putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount); } } public String getOwnerAccount() { return this.ownerAccount; } public void setOwnerAccount(String ownerAccount) { this.ownerAccount = ownerAccount; if(ownerAccount != null){ putQueryParameter("OwnerAccount", ownerAccount); } } public String getEncryptionKey() { return this.encryptionKey; } public void setEncryptionKey(String encryptionKey) { this.encryptionKey = encryptionKey; if(encryptionKey != null){ putQueryParameter("EncryptionKey", encryptionKey); } } public Long getOwnerId() { return this.ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; if(ownerId != null){ putQueryParameter("OwnerId", ownerId.toString()); } } public String getDBName() { return this.dBName; } public void setDBName(String dBName) { this.dBName = dBName; if(dBName != null){ putQueryParameter("DBName", dBName); } } public String getRoleArn() { return this.roleArn; } public void setRoleArn(String roleArn) { this.roleArn = roleArn; if(roleArn != null){ putQueryParameter("RoleArn", roleArn); } } public String getTDEStatus() { return this.tDEStatus; } public void setTDEStatus(String tDEStatus) { this.tDEStatus = tDEStatus; if(tDEStatus != null){ putQueryParameter("TDEStatus", tDEStatus); } } @Override public Class<ModifyDBInstanceTDEResponse> getResponseClass() { return ModifyDBInstanceTDEResponse.class; } }
3e154e2d4704500abf48aff6810d579d0d307f63
4,567
java
Java
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/CacheLoadAllCodec.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
4,283
2015-01-02T03:56:10.000Z
2022-03-29T23:07:45.000Z
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/CacheLoadAllCodec.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
14,014
2015-01-01T04:29:38.000Z
2022-03-31T21:47:55.000Z
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/CacheLoadAllCodec.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
1,608
2015-01-04T09:57:08.000Z
2022-03-31T12:05:26.000Z
43.495238
171
0.752354
9,050
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl.protocol.codec; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.Generated; import com.hazelcast.client.impl.protocol.codec.builtin.*; import com.hazelcast.client.impl.protocol.codec.custom.*; import javax.annotation.Nullable; import static com.hazelcast.client.impl.protocol.ClientMessage.*; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*; /* * This file is auto-generated by the Hazelcast Client Protocol Code Generator. * To change this file, edit the templates or the protocol * definitions on the https://github.com/hazelcast/hazelcast-client-protocol * and regenerate it. */ /** * Loads all the keys into the CacheRecordStore in batch. */ @Generated("276ff1e19e0494bd2fbefacbdf33ba85") public final class CacheLoadAllCodec { //hex: 0x131000 public static final int REQUEST_MESSAGE_TYPE = 1249280; //hex: 0x131001 public static final int RESPONSE_MESSAGE_TYPE = 1249281; private static final int REQUEST_REPLACE_EXISTING_VALUES_FIELD_OFFSET = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES; private static final int REQUEST_INITIAL_FRAME_SIZE = REQUEST_REPLACE_EXISTING_VALUES_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES; private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES; private CacheLoadAllCodec() { } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}) public static class RequestParameters { /** * Name of the cache. */ public java.lang.String name; /** * the keys to load */ public java.util.List<com.hazelcast.internal.serialization.Data> keys; /** * when true existing values in the Cache will * be replaced by those loaded from a CacheLoader */ public boolean replaceExistingValues; } public static ClientMessage encodeRequest(java.lang.String name, java.util.Collection<com.hazelcast.internal.serialization.Data> keys, boolean replaceExistingValues) { ClientMessage clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(false); clientMessage.setOperationName("Cache.LoadAll"); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE); encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1); encodeBoolean(initialFrame.content, REQUEST_REPLACE_EXISTING_VALUES_FIELD_OFFSET, replaceExistingValues); clientMessage.add(initialFrame); StringCodec.encode(clientMessage, name); ListMultiFrameCodec.encode(clientMessage, keys, DataCodec::encode); return clientMessage; } public static CacheLoadAllCodec.RequestParameters decodeRequest(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); RequestParameters request = new RequestParameters(); ClientMessage.Frame initialFrame = iterator.next(); request.replaceExistingValues = decodeBoolean(initialFrame.content, REQUEST_REPLACE_EXISTING_VALUES_FIELD_OFFSET); request.name = StringCodec.decode(iterator); request.keys = ListMultiFrameCodec.decode(iterator, DataCodec::decode); return request; } public static ClientMessage encodeResponse() { ClientMessage clientMessage = ClientMessage.createForEncode(); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE); clientMessage.add(initialFrame); return clientMessage; } }
3e154eb1aeef0e92ba17264772c76e11458fb38d
994
java
Java
src/main/java/com/moon/poi/excel/LoadUtil.java
moon-util/moon-util
28c5cb418861da4d0a5a035a3de919b86b939c0e
[ "MIT" ]
5
2019-04-30T09:23:32.000Z
2022-01-04T05:28:43.000Z
src/main/java/com/moon/poi/excel/LoadUtil.java
moon-util/moon-util
28c5cb418861da4d0a5a035a3de919b86b939c0e
[ "MIT" ]
7
2020-09-08T07:47:18.000Z
2022-01-04T16:47:25.000Z
src/main/java/com/moon/poi/excel/LoadUtil.java
moon-util/moon-util
28c5cb418861da4d0a5a035a3de919b86b939c0e
[ "MIT" ]
1
2022-01-04T05:28:49.000Z
2022-01-04T05:28:49.000Z
22.590909
79
0.617706
9,051
package com.moon.poi.excel; import java.io.File; import java.util.Optional; /** * @author moonsky */ abstract class LoadUtil { protected LoadUtil() { } /** * 推测 Excel 文件类型 * * @param absoluteExcelFile excel 文件 * * @return excel 文件类型 * * @throws NullPointerException absoluteExcelFile is null */ final static Optional<ExcelType> deduceType(File absoluteExcelFile) { return deduceType(absoluteExcelFile.getAbsolutePath()); } /** * 推测绝对路径指向的 Excel 文件类型 * * @param absoluteExcelFilepath excel 文件绝对路径 * * @return excel 文件类型 * * @throws NullPointerException absoluteExcelFilepath is null */ final static Optional<ExcelType> deduceType(String absoluteExcelFilepath) { for (ExcelType value : ExcelType.values()) { if (value.test(absoluteExcelFilepath)) { return Optional.of(value); } } return Optional.empty(); } }
3e154ecc7ab7a1a459aab5877d0e46606480352f
1,016
java
Java
Benchmarks_with_Safety_Bugs/Java/tiles/src/tiles-core/src/main/java/org/apache/tiles/definition/package-info.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Safety_Bugs/Java/tiles/src/tiles-core/src/main/java/org/apache/tiles/definition/package-info.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Safety_Bugs/Java/tiles/src/tiles-core/src/main/java/org/apache/tiles/definition/package-info.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
2
2020-11-26T13:27:14.000Z
2022-03-20T02:12:55.000Z
39.076923
83
0.747047
9,052
/* * $Id$ * * 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. */ /** * It contains classes and interfaces to allow manipulations of "definitions", i.e. * objects made of a template page and a number of filled attributes. */ package org.apache.tiles.definition;
3e154f3c0670ff136ee668e5fb0693ae6ac2f26b
1,950
java
Java
leetcode/src/main/java/com/db117/example/leetcode/office/Offer_25.java
db117/example
687296375fb0be2d1c2bb6ec882d0e17710e70d9
[ "Apache-2.0" ]
2
2019-07-05T08:31:16.000Z
2019-07-05T08:31:24.000Z
leetcode/src/main/java/com/db117/example/leetcode/office/Offer_25.java
db117/example
687296375fb0be2d1c2bb6ec882d0e17710e70d9
[ "Apache-2.0" ]
null
null
null
leetcode/src/main/java/com/db117/example/leetcode/office/Offer_25.java
db117/example
687296375fb0be2d1c2bb6ec882d0e17710e70d9
[ "Apache-2.0" ]
null
null
null
23.780488
78
0.508718
9,053
//输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。 // // 示例1: // // 输入:1->2->4, 1->3->4 //输出:1->1->2->3->4->4 // // 限制: // // 0 <= 链表长度 <= 1000 // // 注意:本题与主站 21 题相同:https://leetcode-cn.com/problems/merge-two-sorted-lists/ // Related Topics 分治算法 // 👍 76 👎 0 package com.db117.example.leetcode.office; import com.db117.example.leetcode.util.ListNode; import com.db117.example.leetcode.util.ListNodeUtil; /** * 剑指 Offer 25.合并两个排序的链表.he-bing-liang-ge-pai-xu-de-lian-biao-lcof * * @author db117 * @since 2021-01-13 14:09:27 **/ public class Offer_25 { public static void main(String[] args) { Solution solution = new Offer_25().new Solution(); ListNode node = solution.mergeTwoLists(ListNodeUtil.builder(new int[]{ 1, 3, 5, 7, 7, 9, 90 }), ListNodeUtil.builder(new int[]{ 4, 6, 7, 8, 8, 9, 9, 40 })); ListNodeUtil.print(node); } //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // 伪头结点 ListNode head = new ListNode(0); // 当前结点 ListNode cur = head; // 当前结点的下一个结点指向最小的 while (l1 != null || l2 != null) { if (l1 == null) { cur.next = l2; l2 = l2.next; } else if (l2 == null || l1.val <= l2.val) { cur.next = l1; l1 = l1.next; } else { cur.next = l2; l2 = l2.next; } cur = cur.next; } return head.next; } } //leetcode submit region end(Prohibit modification and deletion) }
3e154f3d669697c07884a695aecc2069bd36f278
1,844
java
Java
src/wanda/data/Config_Factory.java
CapsicoHealth/Wanda
3c5c0a12302581f408046bbef6b5d10afe8a7629
[ "Apache-2.0" ]
null
null
null
src/wanda/data/Config_Factory.java
CapsicoHealth/Wanda
3c5c0a12302581f408046bbef6b5d10afe8a7629
[ "Apache-2.0" ]
27
2020-11-30T06:27:48.000Z
2022-02-03T17:38:43.000Z
src/wanda/data/Config_Factory.java
CapsicoHealth/WandA-X
4e284e3b7f19713c934735d3671149d14b49a961
[ "Apache-2.0" ]
null
null
null
36.88
122
0.543926
9,054
/* =========================================================================== * Copyright (C) 2017 CapsicoHealth Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Tilda V1.0 template application class. */ package wanda.data; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tilda.db.*; /** This is the application class <B>Data_Config</B> mapped to the table <B>PEOPLE.Config</B>. @see wanda.data._Tilda.TILDA__CONFIG */ public class Config_Factory extends wanda.data._Tilda.TILDA__CONFIG_Factory { protected static final Logger LOG = LogManager.getLogger(Config_Factory.class.getName()); protected Config_Factory() { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Implement your customizations, if any, below. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void init(Connection C) throws Exception { // Add logic to initialize your object, for example, caching some values, or validating some things. } }
3e154fd7b7a304eebc8aa4f991599fb0ceb45739
2,387
java
Java
src/main/java/com/refinedmods/refinedpipes/block/FluidPipeBlock.java
d-l-n/refinedpipes
823bedef0b8764a35074e8135280ce2498dae742
[ "MIT" ]
15
2020-06-01T00:39:40.000Z
2022-02-26T19:29:32.000Z
src/main/java/com/refinedmods/refinedpipes/block/FluidPipeBlock.java
d-l-n/refinedpipes
823bedef0b8764a35074e8135280ce2498dae742
[ "MIT" ]
92
2020-05-29T18:52:25.000Z
2022-03-28T10:27:58.000Z
src/main/java/com/refinedmods/refinedpipes/block/FluidPipeBlock.java
d-l-n/refinedpipes
823bedef0b8764a35074e8135280ce2498dae742
[ "MIT" ]
27
2020-05-29T17:10:09.000Z
2022-01-30T14:59:45.000Z
34.594203
126
0.727692
9,055
package com.refinedmods.refinedpipes.block; import com.refinedmods.refinedpipes.network.pipe.fluid.FluidPipeType; import com.refinedmods.refinedpipes.network.pipe.shape.PipeShapeCache; import com.refinedmods.refinedpipes.tile.FluidPipeTileEntity; import net.minecraft.block.BlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockReader; import net.minecraft.world.IWorld; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import javax.annotation.Nullable; public class FluidPipeBlock extends PipeBlock { private final FluidPipeType type; public FluidPipeBlock(PipeShapeCache shapeCache, FluidPipeType type) { super(shapeCache); this.type = type; this.setRegistryName(type.getId()); } public FluidPipeType getType() { return type; } @Override public boolean hasTileEntity(BlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) { return new FluidPipeTileEntity(type); } @Override protected boolean hasConnection(IWorld world, BlockPos pos, Direction direction) { TileEntity currentTile = world.getTileEntity(pos); if (currentTile instanceof FluidPipeTileEntity && ((FluidPipeTileEntity) currentTile).getAttachmentManager().hasAttachment(direction)) { return false; } BlockState facingState = world.getBlockState(pos.offset(direction)); TileEntity facingTile = world.getTileEntity(pos.offset(direction)); if (facingTile instanceof FluidPipeTileEntity && ((FluidPipeTileEntity) facingTile).getAttachmentManager().hasAttachment(direction.getOpposite())) { return false; } return facingState.getBlock() instanceof FluidPipeBlock && ((FluidPipeBlock) facingState.getBlock()).getType() == type; } @Override protected boolean hasInvConnection(IWorld world, BlockPos pos, Direction direction) { TileEntity facingTile = world.getTileEntity(pos.offset(direction)); return facingTile != null && facingTile.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, direction.getOpposite()).isPresent(); } }
3e154ff8069cd9ae56b4148cef1d7f3341f0da6a
520
java
Java
src/main/java/frc/robot/commands/CMD_SetLed.java
team6002/LedTest
8539a3c80c5deda657c4faa56fa36e20310a5893
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/CMD_SetLed.java
team6002/LedTest
8539a3c80c5deda657c4faa56fa36e20310a5893
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/CMD_SetLed.java
team6002/LedTest
8539a3c80c5deda657c4faa56fa36e20310a5893
[ "BSD-3-Clause" ]
1
2022-01-26T00:56:30.000Z
2022-01-26T00:56:30.000Z
17.931034
55
0.651923
9,056
package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.SUB_LED; public class CMD_SetLed extends CommandBase { private SUB_LED m_led; private double m_setColor; public CMD_SetLed(SUB_LED p_led, double p_setColor) { m_led = p_led; m_setColor = p_setColor; } @Override public void initialize() { m_led.set(m_setColor); } @Override public boolean isFinished() { return true; } }
3e15506063bbd6c5610f94b5a26dfae353fa2d81
1,792
java
Java
src/main/java/com/smartdoc/gradle/constant/GlobalConstants.java
hwck/smart-doc-gradle-plugin
cf930cc535ca777a11b67349c890094a38de7ec0
[ "Apache-2.0" ]
4
2021-04-01T18:11:23.000Z
2021-10-31T08:19:56.000Z
src/main/java/com/smartdoc/gradle/constant/GlobalConstants.java
hwck/smart-doc-gradle-plugin
cf930cc535ca777a11b67349c890094a38de7ec0
[ "Apache-2.0" ]
4
2021-05-25T02:09:46.000Z
2022-03-01T09:08:09.000Z
src/main/java/com/smartdoc/gradle/constant/GlobalConstants.java
hwck/smart-doc-gradle-plugin
cf930cc535ca777a11b67349c890094a38de7ec0
[ "Apache-2.0" ]
4
2021-04-29T01:59:55.000Z
2021-12-12T03:03:06.000Z
29.377049
96
0.732701
9,057
/* * smart-doc https://github.com/shalousun/smart-doc * * Copyright (C) 2018-2021 smart-doc * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.smartdoc.gradle.constant; /** * @author yu 2019/12/13. */ public interface GlobalConstants { String ERROR_MSG = "Failed to build ApiConfig, check if the configuration file is correct."; String DEFAULT_CONFIG = "./src/main/resources/default.json"; String TASK_GROUP = "Documentation"; String REST_HTML_TASK = "smartDocRestHtml"; String REST_ADOC_TASK = "smartDocRestAdoc"; String REST_MARKDOWN_TASK = "smartDocRestMarkdown"; String POSTMAN_TASK = "smartDocPostman"; String OPEN_API_TASK = "smartDocOpenApi"; String RPC_HTML_TASK = "smartDocRpcHtml"; String RPC_ADOC_TASK = "smartDocRpcAdoc"; String RPC_MARKDOWN_TASK = "smartDocRpcMarkdown"; String TORNA_REST_TASK = "tornaRest"; String TORNA_RPC_TASK = "tornaRpc"; String EXTENSION_NAME = "smartdoc"; String SRC_MAIN_JAVA_PATH = "src/main/java"; }
3e1550b7f972f04f77cbef67fdfd2c16e4a765af
10,410
java
Java
Projects/LIBRARY_2/src/library_2/MY_ACCOUNT.java
DarkDeveloperz/My_Projects
4b534435c5a2aef1e730e8e5d9d45bbf238e5b28
[ "MIT" ]
null
null
null
Projects/LIBRARY_2/src/library_2/MY_ACCOUNT.java
DarkDeveloperz/My_Projects
4b534435c5a2aef1e730e8e5d9d45bbf238e5b28
[ "MIT" ]
null
null
null
Projects/LIBRARY_2/src/library_2/MY_ACCOUNT.java
DarkDeveloperz/My_Projects
4b534435c5a2aef1e730e8e5d9d45bbf238e5b28
[ "MIT" ]
null
null
null
33.908795
153
0.604131
9,058
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package library_2; import java.awt.Toolkit; import java.sql.*; import javax.swing.ImageIcon; import java.util.Calendar; import javax.swing.JOptionPane; import static library_2.LIBRARY_2.audio; /** * * @author akash */ public class MY_ACCOUNT extends javax.swing.JFrame { public static String s9; /** * Creates new form MY_ACCOUNT */ public MY_ACCOUNT() { initComponents(); setIcon(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); ta1 = new javax.swing.JTextArea(); lb3 = new javax.swing.JLabel(); lb1 = new javax.swing.JLabel(); lb2 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setLocation(new java.awt.Point(400, 150)); setMinimumSize(new java.awt.Dimension(560, 515)); setUndecorated(true); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); getContentPane().setLayout(null); jButton1.setFont(new java.awt.Font("DigifaceWide", 3, 14)); // NOI18N jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/library_2/color.png"))); // NOI18N jButton1.setText("BACK"); jButton1.setBorder(null); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(10, 488, 245, 20); ta1.setBackground(new java.awt.Color(204, 204, 255)); ta1.setColumns(20); ta1.setRows(5); jScrollPane1.setViewportView(ta1); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(10, 106, 533, 373); getContentPane().add(lb3); lb3.setBounds(411, 11, 132, 77); lb1.setFont(new java.awt.Font("DigifaceWide", 3, 12)); // NOI18N getContentPane().add(lb1); lb1.setBounds(10, 28, 252, 16); lb2.setFont(new java.awt.Font("DigifaceWide", 3, 12)); // NOI18N getContentPane().add(lb2); lb2.setBounds(10, 62, 252, 20); jButton2.setFont(new java.awt.Font("DigifaceWide", 3, 14)); // NOI18N jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/library_2/exit.png"))); // NOI18N jButton2.setText("LOGOUT"); jButton2.setBorder(null); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(294, 488, 249, 20); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/library_2/2.png"))); // NOI18N jLabel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { jLabel1MouseDragged(evt); } }); getContentPane().add(jLabel1); jLabel1.setBounds(0, 0, 600, 520); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed setVisible(false) ; audio(32); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SELECT().setVisible(true); } }); }//GEN-LAST:event_jButton1ActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened try { audio(16); if(LOGIN_AS.c==1) { try { String s1,s2,s3,s4; s1=STUDENT_LOGIN_2.tf1.getText(); ImageIcon format; ResultSet rs=LIBRARY_2.stmt.executeQuery("select * from STUDENT_REG_NO"); while(rs.next()) { s2=rs.getString("REG_NO"); s3=rs.getString("NAME"); if(s1.equals(s2)) { lb1.setText(s3); lb2.setText(STUDENT_LOGIN_2.tf1.getText()); byte [] imagedata = rs.getBytes("pic"); format = new ImageIcon(imagedata); lb3.setIcon(format); } } } catch (Exception e) { } } if(LOGIN_AS.c==2) { try { String s1,s2,s3,s4; s1=STUDENT_LOGIN_2.tf1.getText(); ImageIcon format; ResultSet rs=LIBRARY_2.stmt.executeQuery("select * from TEACHER_REG_NO"); while(rs.next()) { s2=rs.getString("REG_NO"); s3=rs.getString("NAME"); if(s1.equals(s2)) { lb1.setText(s3); lb2.setText(STUDENT_LOGIN_2.tf1.getText()); byte [] imagedata = rs.getBytes("pic"); format = new ImageIcon(imagedata); lb3.setIcon(format); } } } catch (Exception e) { } } byte sa=0; try { String s1=lb2.getText(); ResultSet rs=LIBRARY_2.stmt.executeQuery("select date from issued_book_details where regestration_no='"+s1+"' and type = 'ISSUED' or type = 'RENEWED'"); while(rs.next()) { Date s2=rs.getDate("date"); String s3=rs.getString("regestration_no"); if(s1.equals(s3)) { } } } catch(Exception e) { } try { String s1,s2,s3,s4,s5,s6; String s7; int s8=0; s1=lb2.getText(); s2="ISSUED"; s3="RENEWED"; ResultSet rs=LIBRARY_2.stmt.executeQuery("select * from issued_book_details where regestration_no='"+s1+"' and type = 'ISSUED' or type = 'RENEWED'"); while(rs.next()) { sa++; s4=rs.getString("REGESTRATION_NO"); s5=rs.getString("type"); s6=rs.getString("book_name"); s7=rs.getDate("date").toString(); s9=rs.getString("due_date"); s8=rs.getInt("book_id"); if(s1.equals(s4) &&((s5.equals(s2))|| (s5.equals(s3))) ) { ta1.append("\n-------------------------------------------------------------------------------"); ta1.append("\n SERIAL NUMBER : " +(sa)); ta1.append("\n BOOK NAME : "+(s6)); ta1.append("\n BOOK ID : "+(s8)); ta1.append("\n ISSUE DATE : "+s7); ta1.append("\n DUE DATE : "+s9); ta1.append("\n-------------------------------INFORMATION--------------------------"); ta1.append("\n-------------------------------------------------------------------------------"); } } } catch(Exception e) { } } catch(Exception e) { JOptionPane.showMessageDialog(null,e.getMessage()); } }//GEN-LAST:event_formWindowOpened private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed audio(32); setVisible(false); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LOGIN_AS().setVisible(true); } }); }//GEN-LAST:event_jButton2ActionPerformed private void jLabel1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseDragged this.setLocation(evt.getLocationOnScreen()); // TODO add your handling code here: }//GEN-LAST:event_jLabel1MouseDragged /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MY_ACCOUNT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MY_ACCOUNT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MY_ACCOUNT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MY_ACCOUNT.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MY_ACCOUNT().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lb1; private javax.swing.JLabel lb2; private javax.swing.JLabel lb3; private javax.swing.JTextArea ta1; // End of variables declaration//GEN-END:variables private void setIcon() { setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("icon.png"))); } }
3e1551739415a4ecf2a54e271c1fbb8e83517075
873
java
Java
src/main/java/ca/spottedleaf/concurrentutil/util/CollectionUtil.java
Spottedleaf/ConcurrentUtil
be24a5739438bf513129008241a51939755a9d1d
[ "MIT" ]
8
2019-08-14T22:57:50.000Z
2022-01-01T09:34:45.000Z
src/main/java/ca/spottedleaf/concurrentutil/util/CollectionUtil.java
Spottedleaf/ConcurrentUtil
be24a5739438bf513129008241a51939755a9d1d
[ "MIT" ]
1
2020-03-20T03:27:12.000Z
2020-03-21T04:19:46.000Z
src/main/java/ca/spottedleaf/concurrentutil/util/CollectionUtil.java
Spottedleaf/ConcurrentUtil
be24a5739438bf513129008241a51939755a9d1d
[ "MIT" ]
3
2019-08-20T13:37:31.000Z
2021-08-05T14:17:46.000Z
28.16129
122
0.617411
9,059
package ca.spottedleaf.concurrentutil.util; import java.util.Collection; public final class CollectionUtil { public static String toString(final Collection<?> collection, final String name) { return CollectionUtil.toString(collection, name, new StringBuilder(name.length() + 128)).toString(); } public static StringBuilder toString(final Collection<?> collection, final String name, final StringBuilder builder) { builder.append(name).append(": {elements: {"); boolean first = true; for (final Object element : collection) { if (!first) { builder.append(", "); } first = false; builder.append('"').append(element).append('"'); } return builder.append("}}"); } private CollectionUtil() { throw new RuntimeException(); } }
3e15523bebc3d3ef42dacb27606aa0438e680858
2,619
java
Java
src/server/ee/pri/bcup/server/model/ServerGame.java
rla/bcup
d0b15c3828f00cc9e4688a4b0023207a9a46fdc9
[ "MIT" ]
1
2015-11-08T10:02:27.000Z
2015-11-08T10:02:27.000Z
src/server/ee/pri/bcup/server/model/ServerGame.java
rla/bcup
d0b15c3828f00cc9e4688a4b0023207a9a46fdc9
[ "MIT" ]
null
null
null
src/server/ee/pri/bcup/server/model/ServerGame.java
rla/bcup
d0b15c3828f00cc9e4688a4b0023207a9a46fdc9
[ "MIT" ]
null
null
null
21.120968
81
0.721268
9,060
package ee.pri.bcup.server.model; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import lombok.EqualsAndHashCode; import edu.emory.mathcs.backport.java.util.Arrays; import ee.pri.bcup.common.model.GameType; import ee.pri.bcup.server.dao.Entity; @EqualsAndHashCode(of = "id") public class ServerGame implements Comparable<ServerGame>, Entity { private Long id; private ServerPlayer first; private ServerPlayer second; private List<ServerPlayer> observers = new CopyOnWriteArrayList<ServerPlayer>(); private Long hitTimeout; private Long databaseGameId; private GameType gameType; public ServerGame(ServerPlayer first, ServerPlayer second) { this.first = first; this.second = second; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public ServerPlayer getFirst() { return first; } public ServerPlayer getSecond() { return second; } public List<ServerPlayer> getObservers() { return observers; } public ServerPlayer getOpponent(ServerPlayer player) { if (player.equals(first)) { return second; } else if (player.equals(second)) { return first; } else { return null; } } @SuppressWarnings("unchecked") public List<ServerPlayer> getAll() { List<ServerPlayer> list = new ArrayList<ServerPlayer>(observers); list.addAll(Arrays.asList(new ServerPlayer[] {first, second})); return list; } @Override public int compareTo(ServerGame o) { return id.compareTo(o.id); } public Long getHitTimeout() { return hitTimeout; } public void setHitTimeout(Long hitTimeout) { this.hitTimeout = hitTimeout; } public Long getDatabaseGameId() { return databaseGameId; } public void setDatabaseGameId(Long databaseGameId) { this.databaseGameId = databaseGameId; } /** * Checks whether the given player is observer. */ public boolean isObserver(ServerPlayer player) { return observers.contains(player); } /** * Returns whether the given player takes part in this game * but not as an observer. */ public boolean isPlayer(ServerPlayer player) { return first.equals(player) || second.equals(player); } /** * Removes the given player from the list of * this game observers. */ public void removeObserver(ServerPlayer player) { observers.remove(player); } public GameType getGameType() { return gameType; } public void setGameType(GameType gameType) { this.gameType = gameType; } @Override public String toString() { return "first=" + first + ",second=" + second + ",observers=" + observers; } }
3e155242e5707fccdcb8f0eb7d1cf44f44c55cf2
3,922
java
Java
src/main/java/pl/lijek/veinminer/shapes/Shape.java
lijek/veinminer
80a4588d9cdb7ded56640f972704660c9add5ad1
[ "CC0-1.0" ]
null
null
null
src/main/java/pl/lijek/veinminer/shapes/Shape.java
lijek/veinminer
80a4588d9cdb7ded56640f972704660c9add5ad1
[ "CC0-1.0" ]
null
null
null
src/main/java/pl/lijek/veinminer/shapes/Shape.java
lijek/veinminer
80a4588d9cdb7ded56640f972704660c9add5ad1
[ "CC0-1.0" ]
null
null
null
31.886179
139
0.63335
9,061
package pl.lijek.veinminer.shapes; import net.minecraft.block.BlockBase; import net.minecraft.block.Log; import net.minecraft.block.Plant; import net.minecraft.level.Level; import net.minecraft.util.maths.Box; import net.minecraft.util.maths.Vec3f; import net.minecraft.util.maths.Vec3i; import org.lwjgl.opengl.GL11; import pl.lijek.veinminer.util.BlockAddAction; import pl.lijek.veinminer.util.BlockData; import pl.lijek.veinminer.util.BlockMatcher; import pl.lijek.veinminer.util.Util; import java.util.ArrayList; import java.util.List; import static pl.lijek.veinminer.VeinMiner.*; import static pl.lijek.veinminer.util.BlockAddAction.*; public abstract class Shape { public Level level; public BlockData origin; public BlockBase originBlock; public List<BlockData> blocks = new ArrayList<>(); protected List<BlockData> scannedBlocks = new ArrayList<>(); public int hitSide; public int playerFacing; private static boolean crappyDebug = false; public Shape(Level level, Vec3i originVec3i, int hitSide, int playerFacing){ this.playerFacing = playerFacing; this.level = level; changeOrigin(originVec3i.x, originVec3i.y, originVec3i.z, hitSide); blocks.add(origin); selectBlocks(origin.x, origin.y, origin.z); } protected int getDistance(Vec3i target) { return Util.getSphericalDistance(origin, target); } public abstract void selectBlocks(int x, int y, int z); protected BlockAddAction addBlock(BlockData target){ if(blocks.size() >= config.maxBlocksToMine) { if(crappyDebug) LOGGER.info("CANCELLED: MAX BLOCK COUNT EXCEEDED"); return CANCEL; } if(scannedBlocks.contains(target)) { if(crappyDebug) LOGGER.info("SKIPPED: THIS BLOCK WAS SCANNED"); return SKIP; } if(origin.equals(target)) { if(crappyDebug) LOGGER.info("SKIPPED: THIS BLOCK EQUALS TARGET"); return SKIP; } if (!BlockMatcher.ID_META.matchBlocks(this, target)) { if(crappyDebug) LOGGER.info("SKIPPED: THIS BLOCK DOESN'T MATCH ORIGIN"); return SKIP; } if (!(config.maxDistance == -1 || getDistance(target) <= config.maxDistance)) { if(crappyDebug) LOGGER.info("SKIPPED: THIS BLOCK IS OUT OF maxDistance"); return SKIP; } if(!blocks.contains(target)) blocks.add(target); scannedBlocks.add(target); return PASS; } public void changeOrigin(int x, int y, int z, int hitSide){ this.origin = new BlockData(x, y, z, level.getTileId(x, y, z), level.getTileMeta(x, y, z)); this.originBlock = BlockBase.BY_ID[origin.id]; this.hitSide = hitSide; } public void changeOrigin(BlockData origin){ this.origin = origin; } protected int getConnectionDistance(){ if(originBlock instanceof Plant) return 3; else if(originBlock instanceof Log) return 2; return 1; } public void render(double fixX, double fixY, double fixZ){ GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glColor3f(1.0f, 1.0f, 1.0f); for(Vec3i block : blocks){ Box box = Box.create(block.x, block.y, block.z, block.x + 1.0D, block.y + 1.0D, block.z + 1.0D).method_98(-fixX, -fixY, -fixZ); Util.drawCuboid(GL11.GL_LINE_LOOP, box); } GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_TEXTURE_2D); } public void reset(int x, int y, int z, int hitSide){ blocks = new ArrayList<>(); scannedBlocks = new ArrayList<>(); changeOrigin(x, y, z, hitSide); blocks.add(origin); selectBlocks(x, y, z); } }
3e155255b3945114c74c2ecf64fb4b7486df0c33
2,807
java
Java
registry-integration-tests/src/test/java/org/gbif/registry/identity/surety/IdentityEmailManagerIT.java
MattBlissett/registry
63aafec68d7bd53b5c692113098d64cefc01ead4
[ "Apache-2.0" ]
null
null
null
registry-integration-tests/src/test/java/org/gbif/registry/identity/surety/IdentityEmailManagerIT.java
MattBlissett/registry
63aafec68d7bd53b5c692113098d64cefc01ead4
[ "Apache-2.0" ]
51
2019-09-02T09:41:14.000Z
2020-04-02T14:24:04.000Z
registry-integration-tests/src/test/java/org/gbif/registry/identity/surety/IdentityEmailManagerIT.java
MattBlissett/registry
63aafec68d7bd53b5c692113098d64cefc01ead4
[ "Apache-2.0" ]
null
null
null
36.194805
97
0.772156
9,062
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * 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.gbif.registry.identity.surety; import org.gbif.api.model.ChallengeCode; import org.gbif.api.model.common.GbifUser; import org.gbif.registry.domain.mail.BaseEmailModel; import org.gbif.registry.mail.identity.IdentityEmailManager; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertNotNull; /** * Tests related to {@link IdentityEmailManager}. The main purpose of the following tests is to * ensure we can generate a {@link BaseEmailModel} using the Freemarker templates. */ @SpringBootTest @ActiveProfiles("test") @RunWith(SpringRunner.class) public class IdentityEmailManagerIT { @Autowired private IdentityEmailManager identityEmailManager; private GbifUser generateTestUser() { GbifUser newUser = new GbifUser(); newUser.setUserName("User"); newUser.setEmail("ychag@example.com"); return newUser; } @Test public void testGenerateNewUserEmailModel() throws IOException { GbifUser newUser = generateTestUser(); BaseEmailModel baseEmail = identityEmailManager.generateNewUserEmailModel(newUser, ChallengeCode.newRandom()); assertNotNull("We can generate the model from the template", baseEmail); } @Test public void testGenerateResetPasswordEmailModel() throws IOException { GbifUser newUser = generateTestUser(); BaseEmailModel baseEmail = identityEmailManager.generateResetPasswordEmailModel(newUser, ChallengeCode.newRandom()); assertNotNull("We can generate the model from the template", baseEmail); } @Test public void testGenerateWelcomeEmailModel() throws IOException { GbifUser newUser = new GbifUser(); newUser.setUserName("User"); newUser.setEmail("ychag@example.com"); BaseEmailModel baseEmail = identityEmailManager.generateWelcomeEmailModel(newUser); assertNotNull("We can generate the model from the template", baseEmail); } }
3e1552d994f54473169f7cd3c58a45069d825df1
1,572
java
Java
tidp-test/src/main/java/com/tallate/test/redisconfig/RedisTidpConfig.java
tallate/sidp
9651705c91bfa5a3d1e0a3d3f4f4ab01f584c23e
[ "Apache-2.0" ]
null
null
null
tidp-test/src/main/java/com/tallate/test/redisconfig/RedisTidpConfig.java
tallate/sidp
9651705c91bfa5a3d1e0a3d3f4f4ab01f584c23e
[ "Apache-2.0" ]
6
2020-03-04T22:30:52.000Z
2021-12-09T20:54:26.000Z
tidp-test/src/main/java/com/tallate/test/redisconfig/RedisTidpConfig.java
tallate/sidp
9651705c91bfa5a3d1e0a3d3f4f4ab01f584c23e
[ "Apache-2.0" ]
2
2019-03-08T14:48:26.000Z
2019-06-13T15:16:35.000Z
27.578947
81
0.727735
9,063
package com.tallate.test.redisconfig; import com.tallate.test.http.HttpInterceptor; import com.tallate.test.keyprovider.SpanIdKeyProvider; import com.tallate.tidp.idpchecker.IdpChecker; import com.tallate.tidp.idpchecker.blocking.DefaultIdpChecker; import com.tallate.tidp.keyprovider.KeyProvider; import com.tallate.tidp.keystore.KeyStore; import com.tallate.tidp.keystore.RedisClient; import com.tallate.tidp.keystore.RedisKeyStore; import com.tallate.tidp.spring.IdpInterceptor; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Pointcut; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 在相应启动类中引入 */ @Configuration public class RedisTidpConfig { @Bean public KeyProvider getKeyProvider() { return new SpanIdKeyProvider(); } @Bean public KeyStore getKeyStore(RedisClient redisClient) { return new RedisKeyStore() .setRedisClient(redisClient); } @Bean public IdpChecker getIdpChecker(KeyProvider keyProvider, KeyStore keyStore) { return new DefaultIdpChecker() .setKeyProvider(keyProvider) .setKeyStore(keyStore); } /** * 幂等切面 */ @Bean public IdpInterceptor idpInterceptor(IdpChecker idpChecker) { return new IdpInterceptor() .setIdpChecker(idpChecker); } @Bean public HttpInterceptor httpInterceptor() { return new HttpInterceptor(); } }
3e1552f4ff43a766929880cfa14875fcb42b6af0
849
java
Java
chapter_001/src/main/java/ru/job4j/control/ContainsString.java
agolovatjuk/alexander4j
54f45555ef4c4920b3ded3a6f9a3811686395c27
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/control/ContainsString.java
agolovatjuk/alexander4j
54f45555ef4c4920b3ded3a6f9a3811686395c27
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/control/ContainsString.java
agolovatjuk/alexander4j
54f45555ef4c4920b3ded3a6f9a3811686395c27
[ "Apache-2.0" ]
null
null
null
25.727273
72
0.46172
9,064
package ru.job4j.control; /**. * check Point * @author Alexander Golovatyuk * @version $Id$ * @since 0.1 */ public class ContainsString { /**. * @param origin - test string * @param sub - pattern * @return result boolean */ public boolean contains(String origin, String sub) { char[] chOrig = origin.toCharArray(); char[] chSub = sub.toCharArray(); boolean result = false; for (int i = 0; i < origin.length() && !result; i++) { if (chOrig[i] == chSub[0]) { result = true; for (int j = 0; j < sub.length() && result; i++, j++) { if (i == origin.length() || chOrig[i] != chSub[j]) { result = false; } } } } return result; } }
3e15530dfb4284b3fb62534248146bc77d75c353
4,034
java
Java
api/src/main/java/life/catalogue/api/vocab/Setting.java
CatalogueOfLife/backend
7f38492ac1d33a15ec564824f8eca3835dc1e26d
[ "Apache-2.0" ]
6
2020-03-14T12:25:02.000Z
2022-03-17T20:26:46.000Z
api/src/main/java/life/catalogue/api/vocab/Setting.java
CatalogueOfLife/backend
7f38492ac1d33a15ec564824f8eca3835dc1e26d
[ "Apache-2.0" ]
546
2020-03-13T10:53:07.000Z
2022-03-30T05:17:48.000Z
api/src/main/java/life/catalogue/api/vocab/Setting.java
CatalogueOfLife/backend
7f38492ac1d33a15ec564824f8eca3835dc1e26d
[ "Apache-2.0" ]
9
2020-04-17T16:02:43.000Z
2022-03-26T15:57:07.000Z
26.893333
124
0.70476
9,065
package life.catalogue.api.vocab; import org.gbif.nameparser.api.NomCode; import org.gbif.nameparser.api.Rank; import java.net.URI; import java.time.LocalDate; import com.google.common.base.Preconditions; import static life.catalogue.api.vocab.DatasetOrigin.*; /** * Dataset settings */ public enum Setting { /** * When importing data from text files this overrides * the field delimiter character used */ CSV_DELIMITER(String.class, EXTERNAL), /** * When importing data from text files this overrides * the quote character used */ CSV_QUOTE(String.class, EXTERNAL), /** * When importing data from text files this overrides * the single character used for escaping quotes inside an already quoted value. * For example '"' for CSV */ CSV_QUOTE_ESCAPE(String.class, EXTERNAL), /** * Overrides the gazetteer standard to use in all distribution interpretations for the dataset. */ DISTRIBUTION_GAZETTEER(Gazetteer.class, EXTERNAL, MANAGED), /** * The nomenclatural code followed in the dataset. * It will be used mostly as a hint to format names accordingly. * If the dataset contains mixed data from multiple codes keep this field null. */ NOMENCLATURAL_CODE(NomCode.class, EXTERNAL, MANAGED), /** * Setting that will inform the importer to rematch all decisions (decisions sensu strictu but also sectors and estimates) * Defaults to false */ REMATCH_DECISIONS(Boolean.class, EXTERNAL, MANAGED), /** * Setting that will inform the importer not to update any metadata from archives. * Metadata will be locked and can only be edited manually. */ LOCK_METADATA(Boolean.class, EXTERNAL, MANAGED), /** * Template used to build a new release alias. * See RELEASE_TITLE_TEMPLATE for usage. */ RELEASE_ALIAS_TEMPLATE(String.class, MANAGED), /** * If true a release will include as its authors all authors of all it's sources. */ RELEASE_ADD_SOURCE_AUTHORS(Boolean.class, MANAGED), /** * If true a release will include as its authors all contributors of the project (not source contributors). */ RELEASE_ADD_CONTRIBUTORS(Boolean.class, MANAGED), /** * Number of first authors from a project/release to use for the container authors of a source chapter-in-a-book citation. * If not given all authors are used. */ SOURCE_MAX_CONTAINER_AUTHORS(Integer.class, MANAGED, RELEASED), DATA_FORMAT(DataFormat.class, EXTERNAL, MANAGED), /** * In continuous import mode the frequency the dataset is scheduled for imports. */ IMPORT_FREQUENCY(Frequency.class, EXTERNAL), DATA_ACCESS(URI.class, EXTERNAL), /** * Project defaults to be used for the sector.entities property */ SECTOR_ENTITIES(EntityType.class, true, MANAGED), /** * Project defaults to be used for the sector.ranks property */ SECTOR_RANKS(Rank.class, true, MANAGED), /** * If set to true the dataset metadata is locked and the gbif registry sync will not be applied to the dataset. */ GBIF_SYNC_LOCK(Boolean.class, false, EXTERNAL); private final Class type; private final DatasetOrigin[] origin; private final boolean multiple; public Class getType() { return type; } public DatasetOrigin[] getOrigin() { return origin; } public boolean isEnum() { return type.isEnum(); } public boolean isMultiple() { return multiple; } Setting(Class type, DatasetOrigin... origin) { this(type, false, origin); } /** * Use String, Integer, Boolean, LocalDate, URI or a custom col enumeration class * * @param type * @param origin */ Setting(Class type, boolean multiple, DatasetOrigin... origin) { this.multiple = multiple; this.origin = origin; Preconditions.checkArgument(type.equals(String.class) || type.equals(Integer.class) || type.equals(Boolean.class) || type.equals(LocalDate.class) || type.equals(URI.class) || type.isEnum(), "Unsupported type"); this.type = type; } }
3e15536777d287e6833fe9742d0a478fa8a07acb
404
java
Java
src/main/java/com/sixtyfour/elements/mnemonics/Inx.java
yottatsa/basicv2
d64e3ed256bcac5e6f3d5f5cae0da3266a16d356
[ "Unlicense" ]
71
2016-08-09T20:12:50.000Z
2022-03-25T08:17:48.000Z
src/main/java/com/sixtyfour/elements/mnemonics/Inx.java
yottatsa/basicv2
d64e3ed256bcac5e6f3d5f5cae0da3266a16d356
[ "Unlicense" ]
35
2017-01-04T17:35:08.000Z
2021-11-05T11:09:06.000Z
src/main/java/com/sixtyfour/elements/mnemonics/Inx.java
yottatsa/basicv2
d64e3ed256bcac5e6f3d5f5cae0da3266a16d356
[ "Unlicense" ]
12
2018-08-20T03:12:42.000Z
2021-09-21T00:30:11.000Z
15.538462
69
0.608911
9,066
package com.sixtyfour.elements.mnemonics; /** * The Class Inx. */ public class Inx extends AbstractMnemonic { /** * Instantiates a new inx. */ public Inx() { super("INX", new int[] { 0xE8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); } /* * (non-Javadoc) * * @see com.sixtyfour.elements.mnemonics.AbstractMnemonic#isSingle() */ @Override public boolean isSingle() { return true; } }
3e155447b0e6b0685468cf604af1ba853d9d7f27
5,584
java
Java
web/crc-roaming-ws/src/main/java/bg/infosys/crc/roaming/services/web/UserService.java
governmentbg/crc-roaming
afba722d8d25d2cd6bd1806378bc06a19b2c4c73
[ "Apache-2.0" ]
null
null
null
web/crc-roaming-ws/src/main/java/bg/infosys/crc/roaming/services/web/UserService.java
governmentbg/crc-roaming
afba722d8d25d2cd6bd1806378bc06a19b2c4c73
[ "Apache-2.0" ]
null
null
null
web/crc-roaming-ws/src/main/java/bg/infosys/crc/roaming/services/web/UserService.java
governmentbg/crc-roaming
afba722d8d25d2cd6bd1806378bc06a19b2c4c73
[ "Apache-2.0" ]
1
2021-12-30T10:00:30.000Z
2021-12-30T10:00:30.000Z
37.226667
127
0.770953
9,067
package bg.infosys.crc.roaming.services.web; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import bg.infosys.common.db.helpers.ResultFilter; import bg.infosys.common.exceptions.ResponseStatusException; import bg.infosys.common.mail.Email; import bg.infosys.common.ws.security.SecuritySession; import bg.infosys.common.ws.security.components.AuthService; import bg.infosys.crc.dao.pub.TranslationDAO; import bg.infosys.crc.dao.web.security.AuthorityDAO; import bg.infosys.crc.dao.web.security.UserDAO; import bg.infosys.crc.entities.pub.LanguageEnum; import bg.infosys.crc.entities.pub.Translation.TranslationId; import bg.infosys.crc.entities.pub.TranslationEnum; import bg.infosys.crc.entities.web.security.Authority; import bg.infosys.crc.entities.web.security.User; import bg.infosys.crc.roaming.components.Properties; import bg.infosys.crc.roaming.components.Scheduler; import bg.infosys.crc.roaming.dto.web.users.AddEditUserDTO; import bg.infosys.crc.roaming.dto.web.users.EmailDTO; import bg.infosys.crc.roaming.dto.web.users.ListUserDTO; import bg.infosys.crc.roaming.helpers.mobile.Helper; import bg.infosys.crc.roaming.helpers.web.PagingResultDTO; import bg.infosys.crc.roaming.workers.SendMailTask; @Service public class UserService { @Autowired private Scheduler scheduler; @Autowired private AuthService authService; @Autowired private TranslationDAO translationDAO; @Autowired private UserDAO userDAO; @Autowired private AuthorityDAO authorityDAO; public void requestResetPassword(EmailDTO requestDTO) { User u = userDAO.findByUsername(requestDTO.getEmail()); if (u == null) return; String token = authService.generatePasswordResetToken(u, Properties.MAIL_VALIDITY_MINS); String link = Properties.get("webapp.urlResetPass") + token; String subject = translationDAO.findById(new TranslationId(TranslationEnum.WEB_RESET_PASS_SUBJ, LanguageEnum.BG)).getValue(); String bodyRaw = translationDAO.findById(new TranslationId(TranslationEnum.WEB_RESET_PASS_BODY, LanguageEnum.BG)).getValue(); String body = bodyRaw.replace("{name}", u.getFullName()).replace("{link}", link); Email email = new Email(u.getUsername(), subject, body); scheduler.addTask(new SendMailTask(email)); } public PagingResultDTO<ListUserDTO> getAllUsers(Integer page, Integer pageSize) { List<ListUserDTO> users = userDAO.findAllPaged(ResultFilter.firstResult(page, pageSize), pageSize) .stream().map(u -> new ListUserDTO(u, false)).collect(Collectors.toList()); return new PagingResultDTO<>(users, page, pageSize); } public long countUsers() { return userDAO.count() - 1; // -- subtract the default system user } public ListUserDTO getUser(Integer userId) { return new ListUserDTO(userDAO.findUserById(userId), false); } @Transactional public void saveUser(AddEditUserDTO user) { checkIfUsernameExists(user.getEmail(), null); User u = user.toEntity(); String rawPass = Helper.generatePassword(10); String encodedPass = authService.encodePassword(rawPass); u.setPassword(encodedPass); String subj = translationDAO.findById(new TranslationId(TranslationEnum.WEB_MAIL_NEW_USER_SUBJ, LanguageEnum.BG)).getValue(); String body = translationDAO.findById(new TranslationId(TranslationEnum.WEB_MAIL_NEW_USER_BODY, LanguageEnum.BG)).getValue(); body = body .replace("{name}", u.getFullName()) .replace("{link}", Properties.get("webapp.url")) .replace("{pass}", rawPass); if (user.getRoleId() != null) { Authority a = authorityDAO.findById(user.getRoleId()); checkAuthorityForSingleUser(a, null); u.getGrantedAuthorities().add(a); } u.setCreatedBy(userDAO.findById(SecuritySession.getUserId())); u.setCreatedAt(LocalDateTime.now()); userDAO.save(u); userDAO.flush(); Email email = new Email(u.getUsername(), subj, body); scheduler.addTask(new SendMailTask(email)); } @Transactional public void updateUser(Integer userId, AddEditUserDTO user) { User u = getAndCheckIfUserExists(userId); checkIfUsernameExists(user.getEmail(), userId); user.merge(u); Authority a = authorityDAO.findById(user.getRoleId()); checkAuthorityForSingleUser(a, userId); u.setUpdatedBy(userDAO.findById(SecuritySession.getUserId())); u.setUpdatedAt(LocalDateTime.now()); u.getGrantedAuthorities().add(a); userDAO.update(u); } @Transactional public void deleteUser(Integer userId) { User u = getAndCheckIfUserExists(userId); userDAO.delete(u); } private User getAndCheckIfUserExists(Integer id) { User u = userDAO.findUserById(id); if (u == null) { throw new ResponseStatusException(HttpServletResponse.SC_GONE, "The user does not exist", "userDoesNotExist"); } return u; } private void checkIfUsernameExists(String username, Integer userId) { if (userDAO.findByUsername(username, userId) != null) { throw new ResponseStatusException(HttpServletResponse.SC_CONFLICT, "Email already exists", "userEmailAlreadyExists"); } } private void checkAuthorityForSingleUser(Authority a, Integer userId) { if (Boolean.TRUE.equals(a.getToSingleUser()) && userDAO.countUsingAuhtority(a.getId()) > 0) { throw new ResponseStatusException(HttpServletResponse.SC_CONFLICT, "The role can be assigned to a single user and it's already assigned.", "singleUserRoleAlreadyAssigned"); } } }
3e1554bca6208af45604b30e4e3926363b1e8d48
2,936
java
Java
bsaber-scrapper/src/main/java/bsaber/tools/parser/BSaberParser.java
JamDaBam/BSaber_downloader
a03b13ae6e1102653402af4d936d6720909b620d
[ "MIT" ]
null
null
null
bsaber-scrapper/src/main/java/bsaber/tools/parser/BSaberParser.java
JamDaBam/BSaber_downloader
a03b13ae6e1102653402af4d936d6720909b620d
[ "MIT" ]
null
null
null
bsaber-scrapper/src/main/java/bsaber/tools/parser/BSaberParser.java
JamDaBam/BSaber_downloader
a03b13ae6e1102653402af4d936d6720909b620d
[ "MIT" ]
null
null
null
30.905263
100
0.70436
9,068
package bsaber.tools.parser; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import bsaber.tools.bsaber_scrapper.Constants; import bsaber.tools.bsaber_scrapper.SongEntry; import bsaber.tools.bsaber_scrapper.SongMetaData; import bsaber.tools.bsaber_scrapper.Tools; public class BSaberParser { private static final Logger cvLogger = LogManager.getLogger(BSaberParser.class); // Html tags private static final String TAG_MAPPER = "mapper_id vcard"; private static final String TAG_TITLE = "entry-title"; private static final String TAG_LINK = "href"; private static final String TAG_DIFFICULTY = "post-difficulty"; private static final String TAG_UPVOTES = "fa-thumbs-up"; private static final String TAG_DOWNVOTES = "fa-thumbs-down"; private static final String TAG_DOWNLOADURL = "-download-zip"; public static List<SongEntry> parse(Elements aSongEntryElements) { List<SongEntry> songEntries = new ArrayList<>(); for (Element songEntryElement : aSongEntryElements) { songEntries.add(parse(songEntryElement)); } return songEntries; } private static SongEntry parse(Element aSongEntryElement) { return new SongEntry(parse(Arrays.asList(aSongEntryElement), new SongMetaData())); } private static SongMetaData parse(List<Element> aElements, SongMetaData aMetaData) { if (aElements != null) { for (Element element : aElements) { if (element.hasClass(TAG_MAPPER)) { aMetaData.setLevelAuthorName(element.text()); } if (element.hasClass(TAG_TITLE)) { // Pageentries if (!Tools.isNullOrEmpty(element.children())) { Element child = element.child(0); aMetaData.setSongName(child.text()); aMetaData.setKey(extractKey(child.attr(TAG_LINK), Constants.BSABER_BASE_SONGS_URL)); } // Singleentry else { aMetaData.setSongName(element.text()); } } if (element.hasClass(TAG_DIFFICULTY)) { aMetaData.addDifficulty(element.text()); } if (element.hasClass(TAG_UPVOTES)) { aMetaData.setUpVotes(Integer.parseInt(element.parent().text())); } if (element.hasClass(TAG_DOWNVOTES)) { aMetaData.setDownVotes(Integer.parseInt(element.parent().text())); } if (element.hasClass(TAG_DOWNLOADURL)) { aMetaData.setDownloadURL(element.attr(TAG_LINK)); // Singleentry if (aMetaData.getKey() == null) { aMetaData.setKey(extractKey(aMetaData.getDownloadURL(), Constants.BSABER_BASE_DOWNLOAD_URL)); } } aMetaData = parse(element.children(), aMetaData); } } return aMetaData; } private static String extractKey(String aString, String aCutString) { return aString.replace(aCutString, "").replace("/", ""); } }
3e1554c6a0b3bc579bebe15adce3fba5bc12cfb2
835
java
Java
src/main/java/org/trustedanalytics/usermanagement/summary/model/PlatformSummary.java
trustedanalytics-ng/user-management
f817999a10656555f7f445eed7d48d247739bd11
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/main/java/org/trustedanalytics/usermanagement/summary/model/PlatformSummary.java
trustedanalytics-ng/user-management
f817999a10656555f7f445eed7d48d247739bd11
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/main/java/org/trustedanalytics/usermanagement/summary/model/PlatformSummary.java
trustedanalytics-ng/user-management
f817999a10656555f7f445eed7d48d247739bd11
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
29.821429
76
0.74491
9,069
/** * Copyright (c) 2016 Intel Corporation  * * 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.trustedanalytics.usermanagement.summary.model; import lombok.Data; import java.util.Collection; @Data public class PlatformSummary { private final Collection<OrganizationSummary> organizations; }
3e15550997417aa120820f68aaa56bb0400df64b
7,765
java
Java
Android Version/Interest Destroyer/app/src/main/java/com/tutorazadi/interestdestroyerandroid/InfoGatheringActivity.java
tutorazadi/InterestReducer
41d98be4980056c3fbb3d188ba2bf43a178d9bc1
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Android Version/Interest Destroyer/app/src/main/java/com/tutorazadi/interestdestroyerandroid/InfoGatheringActivity.java
tutorazadi/InterestReducer
41d98be4980056c3fbb3d188ba2bf43a178d9bc1
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Android Version/Interest Destroyer/app/src/main/java/com/tutorazadi/interestdestroyerandroid/InfoGatheringActivity.java
tutorazadi/InterestReducer
41d98be4980056c3fbb3d188ba2bf43a178d9bc1
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
44.119318
131
0.673406
9,070
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.tutorazadi.interestdestroyerandroid; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.text.InputType; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.ImageView; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class InfoGatheringActivity extends Activity { public static double rate, principal_original, payment_amount, simple_interest; public static double compound_interest, original_interest = 0.00f, net_interest, principal_paid, payoff_months; public static double[] min_interest_paid, extra_interest_paid, min_principal_paid, extra_principal_paid; @Bind(R.id.fab) FloatingActionButton fab; @Bind(R.id.principalTxt) EditText principalTxt; @Bind(R.id.interestTxt) EditText interestTxt; @Bind(R.id.numMonthsTxt) EditText numMonthsTxt; @Bind(R.id.extraPaymentTxt) EditText extraPaymentTxt; @Bind(R.id.mainLayout) CoordinatorLayout mainLayout; @Bind(R.id.icon) ImageView icon; public Typeface arimo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info_gathering); ButterKnife.bind(this); initializeControls(); } public void initializeControls() { arimo = Typeface.createFromAsset(this.getAssets(), "fonts/Arimo-Regular.ttf"); List<EditText> fields = Arrays.asList(principalTxt, numMonthsTxt, interestTxt, extraPaymentTxt); for (EditText field: fields) { field.setTypeface(arimo); field.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); } } @OnClick(R.id.fab) void submit() { Item.principal = principal_original; simple_interest = Item.principal * (rate / 100) * (Item.time / 12); Item.interest_paid = 0.00; net_interest = 0.00; principal_paid = 0.00; payment_amount = amortize(Item.principal, rate, Item.time); try { if (principalTxt.getText().length() < 4) { Snackbar.make(mainLayout, "Minimum amount for principal must be greater than $1000", Snackbar.LENGTH_SHORT).show(); return; } else if (interestTxt.getText().length() < 1) { Snackbar.make(mainLayout, "Minimum interest rate must be greater than 0%.", Snackbar.LENGTH_SHORT).show(); return; } else if (numMonthsTxt.getText().length() < 1) { Snackbar.make(mainLayout, "Minimum number of months must be greater than 0.", Snackbar.LENGTH_SHORT).show(); return; } else if (extraPaymentTxt.getText().length() < 1) { Snackbar.make(mainLayout, "Please enter at least $0 for an extra payment amount.", Snackbar.LENGTH_SHORT).show(); } principal_original = Item.principal = Double.parseDouble(principalTxt.getText().toString()); Item.time = Double.parseDouble(numMonthsTxt.getText().toString()); rate = Double.parseDouble(interestTxt.getText().toString()); Item.extra_payment = Double.parseDouble(extraPaymentTxt.getText().toString()); calculate(); Item.total_months = Integer.parseInt(numMonthsTxt.getText().toString()); DonutVariables.PRINCIPAL = (float) principal_original; DonutVariables.INTEREST = (float) Item.interest_paid; startActivity(new Intent(InfoGatheringActivity.this, ResultsActivity.class)); } catch (NumberFormatException e) { Snackbar.make(mainLayout, "You have entered invalid data.", Snackbar.LENGTH_SHORT).show(); } } public void calculate() { Item.extra_payments = new double[(int) Item.time]; Item.minimum_payments = new double[(int) Item.time]; min_principal_paid = new double[(int) Item.time]; extra_principal_paid = new double[(int) Item.time]; min_interest_paid = new double[(int) Item.time]; extra_interest_paid = new double[(int) Item.time]; Item.min_principal_remaining = new double[(int) Item.time]; Item.extra_principal_remaining = new double[(int) Item.time]; for (int i = 0; i < Item.extra_payments.length; i++) { Item.minimum_payments[i] = 0.00f; Item.extra_payments[i] = 0.00f; } payment_amount = amortize(Item.principal, rate, Item.time); for (int i = 0; i < Item.time; i++) { compound_interest = Item.principal * (1 + (rate / 1200)) - Item.principal; if (compound_interest <= 0) break; Item.interest_paid += compound_interest; min_interest_paid[i] = compound_interest; principal_paid = payment_amount - compound_interest; min_principal_paid[i] = principal_paid; Item.min_principal_remaining[i] = Item.principal; Item.principal -= principal_paid; } original_interest = Item.interest_paid; principal_original = Item.principal = Double.parseDouble(principalTxt.getText().toString()); Item.time = Double.parseDouble(numMonthsTxt.getText().toString()); rate = Double.parseDouble(interestTxt.getText().toString()); Item.extra_payment = Double.parseDouble(extraPaymentTxt.getText().toString()); Item.interest_paid = compound_interest = principal_paid = simple_interest = 0; payment_amount = amortize(Item.principal, rate, Item.time); for (int i = 0; i < Item.time; i++) { compound_interest = Item.principal * (1 + (rate / 1200)) - Item.principal; if (compound_interest <= 0) { payoff_months = i; break; } Item.interest_paid += compound_interest; extra_interest_paid[i] = Item.interest_paid - Item.extra_payment; principal_paid = (payment_amount + Item.extra_payment) - compound_interest; extra_principal_paid[i] = principal_paid; Item.extra_principal_remaining[i] = Item.principal; Item.principal -= principal_paid; } Item.timeSaved = (Item.time - payoff_months) / 12; Item.interestSaved = original_interest - Item.interest_paid; } public static double amortize(double principal, double rate, double time) { rate /= 1200; return (principal * rate * Math.pow((1 + rate), time)) / (Math.pow((1 + rate), Item.time) - 1); } }
3e155514b1f0b0d0afd373760dd6ed8fbd5bf69c
6,131
java
Java
hystrix-core/src/jmh/java/com/netflix/hystrix/perf/CollapserPerfTest.java
dmgcodevil/Hystrix
a3dc47c08ba43417bb1c8eaee99c348a45082cf2
[ "Apache-2.0" ]
21,795
2015-01-01T02:36:30.000Z
2022-03-31T15:39:07.000Z
hystrix-core/src/jmh/java/com/netflix/hystrix/perf/CollapserPerfTest.java
dmgcodevil/Hystrix
a3dc47c08ba43417bb1c8eaee99c348a45082cf2
[ "Apache-2.0" ]
1,390
2015-01-03T20:36:54.000Z
2022-03-07T08:13:35.000Z
hystrix-core/src/jmh/java/com/netflix/hystrix/perf/CollapserPerfTest.java
dmgcodevil/Hystrix
a3dc47c08ba43417bb1c8eaee99c348a45082cf2
[ "Apache-2.0" ]
4,951
2015-01-01T02:33:47.000Z
2022-03-27T11:40:12.000Z
37.157576
220
0.67542
9,071
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hystrix.perf; import com.netflix.hystrix.HystrixCollapser; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixThreadPool; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; import rx.Observable; import rx.Subscription; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; public class CollapserPerfTest { @State(Scope.Benchmark) public static class ThreadPoolState { HystrixThreadPool hystrixThreadPool; @Setup public void setUp() { hystrixThreadPool = new HystrixThreadPool.HystrixThreadPoolDefault( HystrixThreadPoolKey.Factory.asKey("PERF") , HystrixThreadPoolProperties.Setter().withCoreSize(100)); } @TearDown public void tearDown() { hystrixThreadPool.getExecutor().shutdownNow(); } } @State(Scope.Thread) public static class CollapserState { @Param({"1", "10", "100", "1000"}) int numToCollapse; @Param({"1", "1000", "1000000"}) int blackholeConsumption; HystrixRequestContext reqContext; Observable<String> executionHandle; @Setup(Level.Invocation) public void setUp() { reqContext = HystrixRequestContext.initializeContext(); List<Observable<String>> os = new ArrayList<Observable<String>>(); for (int i = 0; i < numToCollapse; i++) { IdentityCollapser collapser = new IdentityCollapser(i, blackholeConsumption); os.add(collapser.observe()); } executionHandle = Observable.merge(os); } @TearDown(Level.Invocation) public void tearDown() { reqContext.shutdown(); } } private static class IdentityCollapser extends HystrixCollapser<List<String>, String, String> { private final int arg; private final int blackholeConsumption; IdentityCollapser(int arg, int blackholeConsumption) { super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("COLLAPSER")).andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withMaxRequestsInBatch(1000).withTimerDelayInMilliseconds(1))); this.arg = arg; this.blackholeConsumption = blackholeConsumption; } @Override public String getRequestArgument() { return arg + ""; } @Override protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, String>> collapsedRequests) { List<String> args = new ArrayList<String>(); for (CollapsedRequest<String, String> collapsedReq: collapsedRequests) { args.add(collapsedReq.getArgument()); } return new BatchCommand(args, blackholeConsumption); } @Override protected void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, String>> collapsedRequests) { for (CollapsedRequest<String, String> collapsedReq: collapsedRequests) { String requestArg = collapsedReq.getArgument(); String response = "<not found>"; for (String responsePiece: batchResponse) { if (responsePiece.startsWith(requestArg + ":")) { response = responsePiece; break; } } collapsedReq.setResponse(response); } } } private static class BatchCommand extends HystrixCommand<List<String>> { private final List<String> inputArgs; private final int blackholeConsumption; BatchCommand(List<String> inputArgs, int blackholeConsumption) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("PERF")).andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("PERF"))); this.inputArgs = inputArgs; this.blackholeConsumption = blackholeConsumption; } @Override protected List<String> run() throws Exception { Blackhole.consumeCPU(blackholeConsumption); List<String> toReturn = new ArrayList<String>(); for (String inputArg: inputArgs) { toReturn.add(inputArg + ":1"); } return toReturn; } } @Benchmark @BenchmarkMode({Mode.Throughput}) @OutputTimeUnit(TimeUnit.SECONDS) public List<String> observeCollapsedAndWait(CollapserState collapserState, ThreadPoolState threadPoolState) { return collapserState.executionHandle.toList().toBlocking().single(); } }
3e15559f3826c54239bfe1036638ff61e5b81a05
2,921
java
Java
src/main/java/com/dp/nebula/wormhole/plugins/reader/mysqlreader/MysqlReaderSplitter.java
kangzhenkang/wormhole
4be8f3d6be9beb74ff2dd60a43b73f8efc6cda42
[ "Apache-2.0" ]
34
2015-01-23T09:01:54.000Z
2021-04-11T05:29:02.000Z
src/main/java/com/dp/nebula/wormhole/plugins/reader/mysqlreader/MysqlReaderSplitter.java
jiujiesanxian/wormhole
4be8f3d6be9beb74ff2dd60a43b73f8efc6cda42
[ "Apache-2.0" ]
2
2015-04-24T02:36:12.000Z
2017-02-09T03:19:21.000Z
src/main/java/com/dp/nebula/wormhole/plugins/reader/mysqlreader/MysqlReaderSplitter.java
jiujiesanxian/wormhole
4be8f3d6be9beb74ff2dd60a43b73f8efc6cda42
[ "Apache-2.0" ]
57
2015-01-12T09:20:12.000Z
2022-02-16T11:58:26.000Z
31.074468
123
0.691886
9,072
package com.dp.nebula.wormhole.plugins.reader.mysqlreader; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.dp.nebula.wormhole.common.AbstractSplitter; import com.dp.nebula.wormhole.common.JobStatus; import com.dp.nebula.wormhole.common.WormholeException; import com.dp.nebula.wormhole.common.interfaces.IParam; public class MysqlReaderSplitter extends AbstractSplitter{ private static final String SQL_PATTEN = "%s limit %d, %d"; private Log logger = LogFactory.getLog(MysqlReaderSplitter.class); private String sql; private int blockSize; private int concurrency; private String tableName; private String columns; private String where; private static final int DEFAULT_BLOCK_SIZE = 1000; private static final String SQL_WITH_WHERE_PATTEN = "select %s from %s where %s"; private static final String SQL_WITHOUT_WHERE_PATTEN = "select %s from %s"; @Override public void init(IParam jobParams){ super.init(jobParams); sql = param.getValue(ParamKey.sql, ""); blockSize = param.getIntValue(ParamKey.blockSize, DEFAULT_BLOCK_SIZE); concurrency = param.getIntValue(ParamKey.concurrency,1); tableName = param.getValue(ParamKey.tableName, ""); columns = param.getValue(ParamKey.columns, ""); where = param.getValue(ParamKey.where, ""); } @Override public List<IParam> split() { List<IParam> paramList = new ArrayList<IParam>() ; if(sql.isEmpty()) { if(tableName.isEmpty()||columns.isEmpty()) { logger.error("Mysql reader sql is empty"); throw new WormholeException("Mysql reader sql is empty",JobStatus.CONF_FAILED.getStatus()+MysqlReader.ERROR_CODE_ADD); } if(!where.isEmpty()) { sql = String.format(SQL_WITH_WHERE_PATTEN, columns, tableName, where); } else { sql = String.format(SQL_WITHOUT_WHERE_PATTEN, columns, tableName); } } if(!sql.isEmpty()){ long size = param.getLongValue(MysqlReaderPeriphery.DATA_AMOUNT_KEY,-1); if (size == -1){ paramList.add(param); logger.warn("Cannot get data amount for mysql reader"); return paramList; } int amount = 0; StringBuilder []sqlArray = new StringBuilder[concurrency]; for(long i = 0; i <= size/blockSize; i++){ String sqlSplitted = String.format(SQL_PATTEN, sql, amount, blockSize); int index = (int) (i%concurrency); if(sqlArray[index] == null){ sqlArray[index] = new StringBuilder(); } sqlArray[index].append(sqlSplitted).append(";") ; amount += blockSize; } for(int j = 0; j < concurrency; j++){ if(sqlArray[j] == null) { continue; } IParam paramSplitted = param.clone(); paramSplitted.putValue(ParamKey.sql, sqlArray[j].toString()); paramList.add(paramSplitted); } } return paramList; } }
3e155600c1b9e4046e880a3a8a06ed79382ce3c4
6,704
java
Java
app/src/main/java/com/yandex/disk/rest/djak741/DownloadFileFragment.java
djak7411/yandexapi
d6a6e3b92ee9570b199fbce8d5af386aca9d5a47
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yandex/disk/rest/djak741/DownloadFileFragment.java
djak7411/yandexapi
d6a6e3b92ee9570b199fbce8d5af386aca9d5a47
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yandex/disk/rest/djak741/DownloadFileFragment.java
djak7411/yandexapi
d6a6e3b92ee9570b199fbce8d5af386aca9d5a47
[ "Apache-2.0" ]
null
null
null
33.858586
151
0.61784
9,073
package com.yandex.disk.rest.djak741; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.util.Log; import com.yandex.disk.rest.ProgressListener; import com.yandex.disk.rest.RestClient; import com.yandex.disk.rest.exceptions.ServerException; import com.yandex.disk.rest.exceptions.http.HttpCodeException; import java.io.File; import java.io.IOException; public class DownloadFileFragment extends IODialogFragment { private static final String TAG = "LoadFileFragment"; private static final String WORK_FRAGMENT_TAG = "LoadFileFragment.Background"; private static final String FILE_ITEM = "file.item"; private static final int PROGRESS_DIV = 1024 * 1024; private Credentials credentials; private ListItem item; private DownloadFileRetainedFragment workFragment; public static DownloadFileFragment newInstance(Credentials credentials, ListItem item) { DownloadFileFragment fragment = new DownloadFileFragment(); Bundle args = new Bundle(); args.putParcelable(CREDENTIALS, credentials); args.putParcelable(FILE_ITEM, item); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); credentials = getArguments().getParcelable(CREDENTIALS); item = getArguments().getParcelable(FILE_ITEM); } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); FragmentManager fragmentManager = getFragmentManager(); workFragment = (DownloadFileRetainedFragment) fragmentManager.findFragmentByTag(WORK_FRAGMENT_TAG); if (workFragment == null || workFragment.getTargetFragment() == null) { workFragment = new DownloadFileRetainedFragment(); fragmentManager.beginTransaction().add(workFragment, WORK_FRAGMENT_TAG).commit(); workFragment.loadFile(getActivity(), credentials, item); } workFragment.setTargetFragment(this, 0); } @Override public void onDetach() { super.onDetach(); if (workFragment != null) { workFragment.setTargetFragment(null, 0); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { dialog = new ProgressDialog(getActivity()); dialog.setTitle(R.string.example_loading_file_title); dialog.setMessage(item.getName()); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setIndeterminate(true); dialog.setButton(ProgressDialog.BUTTON_NEUTRAL, getString(R.string.example_loading_file_cancel_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); onCancel(); } }); dialog.setOnCancelListener(this); dialog.show(); return dialog; } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); onCancel(); } private void onCancel() { workFragment.cancelDownload(); } public void onDownloadComplete(File file) { dialog.dismiss(); makeWorldReadableAndOpenFile(file); } private void makeWorldReadableAndOpenFile(File file) { file.setReadable(true, false); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), item.getContentType()); startActivity(Intent.createChooser(intent, getText(R.string.example_loading_file_chooser_title))); } public void setDownloadProgress(long loaded, long total) { if (dialog != null) { if (dialog.isIndeterminate()) { dialog.setIndeterminate(false); } if (total > Integer.MAX_VALUE) { dialog.setProgress((int)(loaded / PROGRESS_DIV)); dialog.setMax((int)(total / PROGRESS_DIV)); } else { dialog.setProgress((int)loaded); dialog.setMax((int)total); } } } public static class DownloadFileRetainedFragment extends IODialogRetainedFragment implements ProgressListener { private boolean cancelled; private File result; public void loadFile(final Context context, final Credentials credentials, final ListItem item) { result = new File("/storage/emulated/0/"+item.getName()); new Thread(new Runnable() { @Override public void run () { try { RestClient client = RestClientUtil.getInstance(credentials); client.downloadFile(item.getPath(), result, DownloadFileRetainedFragment.this); downloadComplete(); } catch (HttpCodeException ex) { Log.d(TAG, "loadFile", ex); sendException(ex.getResponse().getDescription()); } catch (IOException | ServerException ex) { Log.d(TAG, "loadFile", ex); sendException(ex); } } }).start(); } @Override public void updateProgress (final long loaded, final long total) { handler.post(new Runnable() { @Override public void run() { DownloadFileFragment targetFragment = (DownloadFileFragment) getTargetFragment(); if (targetFragment != null) { targetFragment.setDownloadProgress(loaded, total); } } }); } @Override public boolean hasCancelled () { return cancelled; } public void downloadComplete() { handler.post(new Runnable() { @Override public void run() { DownloadFileFragment targetFragment = (DownloadFileFragment) getTargetFragment(); if (targetFragment != null) { targetFragment.onDownloadComplete(result); } } }); } public void cancelDownload() { cancelled = true; } } }
3e155667cc0426998ba27c9ac09e99930e7c56bd
935
java
Java
src/main/java/mchorse/blockbuster/api/formats/vox/data/Vox.java
Chunk7w/blockbuster
f8df3c8d2709135512a1cdd1e08cd3545c9975bc
[ "MIT" ]
106
2016-06-25T04:41:34.000Z
2022-03-27T16:13:28.000Z
src/main/java/mchorse/blockbuster/api/formats/vox/data/Vox.java
Chunk7w/blockbuster
f8df3c8d2709135512a1cdd1e08cd3545c9975bc
[ "MIT" ]
173
2016-06-26T16:04:08.000Z
2022-03-02T23:42:40.000Z
src/main/java/mchorse/blockbuster/api/formats/vox/data/Vox.java
Chunk7w/blockbuster
f8df3c8d2709135512a1cdd1e08cd3545c9975bc
[ "MIT" ]
67
2016-07-11T18:27:32.000Z
2022-02-20T11:14:56.000Z
21.25
127
0.464171
9,074
package mchorse.blockbuster.api.formats.vox.data; public class Vox { public int x; public int y; public int z; public int blocks; public int[] voxels; public int toIndex(int x, int y, int z) { return x + y * this.x + z * this.x * this.y; } public boolean has(int x, int y, int z) { return x >= 0 && y >= 0 && z >= 0 && x < this.x && y < this.y && z < this.z && this.voxels[this.toIndex(x, y, z)] != 0; } public void set(int x, int y, int z, int block) { int index = this.toIndex(x, y, z); if (index < 0 || index >= this.x * this.y * this.z) { return; } int last = this.voxels[index]; this.voxels[index] = block; if (last == 0 && block != 0) { this.blocks += 1; } else if (last != 0 && block == 0) { this.blocks -= 1; } } }
3e155873069bc50c6abff3ce01bc9ffaffee483b
1,236
java
Java
ApiRest/src/main/java/com/mca/apps/lavamassapirest/payloads/request/SignUpRequest.java
MicK9323/Sistema_Lavamass-Backend
f3e5546eb3f15bad19a70aac6096fff91dc04d17
[ "MIT" ]
null
null
null
ApiRest/src/main/java/com/mca/apps/lavamassapirest/payloads/request/SignUpRequest.java
MicK9323/Sistema_Lavamass-Backend
f3e5546eb3f15bad19a70aac6096fff91dc04d17
[ "MIT" ]
null
null
null
ApiRest/src/main/java/com/mca/apps/lavamassapirest/payloads/request/SignUpRequest.java
MicK9323/Sistema_Lavamass-Backend
f3e5546eb3f15bad19a70aac6096fff91dc04d17
[ "MIT" ]
1
2019-04-19T18:23:07.000Z
2019-04-19T18:23:07.000Z
17.913043
54
0.589806
9,075
package com.mca.apps.lavamassapirest.payloads.request; public class SignUpRequest { private String dni; private String passwd; private String name; private String lastName; private String telf; private String address; private String email; public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelf() { return telf; } public void setTelf(String telf) { this.telf = telf; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
3e1558fe995a1be237c041b03db933babe035a7d
1,081
java
Java
mxlib.command/src/main/java/io/github/karlatemp/mxlib/command/CommandParameter.java
Karlatemp/mxlib
c04d532ad177463dbc0647654bf30224eaa01da3
[ "MIT" ]
5
2021-01-30T05:26:15.000Z
2021-08-31T06:11:06.000Z
mxlib.command/src/main/java/io/github/karlatemp/mxlib/command/CommandParameter.java
Karlatemp/mxlib
c04d532ad177463dbc0647654bf30224eaa01da3
[ "MIT" ]
2
2021-05-15T15:44:37.000Z
2021-06-15T14:45:44.000Z
mxlib.command/src/main/java/io/github/karlatemp/mxlib/command/CommandParameter.java
Karlatemp/mxlib
c04d532ad177463dbc0647654bf30224eaa01da3
[ "MIT" ]
1
2021-05-15T15:42:24.000Z
2021-05-15T15:42:24.000Z
21.68
99
0.636531
9,076
/* * Copyright (c) 2018-2021 Karlatemp. All rights reserved. * @author Karlatemp <upchh@example.com> <https://github.com/Karlatemp> * * MXLib/MXLib.mxlib-command.main/CommandParameter.java * * Use of this source code is governed by the MIT license that can be found via the following link. * * https://github.com/Karlatemp/MxLib/blob/master/LICENSE */ package io.github.karlatemp.mxlib.command; import io.github.karlatemp.mxlib.command.annoations.MParameter; /** * The parameter of command. * * @see io.github.karlatemp.mxlib.command.annoations.MParameter */ public interface CommandParameter { /** * Get the option name of this parameter. * * @return The option name. */ String name(); /** * The mark type. * * @return The type. */ Class<?> type(); /** * The value of {@link MParameter#description()} * * @return Parameter description. */ String description(); /** * Does this parameter must exists? * * @return Need exists. */ boolean require(); }
3e15593502dfaaf60eade2f557f998777f3de75b
487
java
Java
app/src/main/java/com/yangh/today/mvp/weight/dynamic/DefaultType.java
flybirdxx/Today
5c68fa043fa3da7b1668629fd322cec98395aed6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yangh/today/mvp/weight/dynamic/DefaultType.java
flybirdxx/Today
5c68fa043fa3da7b1668629fd322cec98395aed6
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yangh/today/mvp/weight/dynamic/DefaultType.java
flybirdxx/Today
5c68fa043fa3da7b1668629fd322cec98395aed6
[ "Apache-2.0" ]
null
null
null
19.48
60
0.679671
9,077
package com.yangh.today.mvp.weight.dynamic; import android.content.Context; import android.graphics.Canvas; /** * Created by yangH on 2019/3/16. */ class DefaultType extends BaseDynamicType { public DefaultType(Context context) { super(context, true); } @Override public boolean drawWeather(Canvas canvas, float alpha) { return false; } @Override protected int[] getSkyBackgroundGradient() { return skyBackground.BLACK; } }
3e1559d9682ffe53a32306d332e148e5173a17ba
697
java
Java
Hrms_Day9/hrms/hrms/src/main/java/kodlamaio/hrms/business/concretes/CvManager.java
BarisKocaman55/KodlamaioHomeworks
5c88e18bd5d1031a7edf9981dbbb750bab3cb780
[ "MIT" ]
3
2021-05-29T16:20:41.000Z
2021-06-02T03:51:34.000Z
Hrms_Day9/hrms/hrms/src/main/java/kodlamaio/hrms/business/concretes/CvManager.java
BarisKocaman55/KodlamaioHomeworks
5c88e18bd5d1031a7edf9981dbbb750bab3cb780
[ "MIT" ]
null
null
null
Hrms_Day9/hrms/hrms/src/main/java/kodlamaio/hrms/business/concretes/CvManager.java
BarisKocaman55/KodlamaioHomeworks
5c88e18bd5d1031a7edf9981dbbb750bab3cb780
[ "MIT" ]
null
null
null
24.892857
63
0.789096
9,078
package kodlamaio.hrms.business.concretes; import java.util.List; import org.springframework.stereotype.Service; import kodlamaio.hrms.business.abstracts.CvService; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.SuccessDataResult; import kodlamaio.hrms.dataAccess.abstracts.CvDao; import kodlamaio.hrms.entities.concretes.CvFile; @Service public class CvManager implements CvService{ private CvDao cvDao; public CvManager(CvDao cvDao) { super(); this.cvDao = cvDao; } @Override public DataResult<List<CvFile>> getAll() { return new SuccessDataResult<List<CvFile>> (this.cvDao.findAll(), "Tüm Cv'ler Görüntülendi!!!"); } }
3e155b3384e4d8fbb05c8dc97891d8a8ffed669e
5,693
java
Java
core/src/test/java/com/envimate/mapmate/deserialization/specs/UnmarshallerSpecs.java
lestephane/mapmate
1ef1d35663deb2a4eab6b892721fc43262938068
[ "Apache-2.0" ]
3
2019-06-25T05:58:10.000Z
2020-12-18T16:45:51.000Z
core/src/test/java/com/envimate/mapmate/deserialization/specs/UnmarshallerSpecs.java
lestephane/mapmate
1ef1d35663deb2a4eab6b892721fc43262938068
[ "Apache-2.0" ]
10
2018-11-07T10:35:31.000Z
2019-11-14T10:14:09.000Z
core/src/test/java/com/envimate/mapmate/deserialization/specs/UnmarshallerSpecs.java
lestephane/mapmate
1ef1d35663deb2a4eab6b892721fc43262938068
[ "Apache-2.0" ]
2
2019-06-17T13:36:11.000Z
2019-08-17T10:15:30.000Z
43.128788
122
0.615844
9,079
/* * Copyright (c) 2019 envimate GmbH - https://envimate.com/. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.envimate.mapmate.deserialization.specs; import com.envimate.mapmate.builder.recipes.marshallers.urlencoded.UrlEncodedMarshallerRecipe; import com.envimate.mapmate.domain.valid.AComplexNestedType; import com.envimate.mapmate.domain.valid.AComplexType; import com.envimate.mapmate.domain.valid.AComplexTypeWithArray; import org.junit.Test; import static com.envimate.mapmate.deserialization.specs.givenwhenthen.Given.givenTheExampleMapMateDeserializer; import static com.envimate.mapmate.deserialization.specs.instances.Instances.*; import static com.envimate.mapmate.marshalling.MarshallingType.*; public final class UnmarshallerSpecs { @Test public void testJsonUnmarshallingIsPossible() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("" + "{\n" + " \"number1\": \"1\",\n" + " \"number2\": \"5\",\n" + " \"stringA\": \"asdf\",\n" + " \"stringB\": \"qwer\"\n" + "}").as(json()).toTheType(AComplexType.class) .theDeserializedObjectIs(theFullyInitializedExampleDto()); } @Test public void testJsonUnmarshallingWithCollectionsIsPossible() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("" + "{\n" + " \"array\": [\n" + " \"1\",\n" + " \"2\"\n" + " ]\n" + "}").as(json()).toTheType(AComplexTypeWithArray.class) .theDeserializedObjectIs(theFullyInitializedExampleDtoWithCollections()); } @Test public void testXmlUnmarshallingIsPossible() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("" + "<HashMap>\n" + " <number1>1</number1>\n" + " <number2>5</number2>\n" + " <stringA>asdf</stringA>\n" + " <stringB>qwer</stringB>\n" + "</HashMap>\n").as(xml()).toTheType(AComplexType.class) .theDeserializedObjectIs(theFullyInitializedExampleDto()); } @Test public void testYamlUnmarshallingIsPossible() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("" + "number1: '1'\n" + "number2: '5'\n" + "stringA: asdf\n" + "stringB: qwer\n").as(yaml()).toTheType(AComplexType.class) .theDeserializedObjectIs(theFullyInitializedExampleDto()); } @Test public void testUrlEncodedUnmarshallingIsPossible() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("number1=1&number2=5&stringA=asdf&stringB=qwer") .as(UrlEncodedMarshallerRecipe.urlEncoded()).toTheType(AComplexType.class) .theDeserializedObjectIs(theFullyInitializedExampleDto()); } @Test public void testUrlEncodedUnmarshallingWithCollectionsIsPossible() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("array[0]=1&array[1]=2") .as(UrlEncodedMarshallerRecipe.urlEncoded()).toTheType(AComplexTypeWithArray.class) .theDeserializedObjectIs(theFullyInitializedExampleDtoWithCollections()); } @Test public void testUrlEncodedUnmarshallingWithMapsIsPossible() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("" + "complexType2[number1]=3&" + "complexType2[number2]=4&" + "complexType2[stringA]=c&" + "complexType2[stringB]=d&" + "complexType1[number1]=1&" + "complexType1[number2]=2&" + "complexType1[stringA]=a&" + "complexType1[stringB]=b").as(UrlEncodedMarshallerRecipe.urlEncoded()).toTheType(AComplexNestedType.class) .theDeserializedObjectIs(theFullyInitializedNestedExampleDto()); } @Test public void testUnknownUnmarshallerThrowsAnException() { givenTheExampleMapMateDeserializer() .when().theDeserializerDeserializes("" + "{\n" + " \"number1\": \"1\",\n" + " \"number2\": \"5\",\n" + " \"stringA\": \"asdf\",\n" + " \"stringB\": \"qwer\"\n" + "}").as(marshallingType("unknown")).toTheType(AComplexType.class) .anExceptionIsThrownWithAMessageContaining( "Unsupported marshalling type 'unknown'," + " known marshalling types are: ['urlencoded', 'json', 'xml', 'yaml']"); } }
3e155bc1185aafdc286da2eb35b664d5db2dedd8
3,035
java
Java
sagres/src/main/java/com/forcetower/sagres/database/model/SClass.java
Matoro17/Melon
34b0b27a888014f47fe45ed9b990b39a6a99ffd9
[ "MIT" ]
null
null
null
sagres/src/main/java/com/forcetower/sagres/database/model/SClass.java
Matoro17/Melon
34b0b27a888014f47fe45ed9b990b39a6a99ffd9
[ "MIT" ]
null
null
null
sagres/src/main/java/com/forcetower/sagres/database/model/SClass.java
Matoro17/Melon
34b0b27a888014f47fe45ed9b990b39a6a99ffd9
[ "MIT" ]
null
null
null
28.148148
97
0.683553
9,080
/* * Copyright (c) 2019. * João Paulo Sena <hzdkv@example.com> * * This file is part of the UNES Open Source Project. * * UNES is licensed under the MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.forcetower.sagres.database.model; import androidx.room.*; import com.google.gson.annotations.SerializedName; @Entity(indices = { @Index(value = "link", unique = true) }) public class SClass { @PrimaryKey private long id; @ColumnInfo(name = "description") @SerializedName(value = "descricao") private String description; @SerializedName(value = "tipo") private String kind; private String link; @ColumnInfo(name = "discipline_link") private String disciplineLink; @Ignore @SerializedName(value = "atividadeCurricular") private SLinker discipline; public SClass(long id, String description, String kind, String link, String disciplineLink) { this.id = id; this.description = description; this.kind = kind; this.link = link; this.disciplineLink = disciplineLink; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getDisciplineLink() { return disciplineLink; } public void setDisciplineLink(String disciplineLink) { this.disciplineLink = disciplineLink; } public SLinker getDiscipline() { return discipline; } public void setDiscipline(SLinker discipline) { this.discipline = discipline; } }
3e155bef1255eae63e70a75c642985f59aba5dca
47,491
java
Java
erp_desktop_all/src_facturacion/com/bydan/erp/facturacion/presentation/swing/jinternalframes/auxiliar/DetaNotaCreditoModel.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
1
2018-01-05T17:50:03.000Z
2018-01-05T17:50:03.000Z
erp_desktop_all/src_facturacion/com/bydan/erp/facturacion/presentation/swing/jinternalframes/auxiliar/DetaNotaCreditoModel.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
null
null
null
erp_desktop_all/src_facturacion/com/bydan/erp/facturacion/presentation/swing/jinternalframes/auxiliar/DetaNotaCreditoModel.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
null
null
null
46.152575
288
0.781137
9,081
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.facturacion.presentation.swing.jinternalframes.auxiliar; import com.bydan.erp.seguridad.business.entity.Usuario; import com.bydan.erp.seguridad.business.entity.Opcion; import com.bydan.erp.seguridad.business.entity.PerfilOpcion; import com.bydan.erp.seguridad.business.entity.PerfilCampo; import com.bydan.erp.seguridad.business.entity.PerfilAccion; import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg; import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario; import com.bydan.erp.seguridad.business.entity.Modulo; import com.bydan.erp.seguridad.business.entity.Accion; //import com.bydan.erp.seguridad.business.entity.PerfilAccion; import com.bydan.erp.seguridad.util.SistemaConstantesFunciones; import com.bydan.erp.seguridad.util.SistemaConstantesFuncionesAdditional; import com.bydan.erp.seguridad.business.logic.SistemaLogicAdditional; import com.bydan.erp.facturacion.util.DetaNotaCreditoConstantesFunciones; import com.bydan.erp.facturacion.util.DetaNotaCreditoParameterReturnGeneral; //import com.bydan.erp.facturacion.util.DetaNotaCreditoParameterGeneral; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; import com.bydan.framework.erp.business.entity.Classe; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.DatoGeneralMinimo; import com.bydan.framework.erp.business.entity.GeneralEntity; import com.bydan.framework.erp.business.entity.Mensajes; //import com.bydan.framework.erp.business.entity.MaintenanceType; import com.bydan.framework.erp.util.MaintenanceType; import com.bydan.framework.erp.util.FuncionesReporte; import com.bydan.framework.erp.business.logic.DatosCliente; import com.bydan.framework.erp.business.logic.Pagination; import com.bydan.erp.facturacion.presentation.swing.jinternalframes.DetaNotaCreditoBeanSwingJInternalFrame; import com.bydan.framework.erp.presentation.desktop.swing.TablaGeneralTotalModel; import com.bydan.framework.erp.presentation.desktop.swing.DateConverter; import com.bydan.framework.erp.presentation.desktop.swing.DateConverterFromDate; import com.bydan.framework.erp.presentation.desktop.swing.DateRenderer; import com.bydan.framework.erp.presentation.desktop.swing.DateEditorRenderer; import com.bydan.framework.erp.presentation.desktop.swing.BooleanRenderer; import com.bydan.framework.erp.presentation.desktop.swing.BooleanEditorRenderer; import com.bydan.framework.erp.presentation.desktop.swing.TextFieldRenderer; import com.bydan.framework.erp.presentation.desktop.swing.*; //import com.bydan.framework.erp.presentation.desktop.swing.TextFieldEditorRenderer; import com.bydan.framework.erp.presentation.desktop.swing.HeaderRenderer; import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase; import com.bydan.framework.erp.presentation.desktop.swing.FuncionesSwing; import com.bydan.framework.erp.presentation.desktop.swing.MainJFrame; import com.bydan.framework.erp.resources.imagenes.AuxiliarImagenes; import com.bydan.erp.facturacion.resources.reportes.AuxiliarReportes; import com.bydan.erp.facturacion.util.*; import com.bydan.erp.facturacion.business.logic.*; import com.bydan.erp.seguridad.business.logic.*; import com.bydan.erp.contabilidad.business.logic.*; import com.bydan.erp.inventario.business.logic.*; //EJB //PARAMETROS //EJB PARAMETROS import com.bydan.framework.erp.business.logic.*; import com.bydan.framework.erp.util.*; import com.bydan.erp.facturacion.business.entity.*; //import com.bydan.framework.erp.business.entity.ConexionBeanFace; //import com.bydan.framework.erp.business.entity.Mensajes; import com.bydan.erp.seguridad.presentation.swing.jinternalframes.*; import com.bydan.erp.contabilidad.presentation.swing.jinternalframes.*; import com.bydan.erp.inventario.presentation.swing.jinternalframes.*; import java.net.NetworkInterface; import java.net.InterfaceAddress; import java.net.InetAddress; import javax.naming.InitialContext; import java.lang.Long; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.io.Serializable; import java.util.Hashtable; import java.io.File; import java.io.FileInputStream; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.FileOutputStream; import java.io.InputStream; import java.io.BufferedReader; import java.io.FileReader; import java.util.HashMap; import java.util.Map; import java.io.PrintWriter; import java.sql.SQLException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.w3c.dom.Document; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.data.JRBeanArrayDataSource; import net.sf.jasperreports.view.JasperViewer; import org.apache.log4j.Logger; import com.bydan.framework.erp.business.entity.Reporte; //VALIDACION import org.hibernate.validator.ClassValidator; import org.hibernate.validator.InvalidValue; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperPrintManager; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.JasperRunManager; import net.sf.jasperreports.engine.export.JExcelApiExporter; import net.sf.jasperreports.engine.export.JRCsvExporter; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import net.sf.jasperreports.engine.util.JRSaver; import net.sf.jasperreports.engine.xml.JRXmlWriter; import com.bydan.erp.facturacion.presentation.web.jsf.sessionbean.*; import com.bydan.erp.facturacion.presentation.swing.jinternalframes.DetaNotaCreditoJInternalFrame; import com.bydan.erp.facturacion.presentation.swing.jinternalframes.DetaNotaCreditoDetalleFormJInternalFrame; import java.util.EventObject; import java.util.EventListener; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.event.*; import org.jdesktop.beansbinding.Binding.SyncFailure; import org.jdesktop.beansbinding.BindingListener; import org.jdesktop.beansbinding.Bindings; import org.jdesktop.beansbinding.BeanProperty; import org.jdesktop.beansbinding.ELProperty; import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy; import org.jdesktop.beansbinding.PropertyStateEvent; import org.jdesktop.swingbinding.JComboBoxBinding; import org.jdesktop.swingbinding.SwingBindings; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import com.bydan.erp.seguridad.business.entity.*; import com.bydan.erp.contabilidad.business.entity.*; import com.bydan.erp.inventario.business.entity.*; import com.bydan.erp.seguridad.util.*; import com.bydan.erp.contabilidad.util.*; import com.bydan.erp.inventario.util.*; import com.bydan.erp.seguridad.presentation.web.jsf.sessionbean.*; import com.bydan.erp.contabilidad.presentation.web.jsf.sessionbean.*; import com.bydan.erp.inventario.presentation.web.jsf.sessionbean.*; @SuppressWarnings("unused") public class DetaNotaCreditoModel extends FocusTraversalPolicy implements TableModel, Serializable,PropertyChangeListener { private static final long serialVersionUID = 1L; public JInternalFrameBase jInternalFrameBase; private String[] columnNames = { Constantes2.S_SELECCIONAR ,DetaNotaCreditoConstantesFunciones.LABEL_ID ,DetaNotaCreditoConstantesFunciones.LABEL_IDEMPRESA ,DetaNotaCreditoConstantesFunciones.LABEL_IDSUCURSAL ,DetaNotaCreditoConstantesFunciones.LABEL_IDEJERCICIO ,DetaNotaCreditoConstantesFunciones.LABEL_IDPERIODO ,DetaNotaCreditoConstantesFunciones.LABEL_IDANIO ,DetaNotaCreditoConstantesFunciones.LABEL_IDMES ,DetaNotaCreditoConstantesFunciones.LABEL_IDNOTACREDITO ,DetaNotaCreditoConstantesFunciones.LABEL_IDBODEGA ,DetaNotaCreditoConstantesFunciones.LABEL_IDPRODUCTO ,DetaNotaCreditoConstantesFunciones.LABEL_IDUNIDAD ,DetaNotaCreditoConstantesFunciones.LABEL_IDTIPODETANOTACREDITO ,DetaNotaCreditoConstantesFunciones.LABEL_IDTIPODEVOLUCIONEMPRESA ,DetaNotaCreditoConstantesFunciones.LABEL_DESCRIPCION ,DetaNotaCreditoConstantesFunciones.LABEL_CANTIDAD ,DetaNotaCreditoConstantesFunciones.LABEL_PRECIO ,DetaNotaCreditoConstantesFunciones.LABEL_MONTO ,DetaNotaCreditoConstantesFunciones.LABEL_COSTO ,DetaNotaCreditoConstantesFunciones.LABEL_DESCUENTO ,DetaNotaCreditoConstantesFunciones.LABEL_DESCUENTO2 ,DetaNotaCreditoConstantesFunciones.LABEL_IMPUESTO ,DetaNotaCreditoConstantesFunciones.LABEL_PORCENIVA ,DetaNotaCreditoConstantesFunciones.LABEL_PORCENDESCUEN ,DetaNotaCreditoConstantesFunciones.LABEL_PORCENICE ,DetaNotaCreditoConstantesFunciones.LABEL_SUBTOTAL ,DetaNotaCreditoConstantesFunciones.LABEL_TOTAL ,DetaNotaCreditoConstantesFunciones.LABEL_IDCENTROCOSTO ,DetaNotaCreditoConstantesFunciones.LABEL_IDEMPAQUE ,DetaNotaCreditoConstantesFunciones.LABEL_INCLUYEIMPUESTO ,DetaNotaCreditoConstantesFunciones.LABEL_FECHAEMISION ,DetaNotaCreditoConstantesFunciones.LABEL_CODIGOLOTE ,DetaNotaCreditoConstantesFunciones.LABEL_NUMEROCAJA }; public List<DetaNotaCredito> detanotacreditos; //NO SE UTILIZA public DetaNotaCreditoModel(List<DetaNotaCredito> detanotacreditos,JInternalFrameBase jInternalFrameBase) { this.detanotacreditos=detanotacreditos; this.jInternalFrameBase=jInternalFrameBase; } public DetaNotaCreditoModel(JInternalFrameBase jInternalFrameBase) { this.detanotacreditos=new ArrayList<DetaNotaCredito>(); this.jInternalFrameBase=jInternalFrameBase; } @Override public String getColumnName(int columnIndex) { return columnNames[columnIndex]; } @Override public int getRowCount() { return this.detanotacreditos.size(); } @Override public int getColumnCount() { return this.columnNames.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return this.detanotacreditos.get(rowIndex).getIsSelected(); case 1: return this.detanotacreditos.get(rowIndex).getId(); case 2: return this.detanotacreditos.get(rowIndex).getid_empresa(); case 3: return this.detanotacreditos.get(rowIndex).getid_sucursal(); case 4: return this.detanotacreditos.get(rowIndex).getid_ejercicio(); case 5: return this.detanotacreditos.get(rowIndex).getid_periodo(); case 6: return this.detanotacreditos.get(rowIndex).getid_anio(); case 7: return this.detanotacreditos.get(rowIndex).getid_mes(); case 8: return this.detanotacreditos.get(rowIndex).getid_nota_credito(); case 9: return this.detanotacreditos.get(rowIndex).getid_bodega(); case 10: return this.detanotacreditos.get(rowIndex).getid_producto(); case 11: return this.detanotacreditos.get(rowIndex).getid_unidad(); case 12: return this.detanotacreditos.get(rowIndex).getid_tipo_deta_nota_credito(); case 13: return this.detanotacreditos.get(rowIndex).getid_tipo_devolucion_empresa(); case 14: return this.detanotacreditos.get(rowIndex).getdescripcion(); case 15: return this.detanotacreditos.get(rowIndex).getcantidad(); case 16: return this.detanotacreditos.get(rowIndex).getprecio(); case 17: return this.detanotacreditos.get(rowIndex).getmonto(); case 18: return this.detanotacreditos.get(rowIndex).getcosto(); case 19: return this.detanotacreditos.get(rowIndex).getdescuento(); case 20: return this.detanotacreditos.get(rowIndex).getdescuento2(); case 21: return this.detanotacreditos.get(rowIndex).getimpuesto(); case 22: return this.detanotacreditos.get(rowIndex).getporcen_iva(); case 23: return this.detanotacreditos.get(rowIndex).getporcen_descuen(); case 24: return this.detanotacreditos.get(rowIndex).getporcen_ice(); case 25: return this.detanotacreditos.get(rowIndex).getsub_total(); case 26: return this.detanotacreditos.get(rowIndex).gettotal(); case 27: return this.detanotacreditos.get(rowIndex).getid_centro_costo(); case 28: return this.detanotacreditos.get(rowIndex).getid_empaque(); case 29: return this.detanotacreditos.get(rowIndex).getincluye_impuesto(); case 30: return this.detanotacreditos.get(rowIndex).getfecha_emision(); case 31: return this.detanotacreditos.get(rowIndex).getcodigo_lote(); case 32: return this.detanotacreditos.get(rowIndex).getnumero_caja(); default: return null; } } @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case 0: return Boolean.class; case 1: return Long.class; case 2: return Long.class; case 3: return Long.class; case 4: return Long.class; case 5: return Long.class; case 6: return Long.class; case 7: return Long.class; case 8: return Long.class; case 9: return Long.class; case 10: return Long.class; case 11: return Long.class; case 12: return Long.class; case 13: return Long.class; case 14: return String.class; case 15: return Integer.class; case 16: return Double.class; case 17: return Double.class; case 18: return Double.class; case 19: return Double.class; case 20: return Double.class; case 21: return Double.class; case 22: return Double.class; case 23: return Double.class; case 24: return Double.class; case 25: return Double.class; case 26: return Double.class; case 27: return Long.class; case 28: return Long.class; case 29: return Boolean.class; case 30: return Date.class; case 31: return String.class; case 32: return String.class; default: return String.class; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return true; case 1: return true; case 2: return true; case 3: return true; case 4: return true; case 5: return true; case 6: return true; case 7: return true; case 8: return true; case 9: return true; case 10: return true; case 11: return true; case 12: return true; case 13: return true; case 14: return true; case 15: return true; case 16: return true; case 17: return true; case 18: return true; case 19: return true; case 20: return true; case 21: return true; case 22: return true; case 23: return true; case 24: return true; case 25: return true; case 26: return true; case 27: return true; case 28: return true; case 29: return true; case 30: return true; case 31: return true; case 32: return true; default: return true; } } @Override public void setValueAt(Object value, int rowIndex, int columnIndex) { DetaNotaCredito detanotacredito = this.detanotacreditos.get(rowIndex); Boolean esCampoValor=false; String sTipo=""; DetaNotaCreditoBeanSwingJInternalFrame detanotacreditoBeanSwingJInternalFrame=(DetaNotaCreditoBeanSwingJInternalFrame)this.jInternalFrameBase; switch (columnIndex) { case 0: try {detanotacredito.setIsSelected((Boolean) value);} catch (Exception e) {e.printStackTrace();} break; case 1: try {detanotacredito.setId((Long) value);} catch (Exception e) {e.printStackTrace();} break; case 2: try {detanotacredito.setid_empresa((Long) value);detanotacredito.setempresa_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualEmpresaForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 3: try {detanotacredito.setid_sucursal((Long) value);detanotacredito.setsucursal_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualSucursalForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 4: try {detanotacredito.setid_ejercicio((Long) value);detanotacredito.setejercicio_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualEjercicioForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 5: try {detanotacredito.setid_periodo((Long) value);detanotacredito.setperiodo_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualPeriodoForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 6: try {detanotacredito.setid_anio((Long) value);detanotacredito.setanio_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualAnioForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 7: try {detanotacredito.setid_mes((Long) value);detanotacredito.setmes_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualMesForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 8: try {detanotacredito.setid_nota_credito((Long) value);detanotacredito.setnotacredito_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualNotaCreditoForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 9: try {detanotacredito.setid_bodega((Long) value);detanotacredito.setbodega_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualBodegaForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 10: try {detanotacredito.setid_producto((Long) value);detanotacredito.setproducto_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualProductoForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 11: try {detanotacredito.setid_unidad((Long) value);detanotacredito.setunidad_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualUnidadForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 12: try {detanotacredito.setid_tipo_deta_nota_credito((Long) value);detanotacredito.settipodetanotacredito_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualTipoDetaNotaCreditoForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 13: try {detanotacredito.setid_tipo_devolucion_empresa((Long) value);detanotacredito.settipodevolucionempresa_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualTipoDevolucionEmpresaForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 14: try {detanotacredito.setdescripcion((String) value);} catch (Exception e) {e.printStackTrace();} break; case 15: try {detanotacredito.setcantidad((Integer) value);} catch (Exception e) {e.printStackTrace();} break; case 16: try {detanotacredito.setprecio((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 17: try {detanotacredito.setmonto((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 18: try {detanotacredito.setcosto((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 19: try {detanotacredito.setdescuento((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 20: try {detanotacredito.setdescuento2((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 21: try {detanotacredito.setimpuesto((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 22: try {detanotacredito.setporcen_iva((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 23: try {detanotacredito.setporcen_descuen((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 24: try {detanotacredito.setporcen_ice((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 25: try {detanotacredito.setsub_total((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 26: try {detanotacredito.settotal((Double) value);esCampoValor=true;} catch (Exception e) {e.printStackTrace();} break; case 27: try {detanotacredito.setid_centro_costo((Long) value);detanotacredito.setcentrocosto_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualCentroCostoForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 28: try {detanotacredito.setid_empaque((Long) value);detanotacredito.setempaque_descripcion(detanotacreditoBeanSwingJInternalFrame.getActualEmpaqueForeignKeyDescripcion((Long)value));} catch (Exception e) {e.printStackTrace();} break; case 29: try {detanotacredito.setincluye_impuesto((Boolean) value);} catch (Exception e) {e.printStackTrace();} break; case 30: try {detanotacredito.setfecha_emision((Date) value);} catch (Exception e) {e.printStackTrace();} break; case 31: try {detanotacredito.setcodigo_lote((String) value);} catch (Exception e) {e.printStackTrace();} break; case 32: try {detanotacredito.setnumero_caja((String) value);} catch (Exception e) {e.printStackTrace();} break; } fireTableCellUpdated(rowIndex, columnIndex); if(esCampoValor) { jInternalFrameBase.procesoActualizarFilaTotales(esCampoValor,sTipo); } } //PARTE PARA EL PROPERTYVALORCHANGELISTENER //public JInternalFrameBase jInternalFrameBase; /* public DetaNotaCreditoModel(JInternalFrameBase jInternalFrameBase) { this.jInternalFrameBase=jInternalFrameBase; } */ @Override public void propertyChange(PropertyChangeEvent evt) { try { this.jInternalFrameBase.procesoActualizarFilaTotales(); } catch (Exception e) { e.printStackTrace(); } } //PARTE PARA EL PROPERTYVALORCHANGELISTENER FIN /*FUNCIONES PARA FOCUS TRAVERSAL POLICY*/ private Component componentTab=new JTextField(); private DetaNotaCreditoDetalleFormJInternalFrame detanotacreditoJInternalFrame=null; public DetaNotaCreditoModel(DetaNotaCreditoDetalleFormJInternalFrame detanotacreditoJInternalFrame) { this.detanotacreditoJInternalFrame=detanotacreditoJInternalFrame; } public Component getComponentAfter(Container focusCycleRoot, Component component) { componentTab=this.detanotacreditoJInternalFrame.getjButtonActualizarToolBarDetaNotaCredito(); if(component!=null && component.equals(this.detanotacreditoJInternalFrame.getjButtonActualizarToolBarDetaNotaCredito())) { componentTab=this.detanotacreditoJInternalFrame.getjButtonEliminarToolBarDetaNotaCredito(); return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.getjButtonEliminarToolBarDetaNotaCredito())) { componentTab=this.detanotacreditoJInternalFrame.getjButtonCancelarToolBarDetaNotaCredito(); return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.getjButtonCancelarToolBarDetaNotaCredito())) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_empresaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldnumero_cajaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxTiposAccionesFormularioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxTiposAccionesFormularioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jButtonEliminarDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jButtonEliminarDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jButtonActualizarDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jButtonActualizarDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jButtonCancelarDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_empresaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_sucursalDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_sucursalDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_ejercicioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_ejercicioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_periodoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_periodoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_anioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_anioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_mesDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_mesDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_nota_creditoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_nota_creditoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_bodegaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_bodegaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_productoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_productoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_unidadDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_unidadDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_tipo_deta_nota_creditoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_tipo_deta_nota_creditoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_tipo_devolucion_empresaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_tipo_devolucion_empresaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextAreadescripcionDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextAreadescripcionDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldcantidadDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldcantidadDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldprecioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldprecioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldmontoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldmontoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldcostoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldcostoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFielddescuentoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFielddescuentoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFielddescuento2DetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFielddescuento2DetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldimpuestoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldimpuestoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldporcen_ivaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldporcen_ivaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldporcen_descuenDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldporcen_descuenDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldporcen_iceDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldporcen_iceDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldsub_totalDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldsub_totalDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldtotalDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldtotalDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_centro_costoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_centro_costoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_empaqueDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_empaqueDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jCheckBoxincluye_impuestoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jCheckBoxincluye_impuestoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jDateChooserfecha_emisionDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jDateChooserfecha_emisionDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldcodigo_loteDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldcodigo_loteDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldnumero_cajaDetaNotaCredito; return componentTab; } return componentTab; } public Component getComponentBefore(Container focusCycleRoot, Component component) { componentTab=this.detanotacreditoJInternalFrame.getjButtonActualizarToolBarDetaNotaCredito(); if(component!=null && component.equals(this.detanotacreditoJInternalFrame.getjButtonEliminarToolBarDetaNotaCredito())) { componentTab=this.detanotacreditoJInternalFrame.getjButtonActualizarToolBarDetaNotaCredito(); return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.getjButtonCancelarToolBarDetaNotaCredito())) { componentTab=this.detanotacreditoJInternalFrame.getjButtonEliminarToolBarDetaNotaCredito(); return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_empresaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.getjButtonCancelarToolBarDetaNotaCredito(); return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxTiposAccionesFormularioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldnumero_cajaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jButtonEliminarDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxTiposAccionesFormularioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jButtonActualizarDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jButtonEliminarDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jButtonCancelarDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jButtonActualizarDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_sucursalDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_empresaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_ejercicioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_sucursalDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_periodoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_ejercicioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_anioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_periodoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_mesDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_anioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_nota_creditoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_mesDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_bodegaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_nota_creditoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_productoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_bodegaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_unidadDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_productoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_tipo_deta_nota_creditoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_unidadDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_tipo_devolucion_empresaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_tipo_deta_nota_creditoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextAreadescripcionDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_tipo_devolucion_empresaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldcantidadDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextAreadescripcionDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldprecioDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldcantidadDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldmontoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldprecioDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldcostoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldmontoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFielddescuentoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldcostoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFielddescuento2DetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFielddescuentoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldimpuestoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFielddescuento2DetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldporcen_ivaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldimpuestoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldporcen_descuenDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldporcen_ivaDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldporcen_iceDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldporcen_descuenDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldsub_totalDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldporcen_iceDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldtotalDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldsub_totalDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_centro_costoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldtotalDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jComboBoxid_empaqueDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_centro_costoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jCheckBoxincluye_impuestoDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jComboBoxid_empaqueDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jDateChooserfecha_emisionDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jCheckBoxincluye_impuestoDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldcodigo_loteDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jDateChooserfecha_emisionDetaNotaCredito; return componentTab; } if(component!=null && component.equals(this.detanotacreditoJInternalFrame.jTextFieldnumero_cajaDetaNotaCredito)) { componentTab=this.detanotacreditoJInternalFrame.jTextFieldcodigo_loteDetaNotaCredito; return componentTab; } return componentTab; } public Component getDefaultComponent(Container focusCycleRoot) { componentTab=this.detanotacreditoJInternalFrame.getjButtonActualizarToolBarDetaNotaCredito(); return componentTab; } public Component getFirstComponent(Container focusCycleRoot) { componentTab=this.detanotacreditoJInternalFrame.getjButtonActualizarToolBarDetaNotaCredito(); return componentTab; } public Component getLastComponent(Container focusCycleRoot) { componentTab=this.detanotacreditoJInternalFrame.getjButtonCancelarToolBarDetaNotaCredito(); return componentTab; } public DetaNotaCreditoDetalleFormJInternalFrame getdetanotacreditoJInternalFrame() { return this.detanotacreditoJInternalFrame; } public void setdetanotacreditoJInternalFrame(DetaNotaCreditoDetalleFormJInternalFrame detanotacreditoJInternalFrame) { this.detanotacreditoJInternalFrame=detanotacreditoJInternalFrame; } public Component getComponentTab() { return this.componentTab; } public void setComponentTab(Component componentTab) { this.componentTab=componentTab; } /*FUNCIONES PARA FOCUS TRAVERSAL POLICY FIN*/ /*FUNCIONES PARA AbstractTableModel*/ /* Notas: * Si Cambia version se copia variables y metodos que no son sobreescritos en esta clase.(Usa Jdk 8) * Se copia del Jdk javax.swing.table.AbstractTableModel * Los argumentos usados es de tipo Interface TableModel no de Clase AbstractTableModel * Si se cambia y/o actualiza jdj, toca actualizar el código nuevamente */ protected EventListenerList listenerList = new EventListenerList(); public int findColumn(String columnName) { for (int i = 0; i < getColumnCount(); i++) { if (columnName.equals(getColumnName(i))) { return i; } } return -1; } public void addTableModelListener(TableModelListener l) { listenerList.add(TableModelListener.class, l); } public void removeTableModelListener(TableModelListener l) { listenerList.remove(TableModelListener.class, l); } public TableModelListener[] getTableModelListeners() { return listenerList.getListeners(TableModelListener.class); } public void fireTableDataChanged() { fireTableChanged(new TableModelEvent(this)); } public void fireTableStructureChanged() { fireTableChanged(new TableModelEvent(this, TableModelEvent.HEADER_ROW)); } public void fireTableRowsInserted(int firstRow, int lastRow) { fireTableChanged(new TableModelEvent(this, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT)); } public void fireTableRowsUpdated(int firstRow, int lastRow) { fireTableChanged(new TableModelEvent(this, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE)); } public void fireTableRowsDeleted(int firstRow, int lastRow) { fireTableChanged(new TableModelEvent(this, firstRow, lastRow, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE)); } public void fireTableCellUpdated(int row, int column) { fireTableChanged(new TableModelEvent(this, row, row, column)); } public void fireTableChanged(TableModelEvent e) { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TableModelListener.class) { ((TableModelListener)listeners[i+1]).tableChanged(e); } } } public <T extends EventListener> T[] getListeners(Class<T> listenerType) { return listenerList.getListeners(listenerType); } /*FUNCIONES PARA AbstractTableModel FIN*/ }
3e155c55e6705e310b6ed189d50b0fe62e151c8c
798
java
Java
src/main/java/kodlamaio/hrms/entities/concretes/MernisActivation.java
semihshn/HRMS-Project
198851918df9c8cba0ea950426c5fb9b773d121c
[ "MIT" ]
11
2021-06-04T16:21:46.000Z
2022-03-11T10:44:29.000Z
src/main/java/kodlamaio/hrms/entities/concretes/MernisActivation.java
semihshn/HRMS-Project
198851918df9c8cba0ea950426c5fb9b773d121c
[ "MIT" ]
1
2021-07-12T15:33:12.000Z
2021-07-13T23:34:11.000Z
src/main/java/kodlamaio/hrms/entities/concretes/MernisActivation.java
semihshn/HRMS-Project
198851918df9c8cba0ea950426c5fb9b773d121c
[ "MIT" ]
2
2021-06-06T14:26:32.000Z
2021-06-06T14:30:37.000Z
21.567568
50
0.810777
9,082
package kodlamaio.hrms.entities.concretes; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import kodlamaio.hrms.core.entities.User; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @Table(name="mernis_activations") @AllArgsConstructor @NoArgsConstructor public class MernisActivation { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; @Column(name="is_approved") private Boolean isAproved; @ManyToOne() @JoinColumn(name="user_id") private User user; }
3e155d63a7f084922a18ce98e084ab5fbe7e8297
3,648
java
Java
components/studio-platform/plugins/org.wso2.integrationstudio.registry.base/src/org/wso2/integrationstudio/registry/base/model/RegistryUserManagerContainer.java
chanikag/integration-studio
860542074068146e95960889e281d9dbdeeaeaba
[ "Apache-2.0" ]
23
2020-12-09T09:52:23.000Z
2022-03-23T03:59:39.000Z
components/studio-platform/plugins/org.wso2.integrationstudio.registry.base/src/org/wso2/integrationstudio/registry/base/model/RegistryUserManagerContainer.java
sajithaliyanage/integration-studio
3329da9fa47e75028edf51f79264b6816bc4e333
[ "Apache-2.0" ]
751
2020-12-16T12:30:50.000Z
2022-03-31T07:53:21.000Z
components/studio-platform/plugins/org.wso2.integrationstudio.registry.base/src/org/wso2/integrationstudio/registry/base/model/RegistryUserManagerContainer.java
sajithaliyanage/integration-studio
3329da9fa47e75028edf51f79264b6816bc4e333
[ "Apache-2.0" ]
25
2020-12-09T09:52:29.000Z
2022-03-16T06:18:08.000Z
22.8
94
0.722588
9,083
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.integrationstudio.registry.base.model; import java.util.List; import org.wso2.integrationstudio.registry.base.persistent.RegistryCredentialData.Credentials; import org.wso2.integrationstudio.usermgt.remote.UserManager; public class RegistryUserManagerContainer { private static final String USER_STORE = "UserStore"; private RegistryUserContainer userContent; private RegistryUserRoleContainer userRoleContent; private RegistryNode registryNode; public RegistryNode getRegistryNode() { return registryNode; } private UserManager userManager; private boolean iterativeRefresh = false; /** * RegistryUserManagerContainer constructor * @param registryNode */ public RegistryUserManagerContainer(RegistryNode registryNode) { setRegistryNode(registryNode); } /** * return RegistryUserContainer * @return */ public RegistryUserContainer getUserContent() { if (userContent == null) { userContent = new RegistryUserContainer(this); } return userContent; } /** * return RegistryUserRoleContainer * @return */ public RegistryUserRoleContainer getUserRoleContent() { if (userRoleContent == null) { userRoleContent = new RegistryUserRoleContainer(this); } return userRoleContent; } /** * set RegistryNode instance * @param registryND */ public void setRegistryNode(RegistryNode registryND) { this.registryNode = registryND; } /** * get RegistryNode instance * @return */ public RegistryNode getRegistryData() { return registryNode; } /** * get the caption for the top level registry tree * @return */ public String getCaption() { return USER_STORE; } /** * get the user name caption */ public String toString() { return getCaption(); } /** * get credentials * @return */ public Credentials getCredentials() { return getRegistryData().getCredentials(); } /** * get user manager instance * @return */ public UserManager getUserManager() { if (userManager == null) { Credentials credentials = getCredentials(); userManager = new UserManager(registryNode.getServerUrl(), credentials.getUsername(), credentials.getPassword()); } return userManager; } public void resetUserManager(){ userManager=null; } /** * set IterativeRefresh * @param iterativeRefresh */ public void setIterativeRefresh(boolean iterativeRefresh) { this.iterativeRefresh = iterativeRefresh; } /** * * @return */ public boolean isIterativeRefresh() { if (iterativeRefresh) { getUserRoleContent().setIterativeRefresh(true); getUserContent().setIterativeRefresh(true); } return iterativeRefresh; } /** * get RegistryUser instance * @param username * @return */ public RegistryUser getUser(String username) { List<RegistryUser> users = getUserContent().getUsers(); for (RegistryUser registryUser : users) { if (registryUser.getUserName().equals(username)) return registryUser; } return null; } }
3e155de632502af0ad79a21c64ab428867aeff20
1,365
java
Java
src/org/snaker/designer/parts/LabelMidpointOffsetLocator.java
snakerflow/snaker-designer
a82e240775ca9a2330948a3a04bbbaf7ce995c0a
[ "Apache-2.0" ]
29
2015-01-31T11:33:33.000Z
2021-02-09T09:44:26.000Z
src/org/snaker/designer/parts/LabelMidpointOffsetLocator.java
x303597316/snaker-designer
a82e240775ca9a2330948a3a04bbbaf7ce995c0a
[ "Apache-2.0" ]
1
2015-06-09T08:56:29.000Z
2015-06-20T15:43:57.000Z
src/org/snaker/designer/parts/LabelMidpointOffsetLocator.java
x303597316/snaker-designer
a82e240775ca9a2330948a3a04bbbaf7ce995c0a
[ "Apache-2.0" ]
68
2015-01-23T03:48:22.000Z
2022-02-18T09:25:41.000Z
28.4375
76
0.712821
9,084
/* Copyright 2012-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.snaker.designer.parts; import org.eclipse.draw2d.Connection; import org.eclipse.draw2d.MidpointLocator; import org.eclipse.draw2d.geometry.Point; /** * 分割点位置 * @author yuqs * @version 1.0 */ public class LabelMidpointOffsetLocator extends MidpointLocator { private Point offset; public LabelMidpointOffsetLocator(Connection c, int i, Point offset) { super(c, i); this.offset = offset == null ? new Point(0, 0) : offset; } @Override protected Point getReferencePoint() { Point point = super.getReferencePoint(); return point.getTranslated(offset); } public Point getOffset() { return offset; } public void setOffset(Point offset) { this.offset = offset; } }
3e155e00b9f3f61c944a2cd3cb90e5f71d73b205
380
java
Java
gulimall-product/src/main/java/com/atguigu/gulimall/product/dao/AttrGroupDao.java
JaChin-Hu/gulimall
e835ec9bf3d3561b616de01f90cf31fbfb161df9
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/atguigu/gulimall/product/dao/AttrGroupDao.java
JaChin-Hu/gulimall
e835ec9bf3d3561b616de01f90cf31fbfb161df9
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/atguigu/gulimall/product/dao/AttrGroupDao.java
JaChin-Hu/gulimall
e835ec9bf3d3561b616de01f90cf31fbfb161df9
[ "Apache-2.0" ]
null
null
null
21.055556
67
0.765172
9,085
package com.atguigu.gulimall.product.dao; import com.atguigu.gulimall.product.entity.AttrGroupEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 属性分组 * * @author jachin * @email ychag@example.com * @date 2022-03-09 15:24:08 */ @Mapper public interface AttrGroupDao extends BaseMapper<AttrGroupEntity> { }
3e155f0f884d974b39ef963a11b2d394da906246
3,586
java
Java
jacc/contexts/src/test/java/org/javaee7/jacc/contexts/SubjectFromPolicyContextTest.java
fichtenbauer/javaee7-samples
278bf7607c523ab229ed3f2cd55c88175e32b0ec
[ "MIT" ]
2,150
2015-01-01T20:41:01.000Z
2022-03-27T19:44:00.000Z
jacc/contexts/src/test/java/org/javaee7/jacc/contexts/SubjectFromPolicyContextTest.java
fichtenbauer/javaee7-samples
278bf7607c523ab229ed3f2cd55c88175e32b0ec
[ "MIT" ]
106
2015-01-05T12:37:30.000Z
2022-01-21T23:22:50.000Z
jacc/contexts/src/test/java/org/javaee7/jacc/contexts/SubjectFromPolicyContextTest.java
fichtenbauer/javaee7-samples
278bf7607c523ab229ed3f2cd55c88175e32b0ec
[ "MIT" ]
1,669
2015-01-03T13:13:24.000Z
2022-03-22T12:21:50.000Z
40.75
127
0.738427
9,086
package org.javaee7.jacc.contexts; import static org.junit.Assert.assertTrue; import java.io.IOException; import javax.security.auth.Subject; import javax.servlet.http.HttpServletRequest; import org.javaee7.jacc.contexts.sam.SamAutoRegistrationListener; import org.javaee7.jacc.contexts.sam.TestServerAuthModule; import org.javaee7.jacc.contexts.servlet.RequestServlet; import org.javaee7.jacc.contexts.servlet.SubjectServlet; import org.javaee7.jaspic.common.ArquillianBase; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.xml.sax.SAXException; /** * This test demonstrates both how to obtain the {@link Subject} and then how to indirectly retrieve the roles from * this Subject. * <p> * This will be done by calling a Servlet that retrieves the {@link Subject} of the authenticated user. * Authentication happens via the {@link TestServerAuthModule} when the "doLogin" parameter is present in * the request. * <p> * The Subject (a "bag of principals") typically contains the user name principal that can also be obtained via * {@link HttpServletRequest#getUserPrincipal()} and may contain the roles this user has. But, it has never * been standardized in Java EE which principal (attribute) of the Subject represents the user name and * which ones represent the roles, so every container does it differently. On top of that JACC did not specify * that *the* Subject should be returned and implementations not rarely return a Subject that contains only the * user name principal instead of the real Subject with all principals. * <p> * Via a somewhat obscure workaround via JACC it's possible to fetch the roles from the Subject * in a standard way. * See <a href="https://blogs.oracle.com/monzillo/entry/using_jacc_to_determine_a">Using JACC to determine a caller's roles</a> * <p> * * * @author Arjan Tijms * */ @RunWith(Arquillian.class) public class SubjectFromPolicyContextTest extends ArquillianBase { @Deployment(testable = false) public static Archive<?> createDeployment() { WebArchive archive = ((WebArchive) ArquillianBase.defaultArchive()) .addClasses( SamAutoRegistrationListener.class, TestServerAuthModule.class, RequestServlet.class, SubjectServlet.class); return archive; } /** * Tests that we are able to obtain a reference to the {@link Subject} from a Servlet. */ @Test public void testCanObtainRequestInServlet() throws IOException, SAXException { String response = getFromServerPath("subjectServlet?doLogin=true"); assertTrue(response.contains("Obtained subject from context.")); } /** * Tests that we are able to obtain a reference to the {@link Subject} from a Servlet and * use JACC to get the roles the user from its principals. */ @Test public void testCanObtainRolesFromSubjectInServlet() throws IOException, SAXException { String response = getFromServerPath("subjectServlet?doLogin=true"); // The role that was assigned to the user in TestServerAuthModule assertTrue(response.contains("User has role architect")); // Servlet 13.3; Every authenticated user should have this role and isUserInRole should return true // when tested. assertTrue(response.contains("User has role **")); } }
3e155f51d9c528d5592166819adf17ffdc051f31
692
java
Java
jasypt-spring3-example/src/main/java/com/ambientideas/cryptography/DemoCrypt.java
matthewmccullough/encryption-jvm-bootcamp
c3d4c1bb093e3bf9d0b5d968de0e276de880189b
[ "MIT" ]
9
2015-07-20T11:35:52.000Z
2021-02-15T12:40:03.000Z
jasypt-spring3-example/src/main/java/com/ambientideas/cryptography/DemoCrypt.java
matthewmccullough/encryption-jvm-bootcamp
c3d4c1bb093e3bf9d0b5d968de0e276de880189b
[ "MIT" ]
32
2019-05-27T18:22:45.000Z
2022-03-10T19:18:32.000Z
jasypt-spring3-example/src/main/java/com/ambientideas/cryptography/DemoCrypt.java
matthewmccullough/encryption-jvm-bootcamp
c3d4c1bb093e3bf9d0b5d968de0e276de880189b
[ "MIT" ]
18
2015-09-22T08:43:16.000Z
2021-07-02T17:43:23.000Z
26.615385
70
0.723988
9,087
package com.ambientideas.cryptography; public class DemoCrypt { private String socialSecurityNumber; private String bankAccountNumber; public String getBankAccountNumber() { return bankAccountNumber; } public void setBankAccountNumber(String bankAccountNumber) { this.bankAccountNumber = bankAccountNumber; } public void setSocialSecurityNumber(String socialSecurityNumber) { this.socialSecurityNumber = socialSecurityNumber; } public String getSocialSecurityNumber() { return socialSecurityNumber; } public void printSocialSecurityNumber() { System.out.println("SSN: " + socialSecurityNumber); } }
3e155f9a3ac7a3009ce72ee096f38b6bd3e383e7
695
java
Java
src/main/java/com/codinglab/collections/doublylinkedlist/Node.java
hakimamarullah/CODINGLAB
25a50f6c45e1db784ea27eee54444e481415c842
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/codinglab/collections/doublylinkedlist/Node.java
hakimamarullah/CODINGLAB
25a50f6c45e1db784ea27eee54444e481415c842
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/codinglab/collections/doublylinkedlist/Node.java
hakimamarullah/CODINGLAB
25a50f6c45e1db784ea27eee54444e481415c842
[ "BSD-3-Clause" ]
null
null
null
15.795455
51
0.530935
9,088
package com.codinglab.collections.doublylinkedlist; public class Node<T> { private Node<T> prev, next; private T data; public Node(T data){ this.data = data; } public Node<T> getPrev() { return prev; } public void setPrev(Node<T> prev) { this.prev = prev; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Node<T> next() { return this.next; } public Node<T> prev() { return this.prev; } }
3e1560611d94584dd30b36ee0cc5d26d23939ac6
4,101
java
Java
src/simpledb/index/btree/BTreeDir.java
sathley/micro-db
455557be2ab41cafa0a23fc76348fee83a533fd2
[ "MIT" ]
6
2021-06-14T09:32:42.000Z
2021-06-28T20:34:47.000Z
src/simpledb/index/btree/BTreeDir.java
sathley/micro-db
455557be2ab41cafa0a23fc76348fee83a533fd2
[ "MIT" ]
null
null
null
src/simpledb/index/btree/BTreeDir.java
sathley/micro-db
455557be2ab41cafa0a23fc76348fee83a533fd2
[ "MIT" ]
12
2019-11-06T19:14:54.000Z
2021-10-05T02:37:55.000Z
34.754237
91
0.640575
9,089
package simpledb.index.btree; import simpledb.file.Block; import simpledb.tx.Transaction; import simpledb.record.TableInfo; import simpledb.query.Constant; /** * A B-tree directory block. * @author Edward Sciore */ public class BTreeDir { private TableInfo ti; private Transaction tx; private String filename; private BTreePage contents; /** * Creates an object to hold the contents of the specified * B-tree block. * @param blk a reference to the specified B-tree block * @param ti the metadata of the B-tree directory file * @param tx the calling transaction */ BTreeDir(Block blk, TableInfo ti, Transaction tx) { this.ti = ti; this.tx = tx; filename = blk.fileName(); contents = new BTreePage(blk, ti, tx); } /** * Closes the directory page. */ public void close() { contents.close(); } /** * Returns the block number of the B-tree leaf block * that contains the specified search key. * @param searchkey the search key value * @return the block number of the leaf block containing that search key */ public int search(Constant searchkey) { Block childblk = findChildBlock(searchkey); while (contents.getFlag() > 0) { contents.close(); contents = new BTreePage(childblk, ti, tx); childblk = findChildBlock(searchkey); } return childblk.number(); } /** * Creates a new root block for the B-tree. * The new root will have two children: * the old root, and the specified block. * Since the root must always be in block 0 of the file, * the contents of the old root will get transferred to a new block. * @param e the directory entry to be added as a child of the new root */ public void makeNewRoot(DirEntry e) { Constant firstval = contents.getDataVal(0); int level = contents.getFlag(); Block newblk = contents.split(0, level); //ie, transfer all the records DirEntry oldroot = new DirEntry(firstval, newblk.number()); insertEntry(oldroot); insertEntry(e); contents.setFlag(level+1); } /** * Inserts a new directory entry into the B-tree block. * If the block is at level 0, then the entry is inserted there. * Otherwise, the entry is inserted into the appropriate * child node, and the return value is examined. * A non-null return value indicates that the child node * split, and so the returned entry is inserted into * this block. * If this block splits, then the method similarly returns * the entry information of the new block to its caller; * otherwise, the method returns null. * @param e the directory entry to be inserted * @return the directory entry of the newly-split block, if one exists; otherwise, null */ public DirEntry insert(DirEntry e) { if (contents.getFlag() == 0) return insertEntry(e); Block childblk = findChildBlock(e.dataVal()); BTreeDir child = new BTreeDir(childblk, ti, tx); DirEntry myentry = child.insert(e); child.close(); return (myentry != null) ? insertEntry(myentry) : null; } private DirEntry insertEntry(DirEntry e) { int newslot = 1 + contents.findSlotBefore(e.dataVal()); contents.insertDir(newslot, e.dataVal(), e.blockNumber()); if (!contents.isFull()) return null; // else page is full, so split it int level = contents.getFlag(); int splitpos = contents.getNumRecs() / 2; Constant splitval = contents.getDataVal(splitpos); Block newblk = contents.split(splitpos, level); return new DirEntry(splitval, newblk.number()); } private Block findChildBlock(Constant searchkey) { int slot = contents.findSlotBefore(searchkey); if (contents.getDataVal(slot+1).equals(searchkey)) slot++; int blknum = contents.getChildNum(slot); return new Block(filename, blknum); } }
3e156106a4362e3019846e6bba4b24f9c8bb2d2c
7,591
java
Java
Final_Project/src/renderer/Renderer.java
Cambis/SWEN222_Game
4bf6d1fdc576dd276b556756712487d4372c853a
[ "Apache-2.0" ]
null
null
null
Final_Project/src/renderer/Renderer.java
Cambis/SWEN222_Game
4bf6d1fdc576dd276b556756712487d4372c853a
[ "Apache-2.0" ]
3
2015-09-27T04:34:01.000Z
2015-10-13T00:12:17.000Z
Final_Project/src/renderer/Renderer.java
Cambis/SWEN222_Game
4bf6d1fdc576dd276b556756712487d4372c853a
[ "Apache-2.0" ]
null
null
null
26.266436
77
0.673956
9,090
package renderer; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import renderer.R_Player.Team; import renderer.math.Mat4; import renderer.math.Vec3; /** * Provides a class for rendering a 3d scene to a buffered image. * * @author Stephen Thompson * ID: 300332215 */ public class Renderer { // The map of all model data stored inside the scene private ConcurrentHashMap<String, R_AbstractModelData> modelDataMap; // The map of all models inside the scene private ConcurrentHashMap<String, R_AbstractModel> modelMap; // The map of all cameras inside the scene private ConcurrentHashMap<String, R_AbstractCamera> cameraMap; // The map of all players inside the scene private ConcurrentHashMap<String, R_Player> playerMap; // The currently selected camera to use private R_AbstractCamera currentCam; // The currently team to view; private R_Player.Team side = R_Player.Team.SPY; // The map private int[][] shadowMap = new int[1][1]; private int tileSize = 10; // Defines the rendered image's width and height private int width; private int height; /** * Constructs a new Renderer object. The new renderer object has a default * camera named "default". * * @param width * the width of the rendered image * @param height * the height of the rendered image */ public Renderer(int width, int height) { this.width = width; this.height = height; this.currentCam = new R_OrthoCamera("default", new Vec3(1, 1, 1), Vec3.Zero(), Vec3.UnitY(), 1, 1000, 1); currentCam.setAspect(1.f * width / height); modelDataMap = new ConcurrentHashMap<String, R_AbstractModelData>(); modelMap = new ConcurrentHashMap<String, R_AbstractModel>(); cameraMap = new ConcurrentHashMap<String, R_AbstractCamera>(); playerMap = new ConcurrentHashMap<String, R_Player>(); addCamera(currentCam); } /** * Adds a new model to the scene, returning false if a model with the same * name already exists * * @param m * the new model * @return whether the model was successfully added or not */ public boolean addModel(R_AbstractModel m) { if(m==null){ return false; } if (modelMap.containsKey(m.getName())) { return false; } modelMap.put(m.getName(), m); if (m instanceof R_Player) { playerMap.put(m.getName(), (R_Player) m); } return true; } /** * Gets the model with the name "name" in the scene * * @param name * the name of the model to get * @return the model with the name "name" or null if the model does not * exist */ public R_AbstractModel getModel(String name) { return modelMap.get(name); } /** * Removes the model with the passed in name from the scene, returning false * if a model does not exist * * @param m * the model's name * @return whether the model was successfully removed or not */ public boolean deleteModel(String name) { if (!modelMap.containsKey(name)) { return false; } if (playerMap.containsKey(name)) { playerMap.remove(name); } modelMap.remove(name); return true; } /** * Adds a new model to the scene, returning false if a model with the same * name already exists * * @param m * the new model * @return whether the model was successfully added or not */ public boolean addModelData(R_AbstractModelData m) { if (modelDataMap.containsKey(m.getName())) { return false; } modelDataMap.put(m.getName(), m); return true; } /** * Gets the model with the name "name" in the scene * * @param name * the name of the model to get * @return the model with the name "name" or null if the model does not * exist */ public R_AbstractModelData getModelData(String name) { return modelDataMap.get(name); } /** * Adds a new camera to the scene, returning false if a camera with the same * name already exists * * @param c * the new camera * @return whether the camera was successfully added or not */ public boolean addCamera(R_AbstractCamera c) { if (cameraMap.containsKey(c.getName())) { return false; } cameraMap.put(c.getName(), c); return true; } /** * Removes the camera with the passed in name from the scene, returning * false if a camera does not exist * * @param c * the camera's name * @return whether the camera was successfully removed or not */ public boolean deleteCamera(String name) { if (currentCam.getName().equals(name) || cameraMap.containsKey(name)) { return false; } cameraMap.remove(name); return true; } /** * Gets the camera with the name "name" in the scene * * @param name * the name of the camera to get * @return the camera with the name "name" or null if the camera does not * exist */ public R_AbstractCamera getCamera(String name) { return cameraMap.get(name); } /** * Sets the current camera used by the renderer to render the scene. Returns * true if the camera is successfully set. * * @param name * the camera's name * @return boolean */ public boolean setCamera(String name) { if (!cameraMap.containsKey(name)) { return false; } currentCam = cameraMap.get(name); currentCam.setAspect(1.f * width / height); return true; } /** * Changes the size of the render. * * @param width * the new width of the render * @param height * the new height of the render */ public void resize(int width, int height) { this.width = width+5; this.height = height; currentCam.setAspect(1.f * width / height); } /** * Sets the map grid for shadow mapping * * @param newShadowMap the array representing the walls on the map */ public void setMap(int[][] newShadowMap){ shadowMap = newShadowMap; } /** * Renders the scene and returns a buffered image of the render * * @return the BufferedImage of the rendered scene */ public BufferedImage render() { BufferedImage viewport = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); float zBuffer[][] = new float[width][height]; // Refresh Buffers for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { zBuffer[x][y] = Float.MAX_VALUE; } } /** Create Matrix Stack **/ Mat4 matrixStack = Mat4.createIdentity(); // Scale the image to fit the window matrixStack = matrixStack.mul(Mat4 .createScale(width / 2, height / 2, 1)); // Move the image to fit inside the window matrixStack = matrixStack.mul(Mat4.createTranslate(1, 1, 1)); // Project image to window coordinates matrixStack = matrixStack.mul(currentCam.getProjection()); // transform image to camera coordinates matrixStack = matrixStack.mul(currentCam.getLookAt()); int[] buf = ((DataBufferInt) viewport.getRaster().getDataBuffer()) .getData(); List<Light> lights = new ArrayList<Light>(); for (R_Player m : playerMap.values()) { lights.add(new Light(m.getPosition(), m.getOrientation(), m.getSide())); } // Draw Model final Mat4 matrix = matrixStack; for (R_AbstractModel m : modelMap.values()) { R_Player.Team visible = R_Player.Team.SCENE; if (m instanceof R_Player){ visible = ((R_Player)m).getSide(); } m.draw(buf, zBuffer, viewport.getWidth(), viewport.getHeight(), matrix, lights, side, visible, shadowMap, tileSize); } return viewport; } public void setTeam(Team rteam) { side = rteam; } }
3e156132618daff7883e38dc607c3dec19ff70a7
1,580
java
Java
src/main/java/graph/Graph.java
harishsharma/junk
70d92242d18b54bbe2faa0957af88db0addebfed
[ "Apache-2.0" ]
1
2021-12-01T21:01:35.000Z
2021-12-01T21:01:35.000Z
src/main/java/graph/Graph.java
harishsharma/junk
70d92242d18b54bbe2faa0957af88db0addebfed
[ "Apache-2.0" ]
null
null
null
src/main/java/graph/Graph.java
harishsharma/junk
70d92242d18b54bbe2faa0957af88db0addebfed
[ "Apache-2.0" ]
null
null
null
20.25641
60
0.444937
9,091
package graph; import java.util.LinkedList; /** * * @author harish.sharma * */ public class Graph { private int V; private int E; private LinkedList<Integer>[] adjList; @SuppressWarnings("unchecked") public Graph(int V) { this.V = V; this.E = 0; adjList = (LinkedList<Integer>[]) new LinkedList[V]; for (int i = 0; i < V; i++) { adjList[i] = new LinkedList<>(); } } public int V() { return V; } public int E() { return E; } public void addEdge(int a, int b) { adjList[a].add(b); adjList[b].add(a); E++; } public Iterable<Integer> adj(int v) { return adjList[v]; } @Override public String toString() { String s = V + " vertices, " + E + " edges\n"; for (int v = 0; v < V; v++) { s += v + ": "; for (int w : this.adj(v)) s += w + " "; s += "\n"; } return s; } public static int degree(Graph g, int v) { int count = 0; for (@SuppressWarnings("unused") Integer a : g.adj(v)) { count++; } return count; } public static int maxDegree(Graph g) { Integer max = Integer.MIN_VALUE; for (int i = 0; i < g.V; i++) { int deg = degree(g, i); max = Math.max(deg, max); } return max; } public static int avgDegree(Graph g) { return 2 * g.E / g.E; } }
3e15619c5c40d6606bb874a28ec0a9d6dd12ba8b
542
java
Java
src/main/resources/archetype-resources/server/src/main/java/api/responses/GetAgentTimeOfDayCmdResponse.java
mlsorensen/acs-plugin-archetype
27083f26f63e646e6c650b64a914f4e820f4b6f7
[ "Apache-2.0" ]
2
2019-09-09T23:52:01.000Z
2019-09-10T00:20:35.000Z
src/main/resources/archetype-resources/server/src/main/java/api/responses/GetAgentTimeOfDayCmdResponse.java
mlsorensen/acs-plugin-archetype
27083f26f63e646e6c650b64a914f4e820f4b6f7
[ "Apache-2.0" ]
2
2020-03-04T23:18:44.000Z
2020-04-23T18:54:37.000Z
src/main/resources/archetype-resources/server/src/main/java/api/responses/GetAgentTimeOfDayCmdResponse.java
mlsorensen/acs-plugin-archetype
27083f26f63e646e6c650b64a914f4e820f4b6f7
[ "Apache-2.0" ]
null
null
null
24.636364
92
0.732472
9,092
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.api.responses; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; import org.apache.cloudstack.api.BaseResponse; public class GetAgentTimeOfDayCmdResponse extends BaseResponse { @SerializedName("agenttime") @Param(description="The time of day from CloudStack agent") private String agentTime; public GetAgentTimeOfDayCmdResponse(String time) { this.agentTime = time; } }
3e156211a3ca301b03b760b0e5f847afd9355df1
2,515
java
Java
src/main/java/org/paukov/combinatorics3/SimpleCombinationGenerator.java
kotomord/lidia_memory
5e849e59001ba84595a24c65c6eddbb567f02297
[ "MIT" ]
null
null
null
src/main/java/org/paukov/combinatorics3/SimpleCombinationGenerator.java
kotomord/lidia_memory
5e849e59001ba84595a24c65c6eddbb567f02297
[ "MIT" ]
null
null
null
src/main/java/org/paukov/combinatorics3/SimpleCombinationGenerator.java
kotomord/lidia_memory
5e849e59001ba84595a24c65c6eddbb567f02297
[ "MIT" ]
null
null
null
28.590909
99
0.704293
9,093
/** * Combinatorics Library 3 * Copyright 2009-2016 Dmytro Paukov kenaa@example.com */ package org.paukov.combinatorics3; import java.util.*; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * This generator generates simple combinations from specified core set by * specified length. Core set and length are specified in the constructor of * generator * <p> * A simple k-combination of a finite set S is a subset of k distinct elements * of S. Specifying a subset does not arrange them in a particular order. As an * example, a poker hand can be described as a 5-combination of cards from a * 52-card deck: the 5 cards of the hand are all distinct, and the order of the * cards in the hand does not matter. * <p> * Example. Generate 3-combination of the set (red, black, white, green, blue). * <p> * <blockquote> * * <pre> * * // Create the initial vector * ICombinatoricsVector&lt;String&gt; initialVector = Factory.createVector(new String[] { * &quot;red&quot;, &quot;black&quot;, &quot;white&quot;, &quot;green&quot;, &quot;blue&quot; }); * * // Create a simple combination generator to generate 3-combinations of the * // initial vector * Generator&lt;String&gt; gen = Factory.createSimpleCombinationGenerator(initialVector, * 3); * * // Print all possible combinations * for (ICombinatoricsVector&lt;String&gt; combination : gen) { * System.out.println(combination); * } * </pre> * * </blockquote> * <p> * * @author Dmytro Paukov * @version 3.0 * @see SimpleCombinationIterator * @param <T> * Type of elements in the combination */ class SimpleCombinationGenerator<T> implements IGenerator<List<T>> { final List<T> originalVector; final int combinationLength; /** * Constructor * * @param originalVector * Original vector which is used for generating the combination * @param combinationsLength * Length of the combinations */ SimpleCombinationGenerator(Collection<T> originalVector, int combinationsLength) { this.originalVector = new ArrayList<>(originalVector); this.combinationLength = combinationsLength; } /** * Creates an iterator of the simple combinations (without repetitions) */ @Override public Iterator<List<T>> iterator() { return new SimpleCombinationIterator<T>(this); } @Override public Stream<List<T>> stream() { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator(), 0), false); } }
3e15621b7effe674964a441d2def7509cc83d9cc
11,322
java
Java
Contable/src/contable/ProgressActualizar.java
lrueda9/ContableSale
e56ddabb3c910bf4572e8ce4fa4de8b8091138f5
[ "Apache-2.0" ]
null
null
null
Contable/src/contable/ProgressActualizar.java
lrueda9/ContableSale
e56ddabb3c910bf4572e8ce4fa4de8b8091138f5
[ "Apache-2.0" ]
null
null
null
Contable/src/contable/ProgressActualizar.java
lrueda9/ContableSale
e56ddabb3c910bf4572e8ce4fa4de8b8091138f5
[ "Apache-2.0" ]
null
null
null
29.180412
129
0.513425
9,094
package contable; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import javax.swing.JTextArea; import javax.swing.SwingWorker; public class ProgressActualizar extends SwingWorker<Integer, String> { private JLabel label1, label2; private JTextArea area; private JProgressBar jpbar; public ProgressActualizar(JLabel label1, JLabel label2, JTextArea area, JProgressBar jpbar) { this.label1 = label1; this.label2 = label2; this.area = area; this.jpbar = jpbar; } @Override protected Integer doInBackground() throws Exception { getLabel1().setVisible(true); getLabel2().setVisible(true); getJpbar().setIndeterminate(true); String url = "http://206.190.134.164/~intelicontable/Contable/Contable.jar"; String name = "Contable.jar"; File file = new File(name); URLConnection conn = new URL(url).openConnection(); conn.connect(); InputStream in = conn.getInputStream(); OutputStream out = new FileOutputStream(file); int b = 0; getLabel2().setText("Descargando: Contable.jar"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("Contable.jar"); url = "http://206.190.134.164/~intelicontable/Contable/CuentasCobrar.jasper"; name = "CuentasCobrar.jasper"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: CuentasCobrar.jasper"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nCuentasCobrar.jasper"); url = "http://206.190.134.164/~intelicontable/Contable/CuentasCobrar.jrxml"; name = "CuentasCobrar.jrxml"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: CuentasCobrar.jrxml"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nCuentasCobrar.jrxml"); url = "http://206.190.134.164/~intelicontable/Contable/Empresa.jpg"; name = "Empresa.jpg"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: Empresa.jpg"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nEmpresa.jpg"); url = "http://206.190.134.164/~intelicontable/Contable/Factura.jasper"; name = "Factura.jasper"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: Factura.jasper"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nFactura.jasper"); url = "http://206.190.134.164/~intelicontable/Contable/Factura.jrxml"; name = "Factura.jrxml"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: Factura.jrxml"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nFactura.jrxml"); url = "http://206.190.134.164/~intelicontable/Contable/OrdenCompra.jasper"; name = "OrdenCompra.jasper"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: OrdenCompra.jasper"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nOrdenCompra.jasper"); url = "http://206.190.134.164/~intelicontable/Contable/OrdenCompra.jrxml"; name = "OrdenCompra.jrxml"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: OrdenCompra.jrxml"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nOrdenCompra.jrxml"); url = "http://206.190.134.164/~intelicontable/Contable/Produccion.jasper"; name = "Produccion.jasper"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: Produccion.jasper"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nProduccion.jasper"); url = "http://206.190.134.164/~intelicontable/Contable/Produccion.jrxml"; name = "Produccion.jrxml"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: Produccion.jrxml"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nProduccion.jrxml"); url = "http://206.190.134.164/~intelicontable/Contable/ProductosComprados.jasper"; name = "ProductosComprados.jasper"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: ProductosComprados.jasper"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nProductosComprados.jasper"); url = "http://206.190.134.164/~intelicontable/Contable/ProductosComprados.jrxml"; name = "ProductosComprados.jrxml"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: ProductosComprados.jrxml"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nProductosComprados.jrxml"); url = "http://206.190.134.164/~intelicontable/Contable/ProductosVendidos.jasper"; name = "ProductosVendidos.jasper"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: ProductosVendidos.jasper"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nProductosVendidos.jasper"); url = "http://206.190.134.164/~intelicontable/Contable/ProductosVendidos.jrxml"; name = "ProductosVendidos.jrxml"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: ProductosVendidos.jrxml"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nProductosVendidos.jrxml"); url = "http://206.190.134.164/~intelicontable/Contable/warning.png"; name = "warning.png"; file = new File(name); conn = new URL(url).openConnection(); conn.connect(); in = conn.getInputStream(); out = new FileOutputStream(file); b = 0; getLabel2().setText("Descargando: warning.png"); while (b != -1) { b = in.read(); if (b != -1) { out.write(b); } } out.close(); in.close(); getArea().append("\nwarning.png"); JOptionPane.showMessageDialog(null, "Actualizacion completada correctamente\nReinicie el programa para ver los cambios"); getLabel1().setVisible(false); getLabel2().setVisible(false); getJpbar().setIndeterminate(false); return 0; } /** * @return the label1 */ public JLabel getLabel1() { return label1; } /** * @param label1 the label1 to set */ public void setLabel1(JLabel label1) { this.label1 = label1; } /** * @return the label2 */ public JLabel getLabel2() { return label2; } /** * @param label2 the label2 to set */ public void setLabel2(JLabel label2) { this.label2 = label2; } /** * @return the area */ public JTextArea getArea() { return area; } /** * @param area the area to set */ public void setArea(JTextArea area) { this.area = area; } /** * @return the jpbar */ public JProgressBar getJpbar() { return jpbar; } /** * @param jpbar the jpbar to set */ public void setJpbar(JProgressBar jpbar) { this.jpbar = jpbar; } }
3e1562244679c43bb564cd6eda79fdc30a439688
3,474
java
Java
src/main/java/com/android/volley/NetworkDispatcher.java
JackChan1999/boohee_v5.6
221f7ea237f491e2153039a42941a515493ba52c
[ "Apache-2.0" ]
7
2017-05-30T12:01:38.000Z
2021-04-22T12:22:39.000Z
src/main/java/com/android/volley/NetworkDispatcher.java
JackChan1999/boohee_v5.6
221f7ea237f491e2153039a42941a515493ba52c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/android/volley/NetworkDispatcher.java
JackChan1999/boohee_v5.6
221f7ea237f491e2153039a42941a515493ba52c
[ "Apache-2.0" ]
6
2017-07-28T03:47:08.000Z
2019-06-28T17:57:50.000Z
40.870588
120
0.561025
9,095
package com.android.volley; import android.annotation.TargetApi; import android.net.TrafficStats; import android.os.Build.VERSION; import android.os.Process; import android.os.SystemClock; import java.util.concurrent.BlockingQueue; public class NetworkDispatcher extends Thread { private final Cache mCache; private final ResponseDelivery mDelivery; private final Network mNetwork; private final BlockingQueue<Request<?>> mQueue; private volatile boolean mQuit = false; public NetworkDispatcher(BlockingQueue<Request<?>> queue, Network network, Cache cache, ResponseDelivery delivery) { this.mQueue = queue; this.mNetwork = network; this.mCache = cache; this.mDelivery = delivery; } public void quit() { this.mQuit = true; interrupt(); } @TargetApi(14) private void addTrafficStatsTag(Request<?> request) { if (VERSION.SDK_INT >= 14) { TrafficStats.setThreadStatsTag(request.getTrafficStatsTag()); } } public void run() { VolleyError volleyError; Process.setThreadPriority(10); while (true) { long startTimeMs = SystemClock.elapsedRealtime(); try { Request<?> request = (Request) this.mQueue.take(); try { request.addMarker("network-queue-take"); if (request.isCanceled()) { request.finish("network-discard-cancelled"); } else { addTrafficStatsTag(request); NetworkResponse networkResponse = this.mNetwork.performRequest(request); request.addMarker("network-http-complete"); if (networkResponse.notModified && request.hasHadResponseDelivered()) { request.finish("not-modified"); } else { Response<?> response = request.parseNetworkResponse(networkResponse); request.addMarker("network-parse-complete"); if (request.shouldCache() && response.cacheEntry != null) { this.mCache.put(request.getCacheKey(), response.cacheEntry); request.addMarker("network-cache-written"); } request.markDelivered(); this.mDelivery.postResponse(request, response); } } } catch (VolleyError volleyError2) { volleyError2.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); parseAndDeliverNetworkError(request, volleyError2); } catch (Throwable e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); volleyError2 = new VolleyError(e); volleyError2.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); this.mDelivery.postError(request, volleyError2); } } catch (InterruptedException e2) { if (this.mQuit) { return; } } } } private void parseAndDeliverNetworkError(Request<?> request, VolleyError error) { this.mDelivery.postError(request, request.parseNetworkError(error)); } }
3e15629ef87543ed56e086ade35dfa9c1952dd09
303
java
Java
src/test/java/examples/StaticProvider.java
automationhacks/grasp-java
1f42244048190b490a9c3d13e063b8cfe5c8977a
[ "Apache-2.0" ]
null
null
null
src/test/java/examples/StaticProvider.java
automationhacks/grasp-java
1f42244048190b490a9c3d13e063b8cfe5c8977a
[ "Apache-2.0" ]
1
2020-06-04T02:22:14.000Z
2020-06-04T02:22:14.000Z
src/test/java/examples/StaticProvider.java
gaurav-singh/grasp-java
1f42244048190b490a9c3d13e063b8cfe5c8977a
[ "Apache-2.0" ]
null
null
null
20.2
53
0.607261
9,096
package examples; import org.testng.annotations.DataProvider; public class StaticProvider { @DataProvider(name = "getUserIncome") public static Object[][] staticProviderMethod() { Object[][] data = new Object[][] { {10000}, {20000} }; return data; } }
3e15647c7c0dfeacd3c94ac2724e7424f8494442
12,970
java
Java
src/main/java/org/swrlapi/builtins/arguments/SWRLBuiltInResultArgumentHandler.java
RalphBln/swrlapi
a8df6e0a5a0ff5920d19d0fcda0517c32c13b68e
[ "BSD-2-Clause" ]
89
2015-04-20T07:49:38.000Z
2022-03-05T15:52:21.000Z
src/main/java/org/swrlapi/builtins/arguments/SWRLBuiltInResultArgumentHandler.java
RalphBln/swrlapi
a8df6e0a5a0ff5920d19d0fcda0517c32c13b68e
[ "BSD-2-Clause" ]
76
2015-04-06T17:45:03.000Z
2022-03-17T17:51:03.000Z
src/main/java/org/swrlapi/builtins/arguments/SWRLBuiltInResultArgumentHandler.java
RalphBln/swrlapi
a8df6e0a5a0ff5920d19d0fcda0517c32c13b68e
[ "BSD-2-Clause" ]
48
2015-01-31T18:21:51.000Z
2022-02-21T14:59:55.000Z
52.298387
116
0.771858
9,097
package org.swrlapi.builtins.arguments; import org.checkerframework.checker.nullness.qual.NonNull; import org.semanticweb.owlapi.model.OWLLiteral; import org.swrlapi.exceptions.SWRLBuiltInException; import org.swrlapi.literal.XSDDate; import org.swrlapi.literal.XSDDateTime; import org.swrlapi.literal.XSDDuration; import org.swrlapi.literal.XSDTime; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; import java.util.Map; /** * This interface defines utility methods for built-in implementations to handle result processing. * <p> * Each method will take a list of built-in arguments, an index of a particular argument, and a generated result * argument of a particular type. It will determine if the specified argument and the generated result arguments are * equal, in which case it will evaluate to true; otherwise it will evaluate to false. * * @see org.swrlapi.builtins.AbstractSWRLBuiltInLibrary */ public interface SWRLBuiltInResultArgumentHandler { /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the byte result argument * @param generatedResultArgument The generated result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, byte generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated short result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, short generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated int result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, int generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated long result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, long generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated float result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, float generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated double result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, double generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated big decimal result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, BigDecimal generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated big integer result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, BigInteger generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated string result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, String generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated boolean result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, boolean generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated time result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull XSDTime generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated date result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull XSDDate generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated datetime result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull XSDDateTime generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated duration result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull XSDDuration generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArguments The generated result arguments * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull Collection<@NonNull SWRLBuiltInArgument> generatedResultArguments) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull SWRLBuiltInArgument generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated OWL literal argument result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull SWRLLiteralBuiltInArgument generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param resultArgumentNumber The index of the result argument * @param generatedResultArgument The generated OWL literal result argument * @return If the specified argument is equal to the generated result argument * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultArgument(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, int resultArgumentNumber, @NonNull OWLLiteral generatedResultArgument) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @return A map of built-in argument numbers to built-in arguments * @throws SWRLBuiltInException If an error occurs during processing */ @NonNull Map<@NonNull Integer, @NonNull SWRLMultiValueVariableBuiltInArgument> createOutputMultiValueArguments( @NonNull List<@NonNull SWRLBuiltInArgument> arguments) throws SWRLBuiltInException; /** * @param arguments A list of built-in arguments * @param outputMultiValueArguments A generated map of built-in argument numbers to built-in arguments * @return True if the predicate is satisfied * @throws SWRLBuiltInException If an error occurs during processing */ boolean processResultMultiValueArguments(@NonNull List<@NonNull SWRLBuiltInArgument> arguments, @NonNull Map<@NonNull Integer, @NonNull SWRLMultiValueVariableBuiltInArgument> outputMultiValueArguments) throws SWRLBuiltInException; /** * * @param value A double literal value * @param boundInputNumericArguments A list of numeric arguments * @return The literal with the least narrow type * @throws SWRLBuiltInException If an error occurs during processing */ @NonNull SWRLLiteralBuiltInArgument createLeastNarrowNumericLiteralBuiltInArgument(double value, @NonNull List<@NonNull SWRLBuiltInArgument> boundInputNumericArguments) throws SWRLBuiltInException; /** * * @param value A BigDecimal value * @param boundInputNumericArguments A list of numeric arguments * @return The literal with the least narrow type * @throws SWRLBuiltInException If an error occurs during processing */ @NonNull SWRLLiteralBuiltInArgument createLeastNarrowNumericLiteralBuiltInArgument( @NonNull BigDecimal value, @NonNull List<@NonNull SWRLBuiltInArgument> boundInputNumericArguments) throws SWRLBuiltInException; }
3e1565089e1f47c0bbcb840ce7873e390febcfc9
381
java
Java
test/java/be/bagofwords/minidepi/testbeans/Plugin.java
koendeschacht/mini-dep-i
959e18343e2e926195a7047ce667d464bf9656ed
[ "MIT" ]
null
null
null
test/java/be/bagofwords/minidepi/testbeans/Plugin.java
koendeschacht/mini-dep-i
959e18343e2e926195a7047ce667d464bf9656ed
[ "MIT" ]
null
null
null
test/java/be/bagofwords/minidepi/testbeans/Plugin.java
koendeschacht/mini-dep-i
959e18343e2e926195a7047ce667d464bf9656ed
[ "MIT" ]
null
null
null
38.7
80
0.45478
9,098
/******************************************************************************* * Created by Koen Deschacht (nnheo@example.com) 2017-3-11. For license * information see the LICENSE file in the root folder of this repository. ******************************************************************************/ package be.bagofwords.minidepi.testbeans; public interface Plugin { }
3e15652c5c67e97efc4e31bb9ce7ad4a5784afea
1,035
java
Java
src/test/java/ampcontrol/model/training/schedule/epoch/OffsetTest.java
DrChainsaw/AmpControl
c6d3f20f431b4fa767c86c0d665bba710ee078e9
[ "MIT" ]
5
2018-03-18T15:09:44.000Z
2020-09-01T08:31:26.000Z
src/test/java/ampcontrol/model/training/schedule/epoch/OffsetTest.java
DrChainsaw/AmpControl
c6d3f20f431b4fa767c86c0d665bba710ee078e9
[ "MIT" ]
15
2018-03-18T21:09:28.000Z
2020-10-16T18:49:26.000Z
src/test/java/ampcontrol/model/training/schedule/epoch/OffsetTest.java
DrChainsaw/AmpControl
c6d3f20f431b4fa767c86c0d665bba710ee078e9
[ "MIT" ]
1
2020-02-11T04:48:07.000Z
2020-02-11T04:48:07.000Z
27.972973
105
0.692754
9,099
package ampcontrol.model.training.schedule.epoch; import ampcontrol.model.training.schedule.ScheduleBaseTest; import org.junit.Test; import org.nd4j.linalg.schedule.ISchedule; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; /** * Test cases for {@link Offset} * * @author Christian Skärby */ public class OffsetTest extends ScheduleBaseTest { @Override protected ISchedule createBaseTestInstance() { return new Offset(17, new Linear(2.34)); } @Test public void testValueAt() { final int offset = 13; final ISchedule base = new Linear(3.45); final ISchedule sched = new Offset(offset, base); assertNotEquals("Need different values for test case to test anything!", sched.valueAt(0, 1), sched.valueAt(0, 2)); IntStream.range(0,7).forEach(epoch -> assertEquals("Incorrect value!", base.valueAt(0, offset+epoch), sched.valueAt(0, epoch), 1e-10)); } }
3e156661c5121420d70691d65b021d64a3259e07
66,752
java
Java
Android/android-30/android30_code_view/src/com/company/source/com/android/internal/telephony/PhoneSwitcher.java
jaylinjiehong/-
591834e6d90ec8fbfd6c1d2a0913631f9f723a0a
[ "MIT" ]
null
null
null
Android/android-30/android30_code_view/src/com/company/source/com/android/internal/telephony/PhoneSwitcher.java
jaylinjiehong/-
591834e6d90ec8fbfd6c1d2a0913631f9f723a0a
[ "MIT" ]
null
null
null
Android/android-30/android30_code_view/src/com/company/source/com/android/internal/telephony/PhoneSwitcher.java
jaylinjiehong/-
591834e6d90ec8fbfd6c1d2a0913631f9f723a0a
[ "MIT" ]
null
null
null
47.041579
100
0.655965
9,100
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony; import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR; import static android.telephony.CarrierConfigManager.KEY_DATA_SWITCH_VALIDATION_TIMEOUT_LONG; import static android.telephony.SubscriptionManager.DEFAULT_SUBSCRIPTION_ID; import static android.telephony.SubscriptionManager.INVALID_PHONE_INDEX; import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID; import static android.telephony.TelephonyManager.SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION; import static android.telephony.TelephonyManager.SET_OPPORTUNISTIC_SUB_SUCCESS; import static android.telephony.TelephonyManager.SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED; import static java.util.Arrays.copyOf; import android.compat.annotation.UnsupportedAppUsage; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.MatchAllNetworkSpecifier; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkFactory; import android.net.NetworkRequest; import android.net.NetworkSpecifier; import android.net.TelephonyNetworkSpecifier; import android.os.AsyncResult; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.PersistableBundle; import android.os.Registrant; import android.os.RegistrantList; import android.os.RemoteException; import android.telephony.CarrierConfigManager; import android.telephony.PhoneCapability; import android.telephony.PhoneStateListener; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.telephony.TelephonyRegistryManager; import android.telephony.data.ApnSetting; import android.util.LocalLog; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.telephony.SubscriptionController.WatchedInt; import com.android.internal.telephony.dataconnection.ApnConfigTypeRepository; import com.android.internal.telephony.dataconnection.DcRequest; import com.android.internal.telephony.metrics.TelephonyMetrics; import com.android.internal.telephony.nano.TelephonyProto.TelephonyEvent; import com.android.internal.telephony.nano.TelephonyProto.TelephonyEvent.DataSwitch; import com.android.internal.telephony.nano.TelephonyProto.TelephonyEvent.OnDemandDataSwitch; import com.android.internal.util.IndentingPrintWriter; import com.android.telephony.Rlog; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; /** * Utility singleton to monitor subscription changes and incoming NetworkRequests * and determine which phone/phones are active. * * Manages the ALLOW_DATA calls to modems and notifies phones about changes to * the active phones. Note we don't wait for data attach (which may not happen anyway). */ public class PhoneSwitcher extends Handler { private static final String LOG_TAG = "PhoneSwitcher"; protected static final boolean VDBG = false; private static final int DEFAULT_NETWORK_CHANGE_TIMEOUT_MS = 5000; private static final int MODEM_COMMAND_RETRY_PERIOD_MS = 5000; // After the emergency call ends, wait for a few seconds to see if we enter ECBM before starting // the countdown to remove the emergency DDS override. @VisibleForTesting // not final for testing. public static int ECBM_DEFAULT_DATA_SWITCH_BASE_TIME_MS = 5000; // Wait for a few seconds after the override request comes in to receive the outgoing call // event. If it does not happen before the timeout specified, cancel the override. @VisibleForTesting public static int DEFAULT_DATA_OVERRIDE_TIMEOUT_MS = 5000; // If there are no subscriptions in a device, then the phone to be used for emergency should // always be the "first" phone. private static final int DEFAULT_EMERGENCY_PHONE_ID = 0; /** * Container for an ongoing request to override the DDS in the context of an ongoing emergency * call to allow for carrier specific operations, such as provide SUPL updates during or after * the emergency call, since some modems do not support these operations on the non DDS. */ private static final class EmergencyOverrideRequest { /* The Phone ID that the DDS should be set to. */ int mPhoneId = INVALID_PHONE_INDEX; /* The time after the emergency call ends that the DDS should be overridden for. */ int mGnssOverrideTimeMs = -1; /* A callback to the requester notifying them if the initial call to the modem to override * the DDS was successful. */ CompletableFuture<Boolean> mOverrideCompleteFuture; /* In the special case that the device goes into emergency callback mode after the emergency * call ends, keep the override until ECM finishes and then start the mGnssOverrideTimeMs * timer to leave DDS override. */ boolean mRequiresEcmFinish = false; /* * Keeps track of whether or not this request has already serviced the outgoing emergency * call. Once finished, do not delay for any other calls. */ boolean mPendingOriginatingCall = true; /** * @return true if there is a pending override complete callback. */ boolean isCallbackAvailable() { return mOverrideCompleteFuture != null; } /** * Send the override complete callback the result of setting the DDS to the new value. */ void sendOverrideCompleteCallbackResultAndClear(boolean result) { if (isCallbackAvailable()) { mOverrideCompleteFuture.complete(result); mOverrideCompleteFuture = null; } } @Override public String toString() { return String.format("EmergencyOverrideRequest: [phoneId= %d, overrideMs= %d," + " hasCallback= %b, ecmFinishStatus= %b]", mPhoneId, mGnssOverrideTimeMs, isCallbackAvailable(), mRequiresEcmFinish); } } protected final List<DcRequest> mPrioritizedDcRequests = new ArrayList<>(); protected final RegistrantList mActivePhoneRegistrants; protected final SubscriptionController mSubscriptionController; protected final Context mContext; private final LocalLog mLocalLog; protected PhoneState[] mPhoneStates; protected int[] mPhoneSubscriptions; @VisibleForTesting protected final CellularNetworkValidator mValidator; private int mPendingSwitchSubId = INVALID_SUBSCRIPTION_ID; private boolean mPendingSwitchNeedValidation; @VisibleForTesting public final CellularNetworkValidator.ValidationCallback mValidationCallback = new CellularNetworkValidator.ValidationCallback() { @Override public void onValidationDone(boolean validated, int subId) { Message.obtain(PhoneSwitcher.this, EVENT_NETWORK_VALIDATION_DONE, subId, validated ? 1 : 0).sendToTarget(); } @Override public void onNetworkAvailable(Network network, int subId) { Message.obtain(PhoneSwitcher.this, EVENT_NETWORK_AVAILABLE, subId, 0, network).sendToTarget(); } }; @UnsupportedAppUsage // How many phones (correspondingly logical modems) are allowed for PS attach. This is used // when we specifically use setDataAllowed to initiate on-demand PS(data) attach for each phone. protected int mMaxDataAttachModemCount; // Local cache of TelephonyManager#getActiveModemCount(). 1 if in single SIM mode, 2 if in dual // SIM mode. protected int mActiveModemCount; protected static PhoneSwitcher sPhoneSwitcher = null; // Which primary (non-opportunistic) subscription is set as data subscription among all primary // subscriptions. This value usually comes from user setting, and it's the subscription used for // Internet data if mOpptDataSubId is not set. protected int mPrimaryDataSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; // mOpptDataSubId must be an active subscription. If it's set, it overrides mPrimaryDataSubId // to be used for Internet data. private int mOpptDataSubId = SubscriptionManager.DEFAULT_SUBSCRIPTION_ID; // The phone ID that has an active voice call. If set, and its mobile data setting is on, // it will become the mPreferredDataPhoneId. protected int mPhoneIdInVoiceCall = SubscriptionManager.INVALID_PHONE_INDEX; @VisibleForTesting // It decides: // 1. In modem layer, which modem is DDS (preferred to have data traffic on) // 2. In TelephonyNetworkFactory, which subscription will apply default network requests, which // are requests without specifying a subId. // Corresponding phoneId after considering mOpptDataSubId, mPrimaryDataSubId and // mPhoneIdInVoiceCall above. protected int mPreferredDataPhoneId = SubscriptionManager.INVALID_PHONE_INDEX; // Subscription ID corresponds to mPreferredDataPhoneId. protected WatchedInt mPreferredDataSubId = new WatchedInt(SubscriptionManager.INVALID_SUBSCRIPTION_ID) { @Override public void set(int newValue) { super.set(newValue); SubscriptionController.invalidateActiveDataSubIdCaches(); } }; // If non-null, An emergency call is about to be started, is ongoing, or has just ended and we // are overriding the DDS. // Internal state, should ONLY be accessed/modified inside of the handler. private EmergencyOverrideRequest mEmergencyOverride; private ISetOpportunisticDataCallback mSetOpptSubCallback; private static final int EVENT_PRIMARY_DATA_SUB_CHANGED = 101; protected static final int EVENT_SUBSCRIPTION_CHANGED = 102; private static final int EVENT_REQUEST_NETWORK = 103; private static final int EVENT_RELEASE_NETWORK = 104; // ECBM has started/ended. If we just ended an emergency call and mEmergencyOverride is not // null, we will wait for EVENT_EMERGENCY_TOGGLE again with ECBM ending to send the message // EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE to remove the override after the mEmergencyOverride // override timer ends. private static final int EVENT_EMERGENCY_TOGGLE = 105; private static final int EVENT_RADIO_CAPABILITY_CHANGED = 106; private static final int EVENT_OPPT_DATA_SUB_CHANGED = 107; private static final int EVENT_RADIO_AVAILABLE = 108; // A call has either started or ended. If an emergency ended and DDS is overridden using // mEmergencyOverride, start the countdown to remove the override using the message // EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE. The only exception to this is if the device moves to // ECBM, which is detected by EVENT_EMERGENCY_TOGGLE. @VisibleForTesting public static final int EVENT_PRECISE_CALL_STATE_CHANGED = 109; private static final int EVENT_NETWORK_VALIDATION_DONE = 110; private static final int EVENT_REMOVE_DEFAULT_NETWORK_CHANGE_CALLBACK = 111; private static final int EVENT_MODEM_COMMAND_DONE = 112; private static final int EVENT_MODEM_COMMAND_RETRY = 113; @VisibleForTesting public static final int EVENT_DATA_ENABLED_CHANGED = 114; // An emergency call is about to be originated and requires the DDS to be overridden. // Uses EVENT_PRECISE_CALL_STATE_CHANGED message to start countdown to finish override defined // in mEmergencyOverride. If EVENT_PRECISE_CALL_STATE_CHANGED does not come in // DEFAULT_DATA_OVERRIDE_TIMEOUT_MS milliseconds, then the override will be removed. private static final int EVENT_OVERRIDE_DDS_FOR_EMERGENCY = 115; // If it exists, remove the current mEmergencyOverride DDS override. private static final int EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE = 116; // If it exists, remove the current mEmergencyOverride DDS override. @VisibleForTesting public static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 117; private static final int EVENT_NETWORK_AVAILABLE = 118; // Depending on version of IRadioConfig, we need to send either RIL_REQUEST_ALLOW_DATA if it's // 1.0, or RIL_REQUEST_SET_PREFERRED_DATA if it's 1.1 or later. So internally mHalCommandToUse // will be either HAL_COMMAND_ALLOW_DATA or HAL_COMMAND_ALLOW_DATA or HAL_COMMAND_UNKNOWN. protected static final int HAL_COMMAND_UNKNOWN = 0; protected static final int HAL_COMMAND_ALLOW_DATA = 1; protected static final int HAL_COMMAND_PREFERRED_DATA = 2; protected int mHalCommandToUse = HAL_COMMAND_UNKNOWN; protected RadioConfig mRadioConfig; private final static int MAX_LOCAL_LOG_LINES = 30; // Default timeout value of network validation in millisecond. private final static int DEFAULT_VALIDATION_EXPIRATION_TIME = 2000; private Boolean mHasRegisteredDefaultNetworkChangeCallback = false; private ConnectivityManager mConnectivityManager; private class DefaultNetworkCallback extends ConnectivityManager.NetworkCallback { public int mExpectedSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; public int mSwitchReason = TelephonyEvent.DataSwitch.Reason.DATA_SWITCH_REASON_UNKNOWN; @Override public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) { if (networkCapabilities.hasTransport(TRANSPORT_CELLULAR) && SubscriptionManager.isValidSubscriptionId(mExpectedSubId) && mExpectedSubId == getSubIdFromNetworkSpecifier( networkCapabilities.getNetworkSpecifier())) { logDataSwitchEvent( mExpectedSubId, TelephonyEvent.EventState.EVENT_STATE_END, mSwitchReason); removeDefaultNetworkChangeCallback(); } } } private final DefaultNetworkCallback mDefaultNetworkCallback = new DefaultNetworkCallback(); /** * Method to get singleton instance. */ public static PhoneSwitcher getInstance() { return sPhoneSwitcher; } /** * Method to create singleton instance. */ public static PhoneSwitcher make(int maxDataAttachModemCount, Context context, Looper looper) { if (sPhoneSwitcher == null) { sPhoneSwitcher = new PhoneSwitcher(maxDataAttachModemCount, context, looper); SubscriptionController.invalidateActiveDataSubIdCaches(); } return sPhoneSwitcher; } private boolean isPhoneInVoiceCallChanged() { int oldPhoneIdInVoiceCall = mPhoneIdInVoiceCall; // If there's no active call, the value will become INVALID_PHONE_INDEX // and internet data will be switched back to system selected or user selected // subscription. mPhoneIdInVoiceCall = SubscriptionManager.INVALID_PHONE_INDEX; for (Phone phone : PhoneFactory.getPhones()) { if (isPhoneInVoiceCall(phone) || isPhoneInVoiceCall(phone.getImsPhone())) { mPhoneIdInVoiceCall = phone.getPhoneId(); break; } } if (mPhoneIdInVoiceCall != oldPhoneIdInVoiceCall) { log("isPhoneInVoiceCallChanged from phoneId " + oldPhoneIdInVoiceCall + " to phoneId " + mPhoneIdInVoiceCall); return true; } else { return false; } } @VisibleForTesting public PhoneSwitcher(int maxActivePhones, Context context, Looper looper) { super(looper); mContext = context; mActiveModemCount = getTm().getActiveModemCount(); mPhoneSubscriptions = new int[mActiveModemCount]; mPhoneStates = new PhoneState[mActiveModemCount]; mMaxDataAttachModemCount = maxActivePhones; mLocalLog = new LocalLog(MAX_LOCAL_LOG_LINES); mSubscriptionController = SubscriptionController.getInstance(); mRadioConfig = RadioConfig.getInstance(mContext); mValidator = CellularNetworkValidator.getInstance(); mActivePhoneRegistrants = new RegistrantList(); for (int i = 0; i < mActiveModemCount; i++) { mPhoneStates[i] = new PhoneState(); if (PhoneFactory.getPhone(i) != null) { PhoneFactory.getPhone(i).registerForEmergencyCallToggle( this, EVENT_EMERGENCY_TOGGLE, null); // TODO (b/135566422): combine register for both GsmCdmaPhone and ImsPhone. PhoneFactory.getPhone(i).registerForPreciseCallStateChanged( this, EVENT_PRECISE_CALL_STATE_CHANGED, null); if (PhoneFactory.getPhone(i).getImsPhone() != null) { PhoneFactory.getPhone(i).getImsPhone().registerForPreciseCallStateChanged( this, EVENT_PRECISE_CALL_STATE_CHANGED, null); } PhoneFactory.getPhone(i).getDataEnabledSettings().registerForDataEnabledChanged( this, EVENT_DATA_ENABLED_CHANGED, null); } } if (mActiveModemCount > 0) { PhoneFactory.getPhone(0).mCi.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null); } TelephonyRegistryManager telephonyRegistryManager = (TelephonyRegistryManager) context.getSystemService(Context.TELEPHONY_REGISTRY_SERVICE); telephonyRegistryManager.addOnSubscriptionsChangedListener( mSubscriptionsChangedListener, mSubscriptionsChangedListener.getHandlerExecutor()); mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); mContext.registerReceiver(mDefaultDataChangedReceiver, new IntentFilter(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED)); PhoneConfigurationManager.registerForMultiSimConfigChange( this, EVENT_MULTI_SIM_CONFIG_CHANGED, null); NetworkCapabilities netCap = new NetworkCapabilities(); netCap.addTransportType(TRANSPORT_CELLULAR); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_SUPL); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_DUN); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_FOTA); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_IMS); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_CBS); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_IA); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_RCS); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_XCAP); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_EIMS); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_MCX); netCap.setNetworkSpecifier(new MatchAllNetworkSpecifier()); NetworkFactory networkFactory = new PhoneSwitcherNetworkRequestListener(looper, context, netCap, this); // we want to see all requests networkFactory.setScoreFilter(101); networkFactory.register(); log("PhoneSwitcher started"); } private final BroadcastReceiver mDefaultDataChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Message msg = PhoneSwitcher.this.obtainMessage(EVENT_PRIMARY_DATA_SUB_CHANGED); msg.sendToTarget(); } }; private final SubscriptionManager.OnSubscriptionsChangedListener mSubscriptionsChangedListener = new SubscriptionManager.OnSubscriptionsChangedListener() { @Override public void onSubscriptionsChanged() { Message msg = PhoneSwitcher.this.obtainMessage(EVENT_SUBSCRIPTION_CHANGED); msg.sendToTarget(); } }; @Override public void handleMessage(Message msg) { switch (msg.what) { case EVENT_SUBSCRIPTION_CHANGED: { onEvaluate(REQUESTS_UNCHANGED, "subChanged"); break; } case EVENT_PRIMARY_DATA_SUB_CHANGED: { if (onEvaluate(REQUESTS_UNCHANGED, "primary data subId changed")) { logDataSwitchEvent(mPreferredDataSubId.get(), TelephonyEvent.EventState.EVENT_STATE_START, DataSwitch.Reason.DATA_SWITCH_REASON_MANUAL); registerDefaultNetworkChangeCallback(mPreferredDataSubId.get(), DataSwitch.Reason.DATA_SWITCH_REASON_MANUAL); } break; } case EVENT_REQUEST_NETWORK: { onRequestNetwork((NetworkRequest)msg.obj); break; } case EVENT_RELEASE_NETWORK: { onReleaseNetwork((NetworkRequest)msg.obj); break; } case EVENT_EMERGENCY_TOGGLE: { boolean isInEcm = isInEmergencyCallbackMode(); if (mEmergencyOverride != null) { log("Emergency override - ecbm status = " + isInEcm); if (isInEcm) { // The device has gone into ECBM. Wait until it's out. removeMessages(EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE); mEmergencyOverride.mRequiresEcmFinish = true; } else if (mEmergencyOverride.mRequiresEcmFinish) { // we have exited ECM! Start the timer to exit DDS override. Message msg2 = obtainMessage(EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE); sendMessageDelayed(msg2, mEmergencyOverride.mGnssOverrideTimeMs); } } onEvaluate(REQUESTS_CHANGED, "emergencyToggle"); break; } case EVENT_RADIO_CAPABILITY_CHANGED: { final int phoneId = msg.arg1; sendRilCommands(phoneId); break; } case EVENT_OPPT_DATA_SUB_CHANGED: { int subId = msg.arg1; boolean needValidation = (msg.arg2 == 1); ISetOpportunisticDataCallback callback = (ISetOpportunisticDataCallback) msg.obj; setOpportunisticDataSubscription(subId, needValidation, callback); break; } case EVENT_RADIO_AVAILABLE: { updateHalCommandToUse(); onEvaluate(REQUESTS_UNCHANGED, "EVENT_RADIO_AVAILABLE"); break; } case EVENT_PRECISE_CALL_STATE_CHANGED: { // If the phoneId in voice call didn't change, do nothing. if (!isPhoneInVoiceCallChanged()) break; // Only handle this event if we are currently waiting for the emergency call // associated with the override request to start or end. if (mEmergencyOverride != null && mEmergencyOverride.mPendingOriginatingCall) { removeMessages(EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE); if (mPhoneIdInVoiceCall == SubscriptionManager.INVALID_PHONE_INDEX) { // not in a call anymore. Message msg2 = obtainMessage(EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE); sendMessageDelayed(msg2, mEmergencyOverride.mGnssOverrideTimeMs + ECBM_DEFAULT_DATA_SWITCH_BASE_TIME_MS); // Do not extend the emergency override by waiting for other calls to end. // If it needs to be extended, a new request will come in and replace the // current override. mEmergencyOverride.mPendingOriginatingCall = false; } } } // fall through case EVENT_DATA_ENABLED_CHANGED: if (onEvaluate(REQUESTS_UNCHANGED, "EVENT_PRECISE_CALL_STATE_CHANGED")) { logDataSwitchEvent(mPreferredDataSubId.get(), TelephonyEvent.EventState.EVENT_STATE_START, DataSwitch.Reason.DATA_SWITCH_REASON_IN_CALL); registerDefaultNetworkChangeCallback(mPreferredDataSubId.get(), DataSwitch.Reason.DATA_SWITCH_REASON_IN_CALL); } break; case EVENT_NETWORK_VALIDATION_DONE: { int subId = msg.arg1; boolean passed = (msg.arg2 == 1); onValidationDone(subId, passed); break; } case EVENT_NETWORK_AVAILABLE: { int subId = msg.arg1; Network network = (Network) msg.obj; onNetworkAvailable(subId, network); break; } case EVENT_REMOVE_DEFAULT_NETWORK_CHANGE_CALLBACK: { removeDefaultNetworkChangeCallback(); break; } case EVENT_MODEM_COMMAND_DONE: { AsyncResult ar = (AsyncResult) msg.obj; boolean commandSuccess = ar != null && ar.exception == null; if (mEmergencyOverride != null) { log("Emergency override result sent = " + commandSuccess); mEmergencyOverride.sendOverrideCompleteCallbackResultAndClear(commandSuccess); // Do not retry , as we do not allow changes in onEvaluate during an emergency // call. When the call ends, we will start the countdown to remove the override. } else if (!commandSuccess) { int phoneId = (int) ar.userObj; log("Modem command failed. with exception " + ar.exception); sendMessageDelayed(Message.obtain(this, EVENT_MODEM_COMMAND_RETRY, phoneId), MODEM_COMMAND_RETRY_PERIOD_MS); } break; } case EVENT_MODEM_COMMAND_RETRY: { int phoneId = (int) msg.obj; log("Resend modem command on phone " + phoneId); sendRilCommands(phoneId); break; } case EVENT_OVERRIDE_DDS_FOR_EMERGENCY: { EmergencyOverrideRequest req = (EmergencyOverrideRequest) msg.obj; if (mEmergencyOverride != null) { // If an override request comes in for a different phone ID than what is already // being overridden, ignore. We should not try to switch DDS while already // waiting for SUPL. if (mEmergencyOverride.mPhoneId != req.mPhoneId) { log("emergency override requested for phone id " + req.mPhoneId + " when " + "there is already an override in place for phone id " + mEmergencyOverride.mPhoneId + ". Ignoring."); if (req.isCallbackAvailable()) { // Send failed result req.mOverrideCompleteFuture.complete(false); } break; } else { if (mEmergencyOverride.isCallbackAvailable()) { // Unblock any waiting overrides if a new request comes in before the // previous one is processed. mEmergencyOverride.mOverrideCompleteFuture.complete(false); } } mEmergencyOverride = req; } else { mEmergencyOverride = req; } log("new emergency override - " + mEmergencyOverride); // a new request has been created, remove any previous override complete scheduled. removeMessages(EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE); Message msg2 = obtainMessage(EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE); // Make sure that if we never get an incall indication that we remove the override. sendMessageDelayed(msg2, DEFAULT_DATA_OVERRIDE_TIMEOUT_MS); // Wait for call to end and EVENT_PRECISE_CALL_STATE_CHANGED to be called, then // start timer to remove DDS emergency override. if (!onEvaluate(REQUESTS_UNCHANGED, "emer_override_dds")) { // Nothing changed as a result of override, so no modem command was sent. Treat // as success. mEmergencyOverride.sendOverrideCompleteCallbackResultAndClear(true); // Do not clear mEmergencyOverride here, as we still want to keep the override // active for the time specified in case the user tries to switch default data. } break; } case EVENT_REMOVE_DDS_EMERGENCY_OVERRIDE: { log("Emergency override removed - " + mEmergencyOverride); mEmergencyOverride = null; onEvaluate(REQUESTS_UNCHANGED, "emer_rm_override_dds"); break; } case EVENT_MULTI_SIM_CONFIG_CHANGED: { int activeModemCount = (int) ((AsyncResult) msg.obj).result; onMultiSimConfigChanged(activeModemCount); break; } } } private synchronized void onMultiSimConfigChanged(int activeModemCount) { // No change. if (mActiveModemCount == activeModemCount) return; int oldActiveModemCount = mActiveModemCount; mActiveModemCount = activeModemCount; mPhoneSubscriptions = copyOf(mPhoneSubscriptions, mActiveModemCount); mPhoneStates = copyOf(mPhoneStates, mActiveModemCount); // Single SIM -> dual SIM switch. for (int phoneId = oldActiveModemCount; phoneId < mActiveModemCount; phoneId++) { mPhoneStates[phoneId] = new PhoneState(); Phone phone = PhoneFactory.getPhone(phoneId); if (phone == null) continue; phone.registerForEmergencyCallToggle(this, EVENT_EMERGENCY_TOGGLE, null); // TODO (b/135566422): combine register for both GsmCdmaPhone and ImsPhone. phone.registerForPreciseCallStateChanged(this, EVENT_PRECISE_CALL_STATE_CHANGED, null); if (phone.getImsPhone() != null) { phone.getImsPhone().registerForPreciseCallStateChanged( this, EVENT_PRECISE_CALL_STATE_CHANGED, null); } phone.getDataEnabledSettings().registerForDataEnabledChanged( this, EVENT_DATA_ENABLED_CHANGED, null); } } private boolean isInEmergencyCallbackMode() { for (Phone p : PhoneFactory.getPhones()) { if (p == null) continue; if (p.isInEcm()) return true; Phone imsPhone = p.getImsPhone(); if (imsPhone != null && imsPhone.isInEcm()) { return true; } } return false; } private static class PhoneSwitcherNetworkRequestListener extends NetworkFactory { private final PhoneSwitcher mPhoneSwitcher; public PhoneSwitcherNetworkRequestListener (Looper l, Context c, NetworkCapabilities nc, PhoneSwitcher ps) { super(l, c, "PhoneSwitcherNetworkRequstListener", nc); mPhoneSwitcher = ps; } @Override protected void needNetworkFor(NetworkRequest networkRequest, int score) { if (VDBG) log("needNetworkFor " + networkRequest + ", " + score); Message msg = mPhoneSwitcher.obtainMessage(EVENT_REQUEST_NETWORK); msg.obj = networkRequest; msg.sendToTarget(); } @Override protected void releaseNetworkFor(NetworkRequest networkRequest) { if (VDBG) log("releaseNetworkFor " + networkRequest); Message msg = mPhoneSwitcher.obtainMessage(EVENT_RELEASE_NETWORK); msg.obj = networkRequest; msg.sendToTarget(); } } private void onRequestNetwork(NetworkRequest networkRequest) { final DcRequest dcRequest = DcRequest.create(networkRequest, createApnRepository(networkRequest)); if (dcRequest != null) { if (!mPrioritizedDcRequests.contains(dcRequest)) { collectRequestNetworkMetrics(networkRequest); mPrioritizedDcRequests.add(dcRequest); Collections.sort(mPrioritizedDcRequests); onEvaluate(REQUESTS_CHANGED, "netRequest"); log("Added DcRequest, size: " + mPrioritizedDcRequests.size()); } } } private void onReleaseNetwork(NetworkRequest networkRequest) { final DcRequest dcRequest = DcRequest.create(networkRequest, createApnRepository(networkRequest)); if (dcRequest != null) { if (mPrioritizedDcRequests.remove(dcRequest)) { onEvaluate(REQUESTS_CHANGED, "netReleased"); collectReleaseNetworkMetrics(networkRequest); log("Removed DcRequest, size: " + mPrioritizedDcRequests.size()); } } } private ApnConfigTypeRepository createApnRepository(NetworkRequest networkRequest) { int phoneIdForRequest = phoneIdForRequest(networkRequest); int subId = mSubscriptionController.getSubIdUsingPhoneId(phoneIdForRequest); CarrierConfigManager configManager = (CarrierConfigManager) mContext .getSystemService(Context.CARRIER_CONFIG_SERVICE); PersistableBundle carrierConfig; if (configManager != null) { carrierConfig = configManager.getConfigForSubId(subId); } else { carrierConfig = null; } return new ApnConfigTypeRepository(carrierConfig); } private void removeDefaultNetworkChangeCallback() { removeMessages(EVENT_REMOVE_DEFAULT_NETWORK_CHANGE_CALLBACK); mDefaultNetworkCallback.mExpectedSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID; mDefaultNetworkCallback.mSwitchReason = TelephonyEvent.DataSwitch.Reason.DATA_SWITCH_REASON_UNKNOWN; mConnectivityManager.unregisterNetworkCallback(mDefaultNetworkCallback); } private void registerDefaultNetworkChangeCallback(int expectedSubId, int reason) { mDefaultNetworkCallback.mExpectedSubId = expectedSubId; mDefaultNetworkCallback.mSwitchReason = reason; mConnectivityManager.registerDefaultNetworkCallback(mDefaultNetworkCallback, this); sendMessageDelayed( obtainMessage(EVENT_REMOVE_DEFAULT_NETWORK_CHANGE_CALLBACK), DEFAULT_NETWORK_CHANGE_TIMEOUT_MS); } private void collectRequestNetworkMetrics(NetworkRequest networkRequest) { // Request network for MMS will temporary disable the network on default data subscription, // this only happen on multi-sim device. if (mActiveModemCount > 1 && networkRequest.hasCapability( NetworkCapabilities.NET_CAPABILITY_MMS)) { OnDemandDataSwitch onDemandDataSwitch = new OnDemandDataSwitch(); onDemandDataSwitch.apn = TelephonyEvent.ApnType.APN_TYPE_MMS; onDemandDataSwitch.state = TelephonyEvent.EventState.EVENT_STATE_START; TelephonyMetrics.getInstance().writeOnDemandDataSwitch(onDemandDataSwitch); } } private void collectReleaseNetworkMetrics(NetworkRequest networkRequest) { // Release network for MMS will recover the network on default data subscription, this only // happen on multi-sim device. if (mActiveModemCount > 1 && networkRequest.hasCapability( NetworkCapabilities.NET_CAPABILITY_MMS)) { OnDemandDataSwitch onDemandDataSwitch = new OnDemandDataSwitch(); onDemandDataSwitch.apn = TelephonyEvent.ApnType.APN_TYPE_MMS; onDemandDataSwitch.state = TelephonyEvent.EventState.EVENT_STATE_END; TelephonyMetrics.getInstance().writeOnDemandDataSwitch(onDemandDataSwitch); } } private TelephonyManager getTm() { return (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); } protected static final boolean REQUESTS_CHANGED = true; protected static final boolean REQUESTS_UNCHANGED = false; /** * Re-evaluate things. Do nothing if nothing's changed. * * Otherwise, go through the requests in priority order adding their phone until we've added up * to the max allowed. Then go through shutting down phones that aren't in the active phone * list. Finally, activate all phones in the active phone list. * * @return {@code True} if the default data subscription need to be changed. */ protected boolean onEvaluate(boolean requestsChanged, String reason) { StringBuilder sb = new StringBuilder(reason); // If we use HAL_COMMAND_PREFERRED_DATA, boolean diffDetected = mHalCommandToUse != HAL_COMMAND_PREFERRED_DATA && requestsChanged; // Check if user setting of default non-opportunistic data sub is changed. final int primaryDataSubId = mSubscriptionController.getDefaultDataSubId(); if (primaryDataSubId != mPrimaryDataSubId) { sb.append(" mPrimaryDataSubId ").append(mPrimaryDataSubId).append("->") .append(primaryDataSubId); mPrimaryDataSubId = primaryDataSubId; } // Check to see if there is any active subscription on any phone boolean hasAnyActiveSubscription = false; // Check if phoneId to subId mapping is changed. for (int i = 0; i < mActiveModemCount; i++) { int sub = mSubscriptionController.getSubIdUsingPhoneId(i); if (SubscriptionManager.isValidSubscriptionId(sub)) hasAnyActiveSubscription = true; if (sub != mPhoneSubscriptions[i]) { sb.append(" phone[").append(i).append("] ").append(mPhoneSubscriptions[i]); sb.append("->").append(sub); mPhoneSubscriptions[i] = sub; diffDetected = true; } } if (!hasAnyActiveSubscription) { transitionToEmergencyPhone(); } else { if (VDBG) log("Found an active subscription"); } // Check if phoneId for preferred data is changed. int oldPreferredDataPhoneId = mPreferredDataPhoneId; // When there are no subscriptions, the preferred data phone ID is invalid, but we want // to keep a valid phoneId for Emergency, so skip logic that updates for preferred data // phone ID. Ideally there should be a single set of checks that evaluate the correct // phoneId on a service-by-service basis (EIMS being one), but for now... just bypass // this logic in the no-SIM case. if (hasAnyActiveSubscription) updatePreferredDataPhoneId(); if (oldPreferredDataPhoneId != mPreferredDataPhoneId) { sb.append(" preferred phoneId ").append(oldPreferredDataPhoneId) .append("->").append(mPreferredDataPhoneId); diffDetected = true; } if (diffDetected) { log("evaluating due to " + sb.toString()); if (mHalCommandToUse == HAL_COMMAND_PREFERRED_DATA) { // With HAL_COMMAND_PREFERRED_DATA, all phones are assumed to allow PS attach. // So marking all phone as active, and the phone with mPreferredDataPhoneId // will send radioConfig command. for (int phoneId = 0; phoneId < mActiveModemCount; phoneId++) { mPhoneStates[phoneId].active = true; } sendRilCommands(mPreferredDataPhoneId); } else { List<Integer> newActivePhones = new ArrayList<Integer>(); /** * If all phones can have PS attached, activate all. * Otherwise, choose to activate phones according to requests. And * if list is not full, add mPreferredDataPhoneId. */ if (mMaxDataAttachModemCount == mActiveModemCount) { for (int i = 0; i < mMaxDataAttachModemCount; i++) { newActivePhones.add(i); } } else { // First try to activate phone in voice call. if (mPhoneIdInVoiceCall != SubscriptionManager.INVALID_PHONE_INDEX) { newActivePhones.add(mPhoneIdInVoiceCall); } if (newActivePhones.size() < mMaxDataAttachModemCount) { for (DcRequest dcRequest : mPrioritizedDcRequests) { int phoneIdForRequest = phoneIdForRequest(dcRequest.networkRequest); if (phoneIdForRequest == INVALID_PHONE_INDEX) continue; if (newActivePhones.contains(phoneIdForRequest)) continue; newActivePhones.add(phoneIdForRequest); if (newActivePhones.size() >= mMaxDataAttachModemCount) break; } } if (newActivePhones.size() < mMaxDataAttachModemCount && newActivePhones.contains(mPreferredDataPhoneId) && SubscriptionManager.isUsableSubIdValue(mPreferredDataPhoneId)) { newActivePhones.add(mPreferredDataPhoneId); } } if (VDBG) { log("mPrimaryDataSubId = " + mPrimaryDataSubId); log("mOpptDataSubId = " + mOpptDataSubId); for (int i = 0; i < mActiveModemCount; i++) { log(" phone[" + i + "] using sub[" + mPhoneSubscriptions[i] + "]"); } log(" newActivePhones:"); for (Integer i : newActivePhones) log(" " + i); } for (int phoneId = 0; phoneId < mActiveModemCount; phoneId++) { if (!newActivePhones.contains(phoneId)) { deactivate(phoneId); } } // only activate phones up to the limit for (int phoneId : newActivePhones) { activate(phoneId); } } notifyPreferredDataSubIdChanged(); // Notify all registrants. mActivePhoneRegistrants.notifyRegistrants(); } return diffDetected; } protected static class PhoneState { public volatile boolean active = false; public long lastRequested = 0; } @UnsupportedAppUsage protected void activate(int phoneId) { switchPhone(phoneId, true); } @UnsupportedAppUsage protected void deactivate(int phoneId) { switchPhone(phoneId, false); } private void switchPhone(int phoneId, boolean active) { PhoneState state = mPhoneStates[phoneId]; if (state.active == active) return; state.active = active; log((active ? "activate " : "deactivate ") + phoneId); state.lastRequested = System.currentTimeMillis(); sendRilCommands(phoneId); } /** * Used when the modem may have been rebooted and we * want to resend setDataAllowed or setPreferredDataSubscriptionId */ public void onRadioCapChanged(int phoneId) { if (!SubscriptionManager.isValidPhoneId(phoneId)) return; Message msg = obtainMessage(EVENT_RADIO_CAPABILITY_CHANGED); msg.arg1 = phoneId; msg.sendToTarget(); } /** * Switch the Default data for the context of an outgoing emergency call. * * In some cases, we need to try to switch the Default Data subscription before placing the * emergency call on DSDS devices. This includes the following situation: * - The modem does not support processing GNSS SUPL requests on the non-default data * subscription. For some carriers that do not provide a control plane fallback mechanism, the * SUPL request will be dropped and we will not be able to get the user's location for the * emergency call. In this case, we need to swap default data temporarily. * @param phoneId The phone to use to evaluate whether or not the default data should be moved * to this subscription. * @param overrideTimeSec The amount of time to override the default data setting for after the * emergency call ends. * @param dataSwitchResult A {@link CompletableFuture} to be called with a {@link Boolean} * result when the default data switch has either completed (true) or * failed (false). */ public void overrideDefaultDataForEmergency(int phoneId, int overrideTimeSec, CompletableFuture<Boolean> dataSwitchResult) { if (!SubscriptionManager.isValidPhoneId(phoneId)) return; Message msg = obtainMessage(EVENT_OVERRIDE_DDS_FOR_EMERGENCY); EmergencyOverrideRequest request = new EmergencyOverrideRequest(); request.mPhoneId = phoneId; request.mGnssOverrideTimeMs = overrideTimeSec * 1000; request.mOverrideCompleteFuture = dataSwitchResult; msg.obj = request; msg.sendToTarget(); } protected void sendRilCommands(int phoneId) { if (!SubscriptionManager.isValidPhoneId(phoneId)) return; Message message = Message.obtain(this, EVENT_MODEM_COMMAND_DONE, phoneId); if (mHalCommandToUse == HAL_COMMAND_ALLOW_DATA || mHalCommandToUse == HAL_COMMAND_UNKNOWN) { // Skip ALLOW_DATA for single SIM device if (mActiveModemCount > 1) { PhoneFactory.getPhone(phoneId).mCi.setDataAllowed(isPhoneActive(phoneId), message); } } else if (phoneId == mPreferredDataPhoneId) { // Only setPreferredDataModem if the phoneId equals to current mPreferredDataPhoneId. mRadioConfig.setPreferredDataModem(mPreferredDataPhoneId, message); } } private void onPhoneCapabilityChangedInternal(PhoneCapability capability) { int newMaxDataAttachModemCount = TelephonyManager.getDefault() .getNumberOfModemsWithSimultaneousDataConnections(); if (mMaxDataAttachModemCount != newMaxDataAttachModemCount) { mMaxDataAttachModemCount = newMaxDataAttachModemCount; log("Max active phones changed to " + mMaxDataAttachModemCount); onEvaluate(REQUESTS_UNCHANGED, "phoneCfgChanged"); } } private int phoneIdForRequest(NetworkRequest netRequest) { int subId = getSubIdFromNetworkSpecifier(netRequest.getNetworkSpecifier()); if (subId == DEFAULT_SUBSCRIPTION_ID) return mPreferredDataPhoneId; if (subId == INVALID_SUBSCRIPTION_ID) return INVALID_PHONE_INDEX; int preferredDataSubId = (mPreferredDataPhoneId >= 0 && mPreferredDataPhoneId < mActiveModemCount) ? mPhoneSubscriptions[mPreferredDataPhoneId] : INVALID_SUBSCRIPTION_ID; // Currently we assume multi-SIM devices will only support one Internet PDN connection. So // if Internet PDN is established on the non-preferred phone, it will interrupt // Internet connection on the preferred phone. So we only accept Internet request with // preferred data subscription or no specified subscription. // One exception is, if it's restricted request (doesn't have NET_CAPABILITY_NOT_RESTRICTED) // it will be accepted, which is used temporary data usage from system. if (netRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && netRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) && subId != preferredDataSubId && subId != mValidator.getSubIdInValidation()) { // Returning INVALID_PHONE_INDEX will result in netRequest not being handled. return INVALID_PHONE_INDEX; } // Try to find matching phone ID. If it doesn't exist, we'll end up returning INVALID. int phoneId = INVALID_PHONE_INDEX; for (int i = 0; i < mActiveModemCount; i++) { if (mPhoneSubscriptions[i] == subId) { phoneId = i; break; } } return phoneId; } protected int getSubIdFromNetworkSpecifier(NetworkSpecifier specifier) { if (specifier == null) { return DEFAULT_SUBSCRIPTION_ID; } if (specifier instanceof TelephonyNetworkSpecifier) { return ((TelephonyNetworkSpecifier) specifier).getSubscriptionId(); } return INVALID_SUBSCRIPTION_ID; } private int getSubIdForDefaultNetworkRequests() { if (mSubscriptionController.isActiveSubId(mOpptDataSubId)) { return mOpptDataSubId; } else { return mPrimaryDataSubId; } } // This updates mPreferredDataPhoneId which decides which phone should handle default network // requests. protected void updatePreferredDataPhoneId() { Phone voicePhone = findPhoneById(mPhoneIdInVoiceCall); if (mEmergencyOverride != null && findPhoneById(mEmergencyOverride.mPhoneId) != null) { // Override DDS for emergency even if user data is not enabled, since it is an // emergency. // TODO: Provide a notification to the user that metered data is currently being // used during this period. log("updatePreferredDataPhoneId: preferred data overridden for emergency." + " phoneId = " + mEmergencyOverride.mPhoneId); mPreferredDataPhoneId = mEmergencyOverride.mPhoneId; } else if (voicePhone != null && voicePhone.getDataEnabledSettings().isDataEnabled( ApnSetting.TYPE_DEFAULT)) { // If a phone is in call and user enabled its mobile data, we // should switch internet connection to it. Because the other modem // will lose data connection anyway. // TODO: validate network first. mPreferredDataPhoneId = mPhoneIdInVoiceCall; } else { int subId = getSubIdForDefaultNetworkRequests(); int phoneId = SubscriptionManager.INVALID_PHONE_INDEX; if (SubscriptionManager.isUsableSubIdValue(subId)) { for (int i = 0; i < mActiveModemCount; i++) { if (mPhoneSubscriptions[i] == subId) { phoneId = i; break; } } } mPreferredDataPhoneId = phoneId; } mPreferredDataSubId.set( mSubscriptionController.getSubIdUsingPhoneId(mPreferredDataPhoneId)); } protected void transitionToEmergencyPhone() { if (mActiveModemCount <= 0) { log("No phones: unable to reset preferred phone for emergency"); return; } if (mPreferredDataPhoneId != DEFAULT_EMERGENCY_PHONE_ID) { log("No active subscriptions: resetting preferred phone to 0 for emergency"); mPreferredDataPhoneId = DEFAULT_EMERGENCY_PHONE_ID; } if (mPreferredDataSubId.get() != INVALID_SUBSCRIPTION_ID) { mPreferredDataSubId.set(INVALID_SUBSCRIPTION_ID); notifyPreferredDataSubIdChanged(); } } private Phone findPhoneById(final int phoneId) { if (!SubscriptionManager.isValidPhoneId(phoneId)) { return null; } return PhoneFactory.getPhone(phoneId); } public synchronized boolean shouldApplyNetworkRequest( NetworkRequest networkRequest, int phoneId) { if (!SubscriptionManager.isValidPhoneId(phoneId)) return false; // In any case, if phone state is inactive, don't apply the network request. if (!isPhoneActive(phoneId) || ( mSubscriptionController.getSubIdUsingPhoneId(phoneId) == INVALID_SUBSCRIPTION_ID && !isEmergencyNetworkRequest(networkRequest))) { return false; } int phoneIdToHandle = phoneIdForRequest(networkRequest); return phoneId == phoneIdToHandle; } boolean isEmergencyNetworkRequest(NetworkRequest networkRequest) { return networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_EIMS); } @VisibleForTesting protected boolean isPhoneActive(int phoneId) { if (phoneId >= mActiveModemCount) return false; return mPhoneStates[phoneId].active; } /** * If preferred phone changes, or phone activation status changes, registrants * will be notified. */ public void registerForActivePhoneSwitch(Handler h, int what, Object o) { Registrant r = new Registrant(h, what, o); mActivePhoneRegistrants.add(r); r.notifyRegistrant(); } public void unregisterForActivePhoneSwitch(Handler h) { mActivePhoneRegistrants.remove(h); } /** * Set opportunistic data subscription. It's an indication to switch Internet data to this * subscription. It has to be an active subscription, and PhoneSwitcher will try to validate * it first if needed. If subId is DEFAULT_SUBSCRIPTION_ID, it means we are un-setting * opportunistic data sub and switch data back to primary sub. * * @param subId the opportunistic data subscription to switch to. pass DEFAULT_SUBSCRIPTION_ID * if un-setting it. * @param needValidation whether Telephony will wait until the network is validated by * connectivity service before switching data to it. More details see * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED}. * @param callback Callback will be triggered once it succeeds or failed. * Pass null if don't care about the result. */ private void setOpportunisticDataSubscription(int subId, boolean needValidation, ISetOpportunisticDataCallback callback) { if (!mSubscriptionController.isActiveSubId(subId) && subId != SubscriptionManager.DEFAULT_SUBSCRIPTION_ID) { log("Can't switch data to inactive subId " + subId); sendSetOpptCallbackHelper(callback, SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION); return; } // Remove EVENT_NETWORK_VALIDATION_DONE. Don't handle validation result of previously subId // if queued. removeMessages(EVENT_NETWORK_VALIDATION_DONE); removeMessages(EVENT_NETWORK_AVAILABLE); int subIdToValidate = (subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID) ? mPrimaryDataSubId : subId; mPendingSwitchSubId = INVALID_SUBSCRIPTION_ID; if (mValidator.isValidating()) { mValidator.stopValidation(); sendSetOpptCallbackHelper(mSetOpptSubCallback, SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED); mSetOpptSubCallback = null; } if (subId == mOpptDataSubId) { sendSetOpptCallbackHelper(callback, SET_OPPORTUNISTIC_SUB_SUCCESS); return; } logDataSwitchEvent(subId == DEFAULT_SUBSCRIPTION_ID ? mPrimaryDataSubId : subId, TelephonyEvent.EventState.EVENT_STATE_START, DataSwitch.Reason.DATA_SWITCH_REASON_CBRS); registerDefaultNetworkChangeCallback( subId == DEFAULT_SUBSCRIPTION_ID ? mPrimaryDataSubId : subId, DataSwitch.Reason.DATA_SWITCH_REASON_CBRS); // If validation feature is not supported, set it directly. Otherwise, // start validation on the subscription first. if (!mValidator.isValidationFeatureSupported()) { setOpportunisticSubscriptionInternal(subId); sendSetOpptCallbackHelper(callback, SET_OPPORTUNISTIC_SUB_SUCCESS); return; } // Even if needValidation is false, we still send request to validator. The reason is we // want to delay data switch until network is available on the target sub, to have a // smoothest transition possible. // In this case, even if data connection eventually failed in 2 seconds, we still // confirm the switch, to maximally respect the request. mPendingSwitchSubId = subIdToValidate; mPendingSwitchNeedValidation = needValidation; mSetOpptSubCallback = callback; long validationTimeout = getValidationTimeout(subIdToValidate, needValidation); mValidator.validate(subIdToValidate, validationTimeout, false, mValidationCallback); } private long getValidationTimeout(int subId, boolean needValidation) { if (!needValidation) return DEFAULT_VALIDATION_EXPIRATION_TIME; long validationTimeout = DEFAULT_VALIDATION_EXPIRATION_TIME; CarrierConfigManager configManager = (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE); if (configManager != null) { PersistableBundle b = configManager.getConfigForSubId(subId); if (b != null) { validationTimeout = b.getLong(KEY_DATA_SWITCH_VALIDATION_TIMEOUT_LONG); } } return validationTimeout; } private void sendSetOpptCallbackHelper(ISetOpportunisticDataCallback callback, int result) { if (callback == null) return; try { callback.onComplete(result); } catch (RemoteException exception) { log("RemoteException " + exception); } } /** * Set opportunistic data subscription. */ private void setOpportunisticSubscriptionInternal(int subId) { if (mOpptDataSubId != subId) { mOpptDataSubId = subId; onEvaluate(REQUESTS_UNCHANGED, "oppt data subId changed"); } } private void confirmSwitch(int subId, boolean confirm) { log("confirmSwitch: subId " + subId + (confirm ? " confirmed." : " cancelled.")); int resultForCallBack; if (!mSubscriptionController.isActiveSubId(subId)) { log("confirmSwitch: subId " + subId + " is no longer active"); resultForCallBack = SET_OPPORTUNISTIC_SUB_INACTIVE_SUBSCRIPTION; } else if (!confirm) { resultForCallBack = SET_OPPORTUNISTIC_SUB_VALIDATION_FAILED; } else { if (mSubscriptionController.isOpportunistic(subId)) { setOpportunisticSubscriptionInternal(subId); } else { // Switching data back to primary subscription. setOpportunisticSubscriptionInternal(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID); } resultForCallBack = SET_OPPORTUNISTIC_SUB_SUCCESS; } // Trigger callback if needed sendSetOpptCallbackHelper(mSetOpptSubCallback, resultForCallBack); mSetOpptSubCallback = null; mPendingSwitchSubId = INVALID_SUBSCRIPTION_ID; } private void onNetworkAvailable(int subId, Network network) { log("onNetworkAvailable: on subId " + subId); // Do nothing unless pending switch matches target subId and it doesn't require // validation pass. if (mPendingSwitchSubId == INVALID_SUBSCRIPTION_ID || mPendingSwitchSubId != subId || mPendingSwitchNeedValidation) { return; } confirmSwitch(subId, true); } private void onValidationDone(int subId, boolean passed) { log("onValidationDone: " + (passed ? "passed" : "failed") + " on subId " + subId); if (mPendingSwitchSubId == INVALID_SUBSCRIPTION_ID || mPendingSwitchSubId != subId) return; // If validation failed and mPendingSwitch.mNeedValidation is false, we still confirm // the switch. confirmSwitch(subId, passed || !mPendingSwitchNeedValidation); } /** * Notify PhoneSwitcher to try to switch data to an opportunistic subscription. * * Set opportunistic data subscription. It's an indication to switch Internet data to this * subscription. It has to be an active subscription, and PhoneSwitcher will try to validate * it first if needed. If subId is DEFAULT_SUBSCRIPTION_ID, it means we are un-setting * opportunistic data sub and switch data back to primary sub. * * @param subId the opportunistic data subscription to switch to. pass DEFAULT_SUBSCRIPTION_ID * if un-setting it. * @param needValidation whether Telephony will wait until the network is validated by * connectivity service before switching data to it. More details see * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED}. * @param callback Callback will be triggered once it succeeds or failed. * Pass null if don't care about the result. */ public void trySetOpportunisticDataSubscription(int subId, boolean needValidation, ISetOpportunisticDataCallback callback) { log("Try set opportunistic data subscription to subId " + subId + (needValidation ? " with " : " without ") + "validation"); PhoneSwitcher.this.obtainMessage(EVENT_OPPT_DATA_SUB_CHANGED, subId, needValidation ? 1 : 0, callback).sendToTarget(); } protected boolean isPhoneInVoiceCall(Phone phone) { if (phone == null) { return false; } // A phone in voice call might trigger data being switched to it. // We only report true if its precise call state is ACTIVE, ALERTING or HOLDING. // The reason is data switching is interrupting, so we only switch when necessary and // acknowledged by the users. For incoming call, we don't switch until answered // (RINGING -> ACTIVE), for outgoing call we don't switch until call is connected // in network (DIALING -> ALERTING). return (phone.getForegroundCall().getState() == Call.State.ACTIVE || phone.getForegroundCall().getState() == Call.State.ALERTING || phone.getBackgroundCall().getState() == Call.State.HOLDING); } private void updateHalCommandToUse() { mHalCommandToUse = mRadioConfig.isSetPreferredDataCommandSupported() ? HAL_COMMAND_PREFERRED_DATA : HAL_COMMAND_ALLOW_DATA; } public int getOpportunisticDataSubscriptionId() { return mOpptDataSubId; } public int getPreferredDataPhoneId() { return mPreferredDataPhoneId; } @UnsupportedAppUsage protected void log(String l) { Rlog.d(LOG_TAG, l); mLocalLog.log(l); } private void logDataSwitchEvent(int subId, int state, int reason) { log("logDataSwitchEvent subId " + subId + " state " + state + " reason " + reason); DataSwitch dataSwitch = new DataSwitch(); dataSwitch.state = state; dataSwitch.reason = reason; TelephonyMetrics.getInstance().writeDataSwitch(subId, dataSwitch); } /** * See {@link PhoneStateListener#LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE}. */ protected void notifyPreferredDataSubIdChanged() { TelephonyRegistryManager telephonyRegistryManager = (TelephonyRegistryManager) mContext .getSystemService(Context.TELEPHONY_REGISTRY_SERVICE); log("notifyPreferredDataSubIdChanged to " + mPreferredDataSubId.get()); telephonyRegistryManager.notifyActiveDataSubIdChanged(mPreferredDataSubId.get()); } /** * @return The active data subscription id */ public int getActiveDataSubId() { return mPreferredDataSubId.get(); } // TODO (b/148396668): add an internal callback method to monitor phone capability change, // and hook this call to that callback. private void onPhoneCapabilityChanged(PhoneCapability capability) { onPhoneCapabilityChangedInternal(capability); } public void dump(FileDescriptor fd, PrintWriter writer, String[] args) { final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); pw.println("PhoneSwitcher:"); Calendar c = Calendar.getInstance(); for (int i = 0; i < mActiveModemCount; i++) { PhoneState ps = mPhoneStates[i]; c.setTimeInMillis(ps.lastRequested); pw.println("PhoneId(" + i + ") active=" + ps.active + ", lastRequest=" + (ps.lastRequested == 0 ? "never" : String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c))); } pw.increaseIndent(); mLocalLog.dump(fd, pw, args); pw.decreaseIndent(); } }
3e15673b4c354ccc13e7eea831946451399adbbc
1,029
java
Java
Program238.java
PRASAD-DANGARE/JAVA
1f01746c008f09f51de19fcc0c2e68f089c04b52
[ "MIT" ]
4
2021-06-07T07:55:45.000Z
2021-07-06T16:41:07.000Z
Program238.java
PRASAD-DANGARE/JAVA
1f01746c008f09f51de19fcc0c2e68f089c04b52
[ "MIT" ]
null
null
null
Program238.java
PRASAD-DANGARE/JAVA
1f01746c008f09f51de19fcc0c2e68f089c04b52
[ "MIT" ]
null
null
null
21.4375
81
0.506317
9,101
/////////////////////////////////////////////////////////// // // Description : Accept String From User And Find The Frequency Of Characters // Input : Str // Output : Str // Author : Prasad Dangare // Date : 2 June 2021 // /////////////////////////////////////////////////////////// import java.util.*; class Demo { public void CharacterFrequency(String str) { char Arr[] = str.toCharArray(); int Frequency = 0; HashMap <Character,Integer> hobj = new HashMap<Character,Integer>(); for(char ch : Arr) { if(hobj.containsKey(ch)) { Frequency = hobj.get(ch); //hobj.put(ch,hobj.get(ch)+1); } else { hobj.put(ch,1); } } System.out.println(hobj); } } class Program238 { public static void main(String arg[]) { Scanner sobj = new Scanner(System.in); System.out.println("Enter string"); String str = sobj.nextLine(); Demo dobj = new Demo(); dobj.CharacterFrequency(str); } }
3e156761ca0ba7e5b81c405a33367781d0c4d340
12,887
java
Java
src/team492/CmdAutoDiagnostics.java
coolioasjulio/Frc2018FirstPowerUp
43ddbfb67e247f908650a5201593d177c6b9c203
[ "MIT" ]
9
2018-01-14T04:29:09.000Z
2019-01-06T02:19:04.000Z
src/team492/CmdAutoDiagnostics.java
coolioasjulio/Frc2018FirstPowerUp
43ddbfb67e247f908650a5201593d177c6b9c203
[ "MIT" ]
2
2018-09-25T16:34:43.000Z
2019-03-29T19:54:31.000Z
src/team492/CmdAutoDiagnostics.java
coolioasjulio/Frc2018FirstPowerUp
43ddbfb67e247f908650a5201593d177c6b9c203
[ "MIT" ]
3
2018-06-26T00:04:24.000Z
2018-07-16T23:22:49.000Z
38.816265
117
0.502444
9,102
/* * Copyright (c) 2018 Titan Robotics Club (http://www.titanrobotics.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package team492; import common.CmdTimedDrive; import frclib.FrcCANTalon; import trclib.TrcEvent; import trclib.TrcRobot; import trclib.TrcStateMachine; import trclib.TrcTimer; public class CmdAutoDiagnostics implements TrcRobot.RobotCommand { private static final String moduleName = "CmdAutoDiagnostics"; private static final double DRIVE_TIME = 5.0; private static final double ENCODER_Y_ERROR_THRESHOLD = 5.0/RobotInfo.ENCODER_Y_INCHES_PER_COUNT; // 5 inches private static final double FLIPPER_EXTEND_DELAY = 3.0; private static final double ELEVATOR_ERROR_THRESHOLD = 2.0; // 2 inches private static final double GRABBER_DELAY = 3.0; private static final double GRABBER_CURRENT_THRESHOLD = 5.0; private enum State { START, SPIN_MOTORS_FORWARD, SPIN_MOTORS_BACKWARD, TEST_FLIPPERS, RAISE_ELEVATOR, CHECK_ELEVATOR, TOGGLE_GRABBER, TOGGLE_GRABBER_AGAIN, DONE } private Robot robot; private TrcStateMachine<State> sm; private TrcEvent event; private TrcTimer timer; private CmdTimedDrive timedDrive; private boolean diagnosticsFailed = false; public CmdAutoDiagnostics(Robot robot) { this.robot = robot; event = new TrcEvent(moduleName); sm = new TrcStateMachine<>(moduleName); timer = new TrcTimer(moduleName); sm.start(State.START); } private CmdTimedDrive createTimedDrive(double xPower, double yPower) { return new CmdTimedDrive(robot, 0.0, DRIVE_TIME, xPower, yPower, 0.0); } private FrcCANTalon[] getMotors() { return new FrcCANTalon[] { robot.leftFrontWheel, robot.rightFrontWheel, robot.leftRearWheel, robot.rightRearWheel }; } private void checkMotorEncoders() { final String funcName = "checkMotorEncoders"; FrcCANTalon[] motors = getMotors(); double[] motorPositions = new double[motors.length]; double avgPos = 0; for(int i = 0; i < motors.length; i++) { double pos = motors[i].getPosition(); motorPositions[i] = pos; avgPos += pos; } avgPos /= (double)motors.length; for(int i = 0; i < motors.length; i++) { double error = avgPos - motorPositions[i]; if(Math.abs(error) >= ENCODER_Y_ERROR_THRESHOLD) { robot.globalTracer.traceWarn( funcName, "Motor %s may not be working! AvgPos:%.2f, Pos:%.2f, Error:%.2f", motors[i], avgPos, motorPositions[i], error); diagnosticsFailed = true; } else { robot.globalTracer.traceInfo( funcName, "Motor %s seems to be working! AvgPos:%.2f, Pos:%.2f, Error:%.2f", motors[i], avgPos, motorPositions[i], error); } } } @Override public boolean cmdPeriodic(double elapsedTime) { final String funcName = moduleName + ".cmdPeriodic"; boolean done = !sm.isEnabled(); if (done) return true; State state = sm.checkReadyAndGetState(); // // Print debug info. // robot.dashboard.displayPrintf(1, "State: %s", state != null? state: sm.getState()); double yPosition, pickupCurrent; if(state != null) { switch(state) { case START: timedDrive = null; diagnosticsFailed = false; sm.setState(State.SPIN_MOTORS_FORWARD); break; case SPIN_MOTORS_FORWARD: if(timedDrive == null) { robot.driveBase.resetOdometry(); timedDrive = createTimedDrive(0.0,0.7); } if(timedDrive.cmdPeriodic(elapsedTime)) { checkMotorEncoders(); yPosition = robot.driveBase.getYPosition(); if(yPosition > 0) { robot.globalTracer.traceInfo( funcName, "Spun forward! Motors working okay! yPosition=%.2f", yPosition); } else { robot.globalTracer.traceInfo( funcName, "Tried to spin forward! Motors are not okay! yPosition=%.2f", yPosition); diagnosticsFailed = true; } timedDrive = null; sm.setState(State.SPIN_MOTORS_BACKWARD); } break; case SPIN_MOTORS_BACKWARD: if(timedDrive == null) { robot.driveBase.resetOdometry(); timedDrive = createTimedDrive(0.0,-0.7); } if(timedDrive.cmdPeriodic(elapsedTime)) { checkMotorEncoders(); yPosition = robot.driveBase.getYPosition(); if(yPosition < 0) { robot.globalTracer.traceInfo( funcName, "Spun backward! Motors working okay, probably! yPosition=%.2f", yPosition); } else { robot.globalTracer.traceInfo( funcName, "Tried to spin backward! Motors are not okay, probably! yPosition=%.2f", yPosition); diagnosticsFailed = true; } sm.setState(State.TEST_FLIPPERS); } break; case TEST_FLIPPERS: robot.globalTracer.traceInfo( funcName, "Attempting to extend flippers for %.1f seconds!", FLIPPER_EXTEND_DELAY); robot.leftFlipper.timedExtend(FLIPPER_EXTEND_DELAY); robot.rightFlipper.timedExtend(FLIPPER_EXTEND_DELAY); timer.set(FLIPPER_EXTEND_DELAY, event); sm.waitForSingleEvent(event, State.RAISE_ELEVATOR); break; case RAISE_ELEVATOR: robot.globalTracer.traceInfo( funcName, "Attempting to raise elevator to %.1f inches!", RobotInfo.ELEVATOR_MAX_HEIGHT); robot.elevator.setPosition(RobotInfo.ELEVATOR_MAX_HEIGHT, event, 3.0); sm.waitForSingleEvent(event, State.CHECK_ELEVATOR); break; case CHECK_ELEVATOR: // CodeReview: Again, elevator.setPosition may wait forever here. double elevatorHeight = robot.elevator.getPosition(); double error = RobotInfo.ELEVATOR_MAX_HEIGHT - elevatorHeight; if(error >= ELEVATOR_ERROR_THRESHOLD) { robot.globalTracer.traceWarn( funcName, "Elevator innacurate! Target: %.2f, Actual: %.2f, Error: %.2f", RobotInfo.ELEVATOR_MAX_HEIGHT, elevatorHeight, error); diagnosticsFailed = true; } else { robot.globalTracer.traceInfo( funcName, "Elevator working fine!, Target: %.2f, Actual: %.2f, Error: %.2f", RobotInfo.ELEVATOR_MAX_HEIGHT, elevatorHeight, error); } robot.elevator.setPosition(RobotInfo.ELEVATOR_MIN_HEIGHT, event, 3.0); sm.waitForSingleEvent(event, State.TOGGLE_GRABBER); break; case TOGGLE_GRABBER: if(robot.cubePickup.isClawOpen()) { robot.cubePickup.closeClaw(); } else { robot.cubePickup.openClaw(); } if(robot.cubePickup.isPickupDeployed()) { robot.cubePickup.raisePickup(); } else { robot.cubePickup.deployPickup(); } robot.cubePickup.setPickupPower(1.0); timer.set(GRABBER_DELAY, event); sm.waitForSingleEvent(event, State.TOGGLE_GRABBER_AGAIN); break; case TOGGLE_GRABBER_AGAIN: pickupCurrent = robot.cubePickup.getPickupCurrent(); if(pickupCurrent >= GRABBER_CURRENT_THRESHOLD) { robot.globalTracer.traceInfo( funcName, "Grabber motors in working! Current=%.2f, Power=%.2f", pickupCurrent, robot.cubePickup.getPickupPower()); } else { robot.globalTracer.traceErr( funcName, "Grabber motors in not working! Current=%.2f, Power=%.2f", pickupCurrent, robot.cubePickup.getPickupPower()); diagnosticsFailed = true; } if(robot.cubePickup.isClawOpen()) { robot.cubePickup.closeClaw(); } else { robot.cubePickup.openClaw(); } if(robot.cubePickup.isPickupDeployed()) { robot.cubePickup.raisePickup(); } else { robot.cubePickup.deployPickup(); } robot.cubePickup.dropCube(1.0); timer.set(GRABBER_DELAY, event); sm.waitForSingleEvent(event, State.DONE); break; case DONE: pickupCurrent = robot.cubePickup.getPickupCurrent(); if(pickupCurrent >= GRABBER_CURRENT_THRESHOLD) { robot.globalTracer.traceInfo( funcName, "Grabber motors out working! Current=%.2f, Power=%.2f", pickupCurrent, robot.cubePickup.getPickupPower()); } else { robot.globalTracer.traceErr( funcName, "Grabber motors out not working! Current=%.2f, Power=%.2f", pickupCurrent, robot.cubePickup.getPickupPower()); diagnosticsFailed = true; } robot.cubePickup.stopPickup(); if (diagnosticsFailed) robot.ledIndicator.indicateDiagnosticError(); else robot.ledIndicator.indicateNoDiagnosticError(); done = true; break; } } return done; } }
3e156765a666365caf85fd435c1586836bf2d8a8
252
java
Java
remappedSrc/me/bscal/bettershields/bettershields/combat/ShieldEvents.java
bscal/BetterShields
66580ff2f807aeec71d0d2a882ac7b77242f0138
[ "MIT" ]
null
null
null
remappedSrc/me/bscal/bettershields/bettershields/combat/ShieldEvents.java
bscal/BetterShields
66580ff2f807aeec71d0d2a882ac7b77242f0138
[ "MIT" ]
null
null
null
remappedSrc/me/bscal/bettershields/bettershields/combat/ShieldEvents.java
bscal/BetterShields
66580ff2f807aeec71d0d2a882ac7b77242f0138
[ "MIT" ]
null
null
null
22.909091
59
0.833333
9,103
package me.bscal.bettershields.bettershields.common.combat; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; public class ShieldEvents { }
3e15677bf7f1d991e30adf2753ca9fe30c120050
9,797
java
Java
src/main/java/com/Da_Technomancer/crossroads/API/technomancy/IFluxLink.java
Crossroads-Development/Crossroads
5b55e7a6984aefe25168ac6c25f0426966acda72
[ "MIT" ]
1
2021-12-20T18:48:07.000Z
2021-12-20T18:48:07.000Z
src/main/java/com/Da_Technomancer/crossroads/API/technomancy/IFluxLink.java
Crossroads-Development/Crossroads
5b55e7a6984aefe25168ac6c25f0426966acda72
[ "MIT" ]
29
2021-10-04T15:30:47.000Z
2022-03-11T16:24:04.000Z
src/main/java/com/Da_Technomancer/crossroads/API/technomancy/IFluxLink.java
Crossroads-Development/Crossroads
5b55e7a6984aefe25168ac6c25f0426966acda72
[ "MIT" ]
5
2021-10-03T22:31:26.000Z
2022-02-06T13:25:52.000Z
29.42042
327
0.722364
9,104
package com.Da_Technomancer.crossroads.API.technomancy; import com.Da_Technomancer.crossroads.API.IInfoTE; import com.Da_Technomancer.crossroads.API.packets.CRPackets; import com.Da_Technomancer.crossroads.API.packets.IIntArrayReceiver; import com.Da_Technomancer.crossroads.API.packets.SendIntArrayToClient; import com.Da_Technomancer.crossroads.CRConfig; import com.Da_Technomancer.crossroads.ambient.sounds.CRSounds; import com.Da_Technomancer.crossroads.render.CRRenderUtil; import com.Da_Technomancer.essentials.packets.ILongReceiver; import com.Da_Technomancer.essentials.tileentities.ILinkTE; import com.Da_Technomancer.essentials.tileentities.ITickableTileEntity; import com.Da_Technomancer.essentials.tileentities.LinkHelper; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundSource; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import java.util.function.Consumer; public interface IFluxLink extends ILongReceiver, ILinkTE, IInfoTE, IIntArrayReceiver{ int getFlux(); /** * Used for things like omnimeter readouts and rendering- anything the player would see to smooth out the technical fluctuations in getFlux() * @return The total flux that should be represented to the player. */ int getReadingFlux(); /** * Inserts flux to this. Positive values only * @param deltaFlux The increase in flux */ void addFlux(int deltaFlux); /** * Maximum flux this machine can safely contain * @return Flux limit before overloading */ default int getMaxFlux(){ return 64; } @Override default int getRange(){ return 16; } /** * Will not be called if canAcceptLinks() is false * @return Whether this machine can currently accept flux */ default boolean allowAccepting(){ return true; } /** * Should be state independent * @return Whether this machine can ever accept flux */ boolean canAcceptLinks(); @Override default Color getColor(){ return Color.BLACK; } /** * Will only be called on the virtual client * Each int represents one entropy transfer arc * Format for each int: * bits[0,7]: relative x * bits[8,15]: relative y * bits[16,23]: relative z * bits[24,31]: Unused * @return An array of ints representing all transferred entropy to be rendered */ int[] getRenderedArcs(); /** * For rendering * Only called on the virtual client side * @return Whether this block should render effects for being near the failure point */ default boolean renderFluxWarning(){ return false; } enum Behaviour{ SOURCE(1, false),//Flux should be routed away from this TE SINK(0, true),//Flux should be routed towards this TE NODE(16, true);//Connect in a large network of these TEs private final int maxLinks; private final boolean allowedToAccept; Behaviour(int maxLinks, boolean canAccept){ this.maxLinks = maxLinks; this.allowedToAccept = canAccept; } } /** * A standard implementation of IFluxLink * Can be used as either a superclass (extenders should pass null/themselves and their type to the constructor), or as an instantiated helper (instantiators should pass any non-null type and themselves to the constructor) * When used as a helper, calls to the IFluxLink & tick methods should be passed to this class, and read() & write() should call readData() and writeData() */ class FluxHelper extends BlockEntity implements ITickableTileEntity, IFluxLink{ private static final byte RENDER_ID = 6; private final BlockEntity owner; private final Behaviour behaviour; private final LinkHelper linkHelper; private int queuedFlux = 0; private int readingFlux = 0; public int flux = 0; public long lastTick = 0; protected Consumer<Integer> fluxTransferHandler; private boolean shutDown = false;//Only used if safe mode is enabled in the config private int[] rendered = new int[0]; public FluxHelper(BlockEntityType<?> type, BlockPos pos, BlockState state, @Nullable BlockEntity owner, Behaviour behaviour){ this(type, pos, state, owner, behaviour, null); } public FluxHelper(BlockEntityType<?> type, BlockPos pos, BlockState state, @Nullable BlockEntity owner, Behaviour behaviour, @Nullable Consumer<Integer> fluxTransferHandler){ super(type, pos, state); this.owner = owner == null ? this : owner; this.behaviour = behaviour; linkHelper = new LinkHelper((ILinkTE) this.owner); this.fluxTransferHandler = fluxTransferHandler; } @Override public void load(CompoundTag nbt){ super.load(nbt); readData(nbt); } @Override public void saveAdditional(CompoundTag nbt){ super.saveAdditional(nbt); writeData(nbt); } @Override public CompoundTag getUpdateTag(){ CompoundTag nbt = super.getUpdateTag(); nbt.putIntArray("rendered_arcs", rendered); return nbt; } public void readData(CompoundTag nbt){ linkHelper.readNBT(nbt); lastTick = nbt.getLong("last_tick"); flux = nbt.getInt("flux"); queuedFlux = nbt.getInt("queued_flux"); readingFlux = nbt.getInt("reading_flux"); shutDown = nbt.getBoolean("shutdown"); rendered = nbt.getIntArray("rendered_arcs"); } public void writeData(CompoundTag nbt){ linkHelper.writeNBT(nbt); nbt.putLong("last_tick", lastTick); nbt.putInt("flux", flux); nbt.putInt("queued_flux", queuedFlux); nbt.putInt("reading_flux", readingFlux); nbt.putBoolean("shutdown", shutDown); nbt.putIntArray("rendered_arcs", rendered); } /** * Ticks the flux handler * Should be called every tick on the virtual server side */ @Override public void serverTick(){ ITickableTileEntity.super.serverTick(); Level world = owner.getLevel(); long worldTime = world.getGameTime(); if(worldTime != lastTick){ lastTick = worldTime; if(lastTick % FluxUtil.FLUX_TIME == 0){ int toTransfer = flux; readingFlux = flux; flux = queuedFlux; queuedFlux = 0; if(fluxTransferHandler == null){ Pair<Integer, int[]> transferResult = FluxUtil.performTransfer(this, linkHelper.getLinksRelative(), toTransfer); flux += transferResult.getLeft(); if(!Arrays.equals(transferResult.getRight(), rendered)){ rendered = transferResult.getRight(); CRPackets.sendPacketAround(world, owner.getBlockPos(), new SendIntArrayToClient(RENDER_ID, rendered, owner.getBlockPos())); } }else{ fluxTransferHandler.accept(toTransfer); } owner.setChanged(); shutDown = FluxUtil.checkFluxOverload(this); } } } /** * Ticks the flux handler * Should be called every tick on the virtual client side */ @Override public void clientTick(){ ITickableTileEntity.super.clientTick(); //Play sounds Level world = owner.getLevel(); BlockPos pos = owner.getBlockPos(); if(rendered.length != 0 && world.getGameTime() % FluxUtil.FLUX_TIME == 0 && CRConfig.fluxSounds.get()){ CRSounds.playSoundClientLocal(world, pos, CRSounds.FLUX_TRANSFER, SoundSource.BLOCKS, 0.4F, 1F); } //This 5 is the lifetime of the render if(world.getGameTime() % 5 == 0 && renderFluxWarning()){ CRRenderUtil.addArc(world, pos.getX() + 0.5F, pos.getY() + 0.5F, pos.getZ() + 0.5F, pos.getX() + 0.5F + 2.5F * (float) (Math.random() - 0.5F), pos.getY() + 0.5F + 2.5F * (float) (Math.random() - 0.5F), pos.getZ() + 0.5F + 2.5F * (float) (Math.random() - 0.5F), 3, 1F, FluxUtil.COLOR_CODES[(int) (world.getGameTime() % 3)]); } } public boolean isShutDown(){ return shutDown; } @Override public boolean allowAccepting(){ return !isShutDown(); } @Override public int getFlux(){ return flux; } @Override public int getReadingFlux(){ return readingFlux; } @Override public void addFlux(int deltaFlux){ if(owner.getLevel().getGameTime() == lastTick){ flux += deltaFlux; }else{ queuedFlux += deltaFlux; } owner.setChanged(); } @Override public void addInfo(ArrayList<Component> chat, Player player, BlockHitResult hit){ FluxUtil.addLinkInfo(chat, (ILinkTE) owner); } @Override public Set<BlockPos> getLinks(){ return linkHelper.getLinksRelative(); } @Override public boolean createLinkSource(ILinkTE endpoint, @Nullable Player player){ return linkHelper.addLink(endpoint, player); } @Override public void removeLinkSource(BlockPos end){ linkHelper.removeLink(end); } @Override public void receiveLong(byte id, long value, @Nullable ServerPlayer sender){ linkHelper.handleIncomingPacket(id, value); } @Override public void receiveInts(byte context, int[] message, @Nullable ServerPlayer sendingPlayer){ if(context == RENDER_ID){ rendered = message == null ? new int[0] : message; } } @Override public boolean canBeginLinking(){ return behaviour != Behaviour.SINK; } @Override public boolean canAcceptLinks(){ return behaviour.allowedToAccept; } @Override public boolean canLink(ILinkTE otherTE){ return otherTE instanceof IFluxLink && ((IFluxLink) otherTE).canAcceptLinks(); } @Override public int getMaxLinks(){ return behaviour.maxLinks; } @Override public BlockEntity getTE(){ return owner; } @Override public int[] getRenderedArcs(){ return rendered; } } }
3e1568c4e12d131f452920fd5f9aae0afa9472ba
5,904
java
Java
gravitee-management-api-rest/src/main/java/io/gravitee/management/rest/resource/RoleUsersResource.java
Raphcal/gravitee-management-rest-api
1f8ca2a24e5a1667450f97c429e814f6db846a6d
[ "Apache-2.0" ]
null
null
null
gravitee-management-api-rest/src/main/java/io/gravitee/management/rest/resource/RoleUsersResource.java
Raphcal/gravitee-management-rest-api
1f8ca2a24e5a1667450f97c429e814f6db846a6d
[ "Apache-2.0" ]
null
null
null
gravitee-management-api-rest/src/main/java/io/gravitee/management/rest/resource/RoleUsersResource.java
Raphcal/gravitee-management-rest-api
1f8ca2a24e5a1667450f97c429e814f6db846a6d
[ "Apache-2.0" ]
null
null
null
37.846154
133
0.696308
9,105
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.management.rest.resource; import io.gravitee.common.http.MediaType; import io.gravitee.management.model.MemberEntity; import io.gravitee.management.model.UserEntity; import io.gravitee.management.model.permissions.RolePermission; import io.gravitee.management.model.permissions.RolePermissionAction; import io.gravitee.management.rest.model.GroupMembership; import io.gravitee.management.rest.model.RoleMembership; import io.gravitee.management.rest.security.Permission; import io.gravitee.management.rest.security.Permissions; import io.gravitee.management.service.MembershipService; import io.gravitee.management.service.UserService; import io.gravitee.repository.management.model.MembershipDefaultReferenceId; import io.gravitee.repository.management.model.MembershipReferenceType; import io.gravitee.repository.management.model.RoleScope; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import javax.inject.Inject; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.*; import javax.ws.rs.container.ResourceContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; /** * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com) * @author GraviteeSource Team */ @Api(tags = {"Roles"}) public class RoleUsersResource extends AbstractResource { @Context private ResourceContext resourceContext; @Autowired private MembershipService membershipService; @GET @Produces(MediaType.APPLICATION_JSON) @Permissions({ @Permission(value = RolePermission.MANAGEMENT_ROLE, acls = RolePermissionAction.READ) }) public Set<MembershipListItem> listUsersPerRole( @PathParam("scope")RoleScope scope, @PathParam("role") String role) { if (RoleScope.MANAGEMENT.equals(scope) || RoleScope.PORTAL.equals(scope)) { Set<MemberEntity> members = membershipService.getMembers( RoleScope.MANAGEMENT.equals(scope) ? MembershipReferenceType.MANAGEMENT : MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.name(), scope, role); return members.stream().map(MembershipListItem::new).collect(Collectors.toSet()); } return Collections.emptySet(); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Add or update a role to a user") @Permissions({ @Permission(value = RolePermission.MANAGEMENT_ROLE, acls = RolePermissionAction.CREATE), @Permission(value = RolePermission.MANAGEMENT_ROLE, acls = RolePermissionAction.UPDATE), }) public Response addRoleToUser( @ApiParam(name = "scope", required = true, allowableValues = "MANAGEMENT,PORTAL,API,APPLICATION") @PathParam("scope")RoleScope roleScope, @PathParam("role") String roleName, @Valid @NotNull final RoleMembership roleMembership) { if (roleScope == null || roleName == null) { return Response.status(Response.Status.BAD_REQUEST).entity("Role must be set").build(); } MemberEntity membership = membershipService.addOrUpdateMember( new MembershipService.MembershipReference( RoleScope.MANAGEMENT.equals(roleScope) ? MembershipReferenceType.MANAGEMENT : MembershipReferenceType.PORTAL, MembershipDefaultReferenceId.DEFAULT.name()), new MembershipService.MembershipUser(roleMembership.getId(), roleMembership.getReference()), new MembershipService.MembershipRole(roleScope, roleName)); return Response.created(URI.create("/users/" + membership.getId() + "/roles/" + membership.getId())).build(); } @Path("{userId}") public RoleUserResource getRoleUserResource() { return resourceContext.getResource(RoleUserResource.class); } private final static class MembershipListItem { private final String id; private final String username; private final String firstname; private final String lastname; public MembershipListItem(final MemberEntity member) { this.id = member.getId(); this.username = member.getUsername(); this.firstname = member.getFirstname(); this.lastname = member.getLastname(); } public String getId() { return id; } public String getUsername() { return username; } public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public String getDisplayName() { if (this.firstname != null) { return this.firstname + " " + this.lastname; } return this.username; } } }
3e156986ae22689b683a437787a45704f22d084b
4,299
java
Java
confignode/src/main/java/org/apache/iotdb/confignode/client/AsyncDataNodeClientPool.java
SzyWilliam/iotdb
13c732b43a307fe2ecbf6cd990cc537f8c73eceb
[ "Apache-2.0" ]
null
null
null
confignode/src/main/java/org/apache/iotdb/confignode/client/AsyncDataNodeClientPool.java
SzyWilliam/iotdb
13c732b43a307fe2ecbf6cd990cc537f8c73eceb
[ "Apache-2.0" ]
null
null
null
confignode/src/main/java/org/apache/iotdb/confignode/client/AsyncDataNodeClientPool.java
SzyWilliam/iotdb
13c732b43a307fe2ecbf6cd990cc537f8c73eceb
[ "Apache-2.0" ]
null
null
null
34.669355
97
0.739242
9,106
/* * 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.iotdb.confignode.client; import org.apache.iotdb.common.rpc.thrift.TEndPoint; import org.apache.iotdb.common.rpc.thrift.THeartbeatReq; import org.apache.iotdb.commons.client.IClientManager; import org.apache.iotdb.commons.client.async.AsyncDataNodeInternalServiceClient; import org.apache.iotdb.confignode.client.handlers.CreateRegionHandler; import org.apache.iotdb.confignode.client.handlers.HeartbeatHandler; import org.apache.iotdb.mpp.rpc.thrift.TCreateDataRegionReq; import org.apache.iotdb.mpp.rpc.thrift.TCreateSchemaRegionReq; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** Asynchronously send RPC requests to DataNodes. See mpp.thrift for more details. */ public class AsyncDataNodeClientPool { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncDataNodeClientPool.class); private final IClientManager<TEndPoint, AsyncDataNodeInternalServiceClient> clientManager; private AsyncDataNodeClientPool() { clientManager = new IClientManager.Factory<TEndPoint, AsyncDataNodeInternalServiceClient>() .createClientManager( new ConfigNodeClientPoolFactory.AsyncDataNodeInternalServiceClientPoolFactory()); } /** * Create a SchemaRegion on specific DataNode * * @param endPoint The specific DataNode */ public void createSchemaRegion( TEndPoint endPoint, TCreateSchemaRegionReq req, CreateRegionHandler handler) { AsyncDataNodeInternalServiceClient client; try { client = clientManager.borrowClient(endPoint); client.createSchemaRegion(req, handler); } catch (IOException e) { LOGGER.error("Can't connect to DataNode {}", endPoint, e); } catch (TException e) { LOGGER.error("Create SchemaRegion on DataNode {} failed", endPoint, e); } } /** * Create a DataRegion on specific DataNode * * @param endPoint The specific DataNode */ public void createDataRegion( TEndPoint endPoint, TCreateDataRegionReq req, CreateRegionHandler handler) { AsyncDataNodeInternalServiceClient client; try { client = clientManager.borrowClient(endPoint); client.createDataRegion(req, handler); } catch (IOException e) { LOGGER.error("Can't connect to DataNode {}", endPoint, e); } catch (TException e) { LOGGER.error("Create DataRegion on DataNode {} failed", endPoint, e); } } /** * Only used in LoadManager * * @param endPoint The specific DataNode */ public void getHeartBeat(TEndPoint endPoint, THeartbeatReq req, HeartbeatHandler handler) { AsyncDataNodeInternalServiceClient client; try { client = clientManager.borrowClient(endPoint); client.getHeartBeat(req, handler); } catch (Exception e) { LOGGER.error("Asking DataNode: {}, for heartbeat failed", endPoint, e); } } /** * Always call this interface when a DataNode is restarted or removed * * @param endPoint The specific DataNode */ public void resetClient(TEndPoint endPoint) { clientManager.clear(endPoint); } // TODO: Is the ClientPool must be a singleton? private static class ClientPoolHolder { private static final AsyncDataNodeClientPool INSTANCE = new AsyncDataNodeClientPool(); private ClientPoolHolder() { // Empty constructor } } public static AsyncDataNodeClientPool getInstance() { return ClientPoolHolder.INSTANCE; } }
3e156a08acd51ba7cc7f9f92a0b7e937533fcc08
2,320
java
Java
src/test/java/com/stripe/functional/terminal/LocationTest.java
seratch/stripe-java
8ff74910a578430aff0a659da79d515ec9fbffdd
[ "MIT" ]
null
null
null
src/test/java/com/stripe/functional/terminal/LocationTest.java
seratch/stripe-java
8ff74910a578430aff0a659da79d515ec9fbffdd
[ "MIT" ]
null
null
null
src/test/java/com/stripe/functional/terminal/LocationTest.java
seratch/stripe-java
8ff74910a578430aff0a659da79d515ec9fbffdd
[ "MIT" ]
null
null
null
27.619048
70
0.696552
9,107
package com.stripe.functional.terminal; import static org.junit.Assert.assertNotNull; import com.stripe.BaseStripeTest; import com.stripe.exception.StripeException; import com.stripe.model.terminal.Location; import com.stripe.model.terminal.LocationCollection; import com.stripe.net.ApiResource; import java.util.HashMap; import java.util.Map; import org.junit.Test; public class LocationTest extends BaseStripeTest { public static final String LOCATION_ID = "loc_123"; @Test public void testCreate() throws StripeException { final Map<String, Object> params = new HashMap<String, Object>(); final Map<String, String> address = new HashMap<String, String>(); address.put("line1", "line1"); address.put("country", "US"); address.put("state", "CA"); address.put("postal_code", "123"); address.put("city", "San Francisco"); params.put("address", address); params.put("display_name", "name"); final Location location = Location.create(params); assertNotNull(location); verifyRequest( ApiResource.RequestMethod.POST, String.format("/v1/terminal/locations"), params ); } @Test public void testRetrieve() throws StripeException { final Location location = Location.retrieve(LOCATION_ID); assertNotNull(location); verifyRequest( ApiResource.RequestMethod.GET, String.format("/v1/terminal/locations/%s", LOCATION_ID) ); } @Test public void testUpdate() throws StripeException { final Location location = Location.retrieve(LOCATION_ID); final Map<String, Object> params = new HashMap<String, Object>(); params.put("display_name", "new_name"); final Location updatedLocation = location.update(params); assertNotNull(updatedLocation); verifyRequest( ApiResource.RequestMethod.POST, String.format("/v1/terminal/locations/%s", location.getId()), params ); } @Test public void testList() throws StripeException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("limit", 1); LocationCollection resources = Location.list(params); assertNotNull(resources); verifyRequest( ApiResource.RequestMethod.GET, String.format("/v1/terminal/locations"), params ); } }
3e156b82f32c3fbbf648e8ef8066a28055bac602
1,816
java
Java
engine/src/main/java/nl/inl/blacklab/forwardindex/FIDoc.java
lexionai/BlackLab
b2b9381b848114190746a465dad57697249b49e9
[ "Apache-2.0" ]
67
2015-01-13T09:28:00.000Z
2022-03-13T10:05:51.000Z
engine/src/main/java/nl/inl/blacklab/forwardindex/FIDoc.java
jan-niestadt/BlackLab
4ce7c7018f75717c12be5c768f5b2f26c442b196
[ "Apache-2.0" ]
243
2015-01-27T23:18:52.000Z
2022-03-25T09:17:30.000Z
engine/src/main/java/nl/inl/blacklab/forwardindex/FIDoc.java
lexionai/BlackLab
b2b9381b848114190746a465dad57697249b49e9
[ "Apache-2.0" ]
44
2015-01-19T18:53:44.000Z
2022-02-25T07:06:05.000Z
35.607843
84
0.65033
9,108
package nl.inl.blacklab.forwardindex; import java.util.List; import nl.inl.blacklab.search.indexmetadata.Annotation; /** A document in the (multi-)forward index. */ public interface FIDoc { /** * Delete document from the forward index * * @param fiid id of the document to delete */ void delete(); /** * Retrieve one or more parts from the document, in the form of token * ids. * * This is more efficient than retrieving the whole content, or retrieving parts * in separate calls, because the file is only opened once and random access is * used to read only the required parts. * * NOTE: if offset and length are both -1, retrieves the whole content. This is * used by the retrieve(id) method. * * NOTE2: Mapped file IO on Windows has some issues that sometimes cause an * OutOfMemoryError on the FileChannel.map() call (which makes no sense, because * memory mapping only uses address space, it doesn't try to read the whole * file). Possibly this could be solved by using 64-bit Java, but we haven't * tried. For now we just disable memory mapping on Windows. * * @param annotation annotation for which to retrieve content * @param fiid forward index document id * @param start the starting points of the parts to retrieve (in words) (-1 for * start of document) * @param end the end points (i.e. first token beyond) of the parts to retrieve * (in words) (-1 for end of document) * @return the parts */ List<int[]> retrievePartsInt(Annotation annotation, int[] start, int[] end); /** * Gets the length (in tokens) of the document * * @return length of the document */ int docLength(); }
3e156b9b8e424970ece55eef730e321349f72311
4,964
java
Java
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/util/BackendOperation.java
aksaharan/titan
1fc9959967a2a34255afa2408e8e6335f0544821
[ "Apache-2.0" ]
1
2017-03-28T01:56:59.000Z
2017-03-28T01:56:59.000Z
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/util/BackendOperation.java
areadrom/titan
1fc9959967a2a34255afa2408e8e6335f0544821
[ "Apache-2.0" ]
null
null
null
titan-core/src/main/java/com/thinkaurelius/titan/diskstorage/util/BackendOperation.java
areadrom/titan
1fc9959967a2a34255afa2408e8e6335f0544821
[ "Apache-2.0" ]
1
2019-09-18T21:01:18.000Z
2019-09-18T21:01:18.000Z
43.535088
173
0.660286
9,109
package com.thinkaurelius.titan.diskstorage.util; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.core.TitanException; import com.thinkaurelius.titan.diskstorage.StorageException; import com.thinkaurelius.titan.diskstorage.TemporaryStorageException; import com.thinkaurelius.titan.diskstorage.keycolumnvalue.StoreTransaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; /** * @author Matthias Broecheler (dycjh@example.com) */ public class BackendOperation { private static final Logger log = LoggerFactory.getLogger(BackendOperation.class); private static final long BASE_REATTEMPT_TIME_MS=50; public static final<V> V execute(Callable<V> exe, long maxTimeMS) throws TitanException { long waitTime = BASE_REATTEMPT_TIME_MS; long maxTime = System.currentTimeMillis()+maxTimeMS; StorageException lastException = null; do { try { return exe.call(); } catch (StorageException e) { if (e instanceof TemporaryStorageException) lastException = e; else throw new TitanException("Permanent exception during backend operation",e); //Its permanent } catch (Throwable e) { throw new TitanException("Unexpected exception during backend operation",e); } //Wait and retry Preconditions.checkNotNull(lastException); if (System.currentTimeMillis()+waitTime<maxTime) { log.info("Temporary storage exception during backend operation. Attempting backoff retry",exe.toString(),lastException); try { Thread.sleep(waitTime); } catch (InterruptedException r) { throw new TitanException("Interrupted while waiting to retry failed storage operation", r); } } waitTime*=2; //Exponential backoff } while (System.currentTimeMillis()<maxTime); throw new TitanException("Could not successfully complete backend operation due to repeated temporary exceptions after "+maxTimeMS+" ms",lastException); } private static final double WAITTIME_PERTURBATION_PERCENTAGE = 0.5; private static final double WAITTIME_PERTURBATION_PERCENTAGE_HALF = WAITTIME_PERTURBATION_PERCENTAGE/2; public static final<V> V execute(Callable<V> exe, int maxRetryAttempts, long retryWaittime) throws TitanException { Preconditions.checkArgument(maxRetryAttempts>0,"Retry attempts must be positive"); Preconditions.checkArgument(retryWaittime>=0,"Retry wait time must be non-negative"); int retryAttempts = 0; StorageException lastException = null; do { try { return exe.call(); } catch (StorageException e) { if (e instanceof TemporaryStorageException) lastException = e; else throw new TitanException("Permanent exception during backend operation",e); //Its permanent } catch (Throwable e) { throw new TitanException("Unexpected exception during backend operation",e); } //Wait and retry retryAttempts++; Preconditions.checkNotNull(lastException); if (retryAttempts<maxRetryAttempts) { long waitTime = Math.round(retryWaittime+((Math.random()*WAITTIME_PERTURBATION_PERCENTAGE-WAITTIME_PERTURBATION_PERCENTAGE_HALF)*retryWaittime)); Preconditions.checkArgument(waitTime>=0,"Invalid wait time: %s",waitTime); log.info("Temporary storage exception during backend operation [{}]. Attempting incremental retry",exe.toString(),lastException); try { Thread.sleep(waitTime); } catch (InterruptedException r) { throw new TitanException("Interrupted while waiting to retry failed backend operation", r); } } } while (retryAttempts<maxRetryAttempts); throw new TitanException("Could not successfully complete backend operation due to repeated temporary exceptions after "+maxRetryAttempts+" attempts",lastException); } public static<R> R execute(Transactional<R> exe, TransactionalProvider provider) throws StorageException { StoreTransaction txh = null; try { txh = provider.openTx(); return exe.call(txh); } catch (StorageException e) { if (txh!=null) txh.rollback(); txh=null; throw e; } finally { if (txh!=null) txh.commit(); } } public static interface Transactional<R> { public R call(StoreTransaction txh) throws StorageException; } public static interface TransactionalProvider { public StoreTransaction openTx() throws StorageException; } }
3e156d20884e8a401a1420d372800f4bf32136f9
1,531
java
Java
editor/src/main/java/com/kotcrab/vis/editor/module/scene/RendererModule.java
Blunderchips/vis-editor
0ba9fd4678f1086b18c0455eb3d2a8761e1a8fae
[ "Apache-2.0" ]
12
2019-01-31T08:42:16.000Z
2020-12-19T05:15:05.000Z
editor/src/main/java/com/kotcrab/vis/editor/module/scene/RendererModule.java
Blunderchips/vis-editor
0ba9fd4678f1086b18c0455eb3d2a8761e1a8fae
[ "Apache-2.0" ]
1
2018-12-07T09:03:49.000Z
2018-12-07T09:03:49.000Z
editor/src/main/java/com/kotcrab/vis/editor/module/scene/RendererModule.java
Blunderchips/vis-editor
0ba9fd4678f1086b18c0455eb3d2a8761e1a8fae
[ "Apache-2.0" ]
15
2018-12-29T14:48:28.000Z
2020-11-12T12:01:30.000Z
26.859649
75
0.753103
9,110
/* * Copyright 2014-2017 See AUTHORS file. * * 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.kotcrab.vis.editor.module.scene; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; /** * @author Kotcrab */ public class RendererModule extends SceneModule { private CameraModule camera; private ShapeRenderer shapeRenderer; @Override public void added () { shapeRenderer = new ShapeRenderer(); } @Override public void render (Batch batch) { batch.end(); shapeRenderer.setProjectionMatrix(camera.getCombinedMatrix()); shapeRenderer.setColor(Color.LIGHT_GRAY); shapeRenderer.begin(ShapeType.Line); shapeRenderer.rect(0, 0, scene.width, scene.height); shapeRenderer.end(); batch.begin(); } @Override public void dispose () { shapeRenderer.dispose(); } public ShapeRenderer getShapeRenderer () { return shapeRenderer; } }
3e156d97d812efad389ffba517c05df841183bf0
8,516
java
Java
src/main/java/de/hterhors/semanticmr/crf/structure/annotations/filter/EntityTemplateAnnotationFilter.java
hterhors/SemanticMachineReading
6ead021e736761baf143b4afc52440b07b977d44
[ "Apache-2.0" ]
1
2019-12-02T17:11:18.000Z
2019-12-02T17:11:18.000Z
src/main/java/de/hterhors/semanticmr/crf/structure/annotations/filter/EntityTemplateAnnotationFilter.java
hterhors/SemanticMachineReading
6ead021e736761baf143b4afc52440b07b977d44
[ "Apache-2.0" ]
3
2021-03-31T21:51:34.000Z
2021-12-14T21:19:18.000Z
src/main/java/de/hterhors/semanticmr/crf/structure/annotations/filter/EntityTemplateAnnotationFilter.java
hterhors/SemanticMachineReading
6ead021e736761baf143b4afc52440b07b977d44
[ "Apache-2.0" ]
null
null
null
29.985915
102
0.717943
9,111
package de.hterhors.semanticmr.crf.structure.annotations.filter; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import de.hterhors.semanticmr.crf.structure.annotations.AbstractAnnotation; import de.hterhors.semanticmr.crf.structure.annotations.DocumentLinkedAnnotation; import de.hterhors.semanticmr.crf.structure.annotations.EntityTemplate; import de.hterhors.semanticmr.crf.structure.annotations.EntityTypeAnnotation; import de.hterhors.semanticmr.crf.structure.annotations.LiteralAnnotation; import de.hterhors.semanticmr.crf.structure.annotations.MultiFillerSlot; import de.hterhors.semanticmr.crf.structure.annotations.SingleFillerSlot; import de.hterhors.semanticmr.crf.structure.annotations.SlotType; public class EntityTemplateAnnotationFilter implements IAnnotationFilter { final private Map<SlotType, AbstractAnnotation> singleAnnotations; final private Map<SlotType, Set<AbstractAnnotation>> multiAnnotations; final private Map<SlotType, Set<AbstractAnnotation>> mergedAnnotations; public EntityTemplateAnnotationFilter(Map<SlotType, AbstractAnnotation> singleAnnotations, Map<SlotType, Set<AbstractAnnotation>> multiAnnotations, Map<SlotType, Set<AbstractAnnotation>> mergedAnnotations) { this.singleAnnotations = singleAnnotations; this.multiAnnotations = multiAnnotations; this.mergedAnnotations = mergedAnnotations; } public Map<SlotType, AbstractAnnotation> getSingleAnnotations() { return singleAnnotations; } public Map<SlotType, Set<AbstractAnnotation>> getMultiAnnotations() { return multiAnnotations; } public Map<SlotType, Set<AbstractAnnotation>> getMergedAnnotations() { return mergedAnnotations; } public static class Builder implements IBuilder<EntityTemplateAnnotationFilter> { final private EntityTemplate entityTemplate; private boolean multiSlots; private boolean singleSlots; private boolean nonEmpty; private boolean rootAnnotation; private boolean docLinkedAnnoation; private boolean literalAnnoation; private boolean entityTypeAnnoation; private boolean entityTemplateAnnoation; private boolean merge; private Map<SlotType, AbstractAnnotation> singleAnnotations; private Map<SlotType, Set<AbstractAnnotation>> multiAnnotations; private Map<SlotType, Set<AbstractAnnotation>> mergedAnnotations; public Builder(EntityTemplate entityTemplate) { this.entityTemplate = entityTemplate; } public Builder rootAnnotation() { this.rootAnnotation = true; return this; } public Builder singleSlots() { this.singleSlots = true; return this; } public Builder multiSlots() { this.multiSlots = true; return this; } public Builder nonEmpty() { this.nonEmpty = true; return this; } public Builder docLinkedAnnoation() { this.docLinkedAnnoation = true; return this; } public Builder literalAnnoation() { this.literalAnnoation = true; return this; } public Builder entityTypeAnnoation() { this.entityTypeAnnoation = true; return this; } public Builder entityTemplateAnnoation() { this.entityTemplateAnnoation = true; return this; } public Builder merge() { this.merge = true; return this; } public EntityTemplateAnnotationFilter build() { if (merge) { mergedAnnotations = new HashMap<>(); } else { mergedAnnotations = Collections.emptyMap(); } if (multiSlots) { multiAnnotations = new HashMap<>(); for (SlotType slotType : entityTemplate.getMultiFillerSlotTypes()) { if (slotType.isExcluded()) continue; final MultiFillerSlot slot = entityTemplate.getMultiFillerSlot(slotType); if (!slot.containsSlotFiller()) { if (!nonEmpty) { mergedAnnotations.putIfAbsent(slotType, Collections.emptySet()); multiAnnotations.putIfAbsent(slotType, Collections.emptySet()); } continue; } for (AbstractAnnotation slotFiller : slot.getSlotFiller()) { if (docLinkedAnnoation && slotFiller.isInstanceOfDocumentLinkedAnnotation()) { final DocumentLinkedAnnotation dla = slotFiller.asInstanceOfDocumentLinkedAnnotation(); if (dla == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(dla); } multiAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); multiAnnotations.get(slotType).add(dla); } if (literalAnnoation && slotFiller.isInstanceOfLiteralAnnotation()) { final LiteralAnnotation la = slotFiller.asInstanceOfLiteralAnnotation(); if (la == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(la); } multiAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); multiAnnotations.get(slotType).add(la); } if (entityTypeAnnoation && slotFiller.isInstanceOfEntityTypeAnnotation()) { final EntityTypeAnnotation eta = slotFiller.asInstanceOfEntityTypeAnnotation(); if (eta == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(eta); } multiAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); multiAnnotations.get(slotType).add(eta); } if (entityTemplateAnnoation && slotFiller.isInstanceOfEntityTemplate()) { final EntityTemplate et = slotFiller.asInstanceOfEntityTemplate(); if (et == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(et); } multiAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); multiAnnotations.get(slotType).add(et); } } } } else { multiAnnotations = Collections.emptyMap(); } if (singleSlots) { singleAnnotations = new HashMap<>(); for (SlotType slotType : entityTemplate.getSingleFillerSlotTypes()) { if (slotType.isExcluded()) continue; final SingleFillerSlot slot = entityTemplate.getSingleFillerSlot(slotType); if (!slot.containsSlotFiller()) { if (!nonEmpty) { mergedAnnotations.putIfAbsent(slotType, Collections.emptySet()); singleAnnotations.putIfAbsent(slotType, null); } continue; } if (docLinkedAnnoation && slot.getSlotFiller().isInstanceOfDocumentLinkedAnnotation()) { DocumentLinkedAnnotation slotFiller = slot.getSlotFiller() .asInstanceOfDocumentLinkedAnnotation(); if (slotFiller == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(slotFiller); } singleAnnotations.put(slotType, slotFiller); } if (literalAnnoation && slot.getSlotFiller().isInstanceOfLiteralAnnotation()) { final LiteralAnnotation slotFiller = slot.getSlotFiller().asInstanceOfLiteralAnnotation(); if (slotFiller == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(slotFiller); } singleAnnotations.put(slotType, slotFiller); } if (entityTypeAnnoation && slot.getSlotFiller().isInstanceOfEntityTypeAnnotation()) { final EntityTypeAnnotation slotFiller = slot.getSlotFiller().asInstanceOfEntityTypeAnnotation(); if (slotFiller == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(slotFiller); } singleAnnotations.put(slotType, slotFiller); } if (entityTemplateAnnoation && slot.getSlotFiller().isInstanceOfEntityTemplate()) { final EntityTemplate slotFiller = slot.getSlotFiller().asInstanceOfEntityTemplate(); if (slotFiller == null) continue; if (merge) { mergedAnnotations.putIfAbsent(slotType, new LinkedHashSet<>()); mergedAnnotations.get(slotType).add(slotFiller); } singleAnnotations.put(slotType, slotFiller); } } } else { singleAnnotations = Collections.emptyMap(); } return new EntityTemplateAnnotationFilter(singleAnnotations, multiAnnotations, mergedAnnotations); } } }
3e156e46ebba2c0a69013efe732820a5f79a0105
7,874
java
Java
aurochs-common/src/main/java/cn/aurochs/www/util/SeqUUIDUtil.java
sekift/aurochs
1c6070eb73ace113a44e9b4fe58f3423f269e0e8
[ "MIT" ]
2
2019-12-10T09:32:41.000Z
2019-12-13T06:37:27.000Z
aurochs-common/src/main/java/cn/aurochs/www/util/SeqUUIDUtil.java
sekift/aurochs
1c6070eb73ace113a44e9b4fe58f3423f269e0e8
[ "MIT" ]
null
null
null
aurochs-common/src/main/java/cn/aurochs/www/util/SeqUUIDUtil.java
sekift/aurochs
1c6070eb73ace113a44e9b4fe58f3423f269e0e8
[ "MIT" ]
null
null
null
29.939163
115
0.596393
9,112
package cn.aurochs.www.util; import java.util.UUID; /** * 有序UUID 工具类 * 备注:有序的UUID生成工具类, UUID为32byte字符串. * <p>字符串组成:prefix_char + timestamp + uuid_mostSigBits + uuid_leastSigBits * <pre> * 使用实例: * <1>简单生成 * String sid = SeqUUIDUtil.toSequenceUUID(); // <-- 根据调用方法的时间点,然后随机生成一个UUID对象 * <2>根据时间戳生成 * long current = System.currentTimeMillis(); * String sid = SeqUUIDUtil.toSequenceUUID(current); * <3>根据UUID生成 * UUID uuid = UUID.randomUUID(); * String sid = SeqUUIDUtil.toSequenceUUID(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); * <4>根据时间戳+UUID生成 * long current = System.currentTimeMillis(); * UUID uuid = UUID.randomUUID(); * String sid = SeqUUIDUtil.toSequenceUUID(current, uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); * <5>从有序的UUID中提取它生成时间点的时间戳 * String sid = .... // <-- 一个有序的UUID字符串 * long timestamp = SeqUUIDUtil.extractTimestamp(sid); * 特征: * long current0 = System.currentTimeMillis(); * String sid = SeqUUIDUtil.toSequenceUUID(current0); * long current1 = SeqUUIDUtil.extractTimestamp(sid); * 存在: current0 == current1; * <6>从有序的UUID中提及uuid * UUID uuid0 = UUID.randomUUID(); * String sid = SeqUUIDUtil.toSequenceUUID(uuid0.getMostSignificantBits(), uuid0.getLeastSignificantBits()); * long m = SeqUUIDUtil.extractMostSignificantBits(sid); * long l = SeqUUIDUtil.extractLeastSignificantBits(sid); * UUID uuid1 = new UUID(m, l); * 存在: uuid0.equals(uuid1) == true; * </pre> * @author sekift * @teme 2019-5-19 上午11:31:56 */ public final class SeqUUIDUtil { /** * 默认前缀字符 */ private static char DEFAULT_PREFIX_CHAR = 'o'; /** * 时间戳生成一个有序的uuid字符串 * 使用默认前缀字符(DEFAULT_PREFIX_CHAR)做为前缀 * @param timestamp -- 时间戳 * @return -- 有序的uuid字符串,长度为32位 */ public static String toSequenceUUID(long timestamp) { return toSequenceUUID(DEFAULT_PREFIX_CHAR, timestamp); } /** * 根据当前时间点的时间戳和一个UUID(UUID的高64位和低64位作为参数)生成一个有序的uuid字符串 * @param mostSigBits -- UUID的高64位 * @param leastSigBits -- UUID的低64位 * @return -- 有序的uuid字符串 */ public static String toSequenceUUID(long mostSigBits, long leastSigBits) { return toSequenceUUID(DEFAULT_PREFIX_CHAR, System.currentTimeMillis(), mostSigBits, leastSigBits); } /** * 根据时间戳和一个UUID(UUID的高64位和低64位作为参数)生成一个有序的uuid字符串 * @param timestamp -- 时间戳 * @param mostSigBits -- UUID的高64位 * @param leastSigBits -- UUID的低64位 * @return -- 有序的uuid字符串 */ public static String toSequenceUUID(long timestamp, long mostSigBits, long leastSigBits) { return toSequenceUUID(DEFAULT_PREFIX_CHAR, timestamp, mostSigBits, leastSigBits); } /** * 将一个前缀和时间戳生成一个有序的uuid字符串 * @param prefix -- 前缀字符, 必须是一个字节(byte)的字符 * @param timestamp -- 时间戳 * @return -- 有序的uuid字符串,长度为32位 */ public static String toSequenceUUID(char prefix, long timestamp) { UUID u = UUID.randomUUID(); return toSequenceUUID(prefix, timestamp, u.getMostSignificantBits(), u.getLeastSignificantBits()); } /** * 将一个[前缀,时间戳, UUID的高64bit, UUID的低64bit]生成一个有序的uuid字符串 * @param prefix -- 前缀字符, 必须是一个字节(byte)的字符 * @param timestamp -- 时间戳, 单位毫秒, 见System.currentTimeMillis(); * @param mostSigBits -- UUID的高64bit * @param leastSigBits -- UUID的低64bit * @return */ public static String toSequenceUUID(char prefix, long timestamp, long mostSigBits, long leastSigBits) { if (prefix > Byte.MAX_VALUE) { throw new IllegalArgumentException("prefix必须是一个字节(byte)的字符"); } StringBuilder sb = new StringBuilder(32); sb.append(prefix); sb.append(BaseConvert.compressNumber(timestamp, 5)); String m = BaseConvert.compressNumber(mostSigBits, 6); sb.append(m); if (m.length() < 11) { sb.append("_"); // 作为分隔符 } sb.append(BaseConvert.compressNumber(leastSigBits, 6)); int len = 32 - sb.length(); if (len > 0) { sb.append("________________________________", 0, len); // 32 个'_' 作为补白 } return sb.toString(); } /** * 根据当前时间戳为种子,生成一个有序的uuid字符串 * @return 有序的uuid字符串,长度为32位 */ public static String toSequenceUUID() { return toSequenceUUID(System.currentTimeMillis()); } /** * 通过一个有序的uuid字符串中提取时间戳 * sequenceUUID必须通过UUIDUtil.toSequenceUUID方法生成 * @param sequenceUUID -- 有序uuid字符串 * @return -- 有序uuid中的时间戳 */ public static long extractTimestamp(String sequenceUUID) { return BaseConvert.decompressNumber(sequenceUUID.substring(1, 10), 5); } /** * 通过一个有序的uuid字符串中提取UUID对象的高64bit * @param sequenceUUID -- 有序的uuid * @return -- UUID对象的高64bit */ public static long extractMostSignificantBits(String sequenceUUID) { int endIndex = sequenceUUID.indexOf((int)'_', 10); if (endIndex < 10) { endIndex = 21; } return BaseConvert.decompressNumber(sequenceUUID.substring(10, endIndex), 6); } /** * 通过一个有序的uuid字符串中提取UUID对象的低64bit * @param sequenceUUID -- 有序的uuid * @return -- UUID对象的低64bit */ public static long extractLeastSignificantBits(String sequenceUUID) { int startIndex = sequenceUUID.indexOf((int)'_', 10) + 1; // 加1 为了跳过'_'分隔符 if (startIndex < 10) { startIndex = 21; } int endIndex = sequenceUUID.indexOf((int)'_', startIndex); if (endIndex < 21) { endIndex = 32; } return BaseConvert.decompressNumber(sequenceUUID.substring(startIndex, endIndex), 6); } /** * 进制转换类 * */ public static class BaseConvert { /** * 进制编码表, 使用base64编码表作为基础, 使用'-'替换'+', * 目的是UUIDUtil使用生成的id可以在url不编码就可以传递 */ final static char[] digits = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' , '-' , '_' , }; /** * 把10进制的数字转换成2^shift进制 字符串 * @param number 10进制数字 * @param shift 5表示32进制,6表示64进制,原理 2^shift * @return 2^shift进制字符串 */ public static String compressNumber(long number, int shift) { char[] buf = new char[64]; int charPos = 64; int radix = 1 << shift; long mask = radix - 1; do { buf[--charPos] = digits[(int)(number & mask)]; number >>>= shift; } while (number != 0); return new String(buf, charPos, (64 - charPos)); } /** * 把2^shift进制的字符串转换成10进制 * @param decompStr 2^shift进制的字符串 * @param shift 5表示32进制,6表示64进制,原理 2^shift * @return 10进制数字 */ public static long decompressNumber(String decompStr, int shift) { long result = 0; for (int i = decompStr.length() - 1; i >= 0; i--) { if (i == decompStr.length() - 1) { result += getCharIndexNum(decompStr.charAt(i)); continue; } for (int j = 0; j < digits.length; j++) { if (decompStr.charAt(i) == digits[j]) { result += ((long)j) << shift * (decompStr.length() - 1 - i); } } } return result; } /** * 将字符转成数值 * @param ch -- 字符 * @return -- 对应数值 */ private static long getCharIndexNum(char ch) { int num = ((int)ch); if ( num >= 48 && num <= 57) { return num - 48; } else if (num >= 97 && num <= 122) { return num - 87; } else if (num >= 65 && num <= 90) { return num - 29; } else if (num == 43) { return 62; } else if (num == 47) { return 63; } return 0; } } }
3e156ec3edda46c230ef35e0897671d7d5fa9720
2,353
java
Java
src/test/java/seedu/bagel/storage/StorageManagerTest.java
yuki-cell/tp
d33e21e657c1b077ffc752894b3cea6861a67eee
[ "MIT" ]
null
null
null
src/test/java/seedu/bagel/storage/StorageManagerTest.java
yuki-cell/tp
d33e21e657c1b077ffc752894b3cea6861a67eee
[ "MIT" ]
92
2020-09-19T05:15:27.000Z
2020-11-13T13:47:27.000Z
src/test/java/seedu/bagel/storage/StorageManagerTest.java
yuki-cell/tp
d33e21e657c1b077ffc752894b3cea6861a67eee
[ "MIT" ]
5
2020-09-12T14:03:04.000Z
2020-09-25T20:52:37.000Z
34.101449
111
0.713982
9,113
package seedu.bagel.storage; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static seedu.bagel.testutil.TypicalFlashcards.getTypicalBagel; import java.nio.file.Path; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import seedu.bagel.commons.core.GuiSettings; import seedu.bagel.model.Bagel; import seedu.bagel.model.ReadOnlyBagel; import seedu.bagel.model.UserPrefs; public class StorageManagerTest { @TempDir public Path testFolder; private StorageManager storageManager; @BeforeEach public void setUp() { JsonBagelStorage bagelStorage = new JsonBagelStorage(getTempFilePath("ab")); JsonUserPrefsStorage userPrefsStorage = new JsonUserPrefsStorage(getTempFilePath("prefs")); storageManager = new StorageManager(bagelStorage, userPrefsStorage); } private Path getTempFilePath(String fileName) { return testFolder.resolve(fileName); } @Test public void prefsReadSave() throws Exception { /* * Note: This is an integration test that verifies the StorageManager is properly wired to the * {@link JsonUserPrefsStorage} class. * More extensive testing of UserPref saving/reading is done in {@link JsonUserPrefsStorageTest} class. */ UserPrefs original = new UserPrefs(); original.setGuiSettings(new GuiSettings(300, 600, 4, 6)); storageManager.saveUserPrefs(original); UserPrefs retrieved = storageManager.readUserPrefs().get(); assertEquals(original, retrieved); } @Test public void bagelReadSave() throws Exception { /* * Note: This is an integration test that verifies the StorageManager is properly wired to the * {@link JsonBagelStorage} class. * More extensive testing of UserPref saving/reading is done in {@link JsonBagelStorageTest} class. */ Bagel original = getTypicalBagel(); storageManager.saveBagel(original); ReadOnlyBagel retrieved = storageManager.readBagel().get(); assertEquals(original, new Bagel(retrieved)); } @Test public void getBagelFilePath() { assertNotNull(storageManager.getBagelFilePath()); } }
3e156fd5cc2cdbea4077738ddc2de1aeda2ede9b
1,810
java
Java
jpower-module-common/common-deploy/src/main/java/com/wlcb/jpower/module/common/deploy/config/JpowerDeployConfiguration.java
g-mr/JPower
0fe699c1eb52481f9169770fce2db393806536c5
[ "Apache-2.0" ]
5
2021-06-02T06:34:35.000Z
2022-02-16T01:38:27.000Z
jpower-module-common/common-deploy/src/main/java/com/wlcb/jpower/module/common/deploy/config/JpowerDeployConfiguration.java
Jeansuyan/JPower
94929b03d89f98558e96a5fc6649666ca61f41ea
[ "Apache-2.0" ]
null
null
null
jpower-module-common/common-deploy/src/main/java/com/wlcb/jpower/module/common/deploy/config/JpowerDeployConfiguration.java
Jeansuyan/JPower
94929b03d89f98558e96a5fc6649666ca61f41ea
[ "Apache-2.0" ]
4
2021-06-03T01:49:50.000Z
2022-03-20T10:48:03.000Z
30.677966
105
0.807182
9,114
package com.wlcb.jpower.module.common.deploy.config; import com.wlcb.jpower.module.common.deploy.props.JpowerProperties; import com.wlcb.jpower.module.common.utils.Fc; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import java.net.InetAddress; /** * 配置类 * * @author mr.g */ @Configuration(proxyBeanMethods = false) @Order(Ordered.HIGHEST_PRECEDENCE) @EnableConfigurationProperties({ JpowerProperties.class }) public class JpowerDeployConfiguration implements SmartInitializingSingleton { private final ServerProperties serverProperties; private final JpowerProperties jpowerProperties; @Autowired(required = false) public JpowerDeployConfiguration(ServerProperties serverProperties, JpowerProperties jpowerProperties) { this.serverProperties = serverProperties; this.jpowerProperties = jpowerProperties; } @Override public void afterSingletonsInstantiated() { if (Fc.notNull(serverProperties)){ jpowerProperties.setHostName(getHostName(serverProperties.getAddress())); jpowerProperties.setIp(getHostAddress(serverProperties.getAddress())); jpowerProperties.setPort(serverProperties.getPort()); } } private String getHostName(InetAddress address){ if (Fc.isNull(address)){ return "127.0.0.1"; } return address.getHostName(); } private String getHostAddress(InetAddress address){ if (Fc.isNull(address)){ return "127.0.0.1"; } return address.getHostAddress(); } }
3e15711a5327dd2c1eef3a7e8c0691b01830ad89
401
java
Java
src/main/java/bio/terra/service/filedata/flight/FileMapKeys.java
CanDIG/jade-data-repo
c80074061b56a21fe696e68b6f54356d626e7fe9
[ "BSD-3-Clause" ]
null
null
null
src/main/java/bio/terra/service/filedata/flight/FileMapKeys.java
CanDIG/jade-data-repo
c80074061b56a21fe696e68b6f54356d626e7fe9
[ "BSD-3-Clause" ]
null
null
null
src/main/java/bio/terra/service/filedata/flight/FileMapKeys.java
CanDIG/jade-data-repo
c80074061b56a21fe696e68b6f54356d626e7fe9
[ "BSD-3-Clause" ]
null
null
null
30.846154
64
0.730673
9,115
package bio.terra.service.filedata.flight; public final class FileMapKeys { private FileMapKeys() { } public static final String DATASET_ID = "datasetId"; public static final String FILE_ID = "fileId"; public static final String FILE_INFO = "fileInfo"; public static final String BUCKET_INFO = "bucketInfo"; public static final String FIRESTORE_FILE = "fireStoreFile"; }
3e157334a884298a420353eb2554908840ae47e9
4,675
java
Java
ipmi-protocol/src/main/java/org/anarres/ipmi/protocol/packet/ipmi/command/chassis/ChassisControlRequest.java
shevek/ipmi4j
18e561dc3b3cca2ee3b704ef232f37539641263b
[ "Apache-2.0" ]
28
2015-12-29T16:09:08.000Z
2022-03-07T04:59:17.000Z
ipmi-protocol/src/main/java/org/anarres/ipmi/protocol/packet/ipmi/command/chassis/ChassisControlRequest.java
shevek/ipmi4j
18e561dc3b3cca2ee3b704ef232f37539641263b
[ "Apache-2.0" ]
4
2015-05-20T08:48:48.000Z
2019-12-12T11:13:29.000Z
ipmi-protocol/src/main/java/org/anarres/ipmi/protocol/packet/ipmi/command/chassis/ChassisControlRequest.java
shevek/ipmi4j
18e561dc3b3cca2ee3b704ef232f37539641263b
[ "Apache-2.0" ]
24
2015-05-08T03:32:33.000Z
2022-03-07T04:59:24.000Z
39.618644
122
0.67893
9,116
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.ipmi.protocol.packet.ipmi.command.chassis; import com.google.common.primitives.UnsignedBytes; import java.nio.ByteBuffer; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.anarres.ipmi.protocol.client.visitor.IpmiClientIpmiCommandHandler; import org.anarres.ipmi.protocol.client.visitor.IpmiHandlerContext; import org.anarres.ipmi.protocol.packet.common.Code; import org.anarres.ipmi.protocol.packet.ipmi.IpmiCommandName; import org.anarres.ipmi.protocol.packet.ipmi.command.AbstractIpmiRequest; /** * [IPMI2] Section 28.3, table 28-4, page 390. * * @author shevek */ public class ChassisControlRequest extends AbstractIpmiRequest { /** * [IPMI2] Section 28.3, table 28-4, page 390. */ public static enum ChassisCommand implements Code.DescriptiveWrapper { /** Force system into soft off (S4/S45) state. This is for 'emergency' * management power down actions. The command does not initiate a clean * shut-down of the operating system prior to powering down the system. */ PowerDown(0x00, "Power Down"), PowerUp(0x01, "Power Up"), /** * This command provides a power off interval of at least 1 second * following the deassertion of the system's * POWERGOOD status from the main power subsystem. It is * recommended that no action occur if system power is off (S4/S5) * when this action is selected, and that a D5h 'Request parameter(s) * not supported in present state.' error completion code be returned. * Note that some implementations may cause a system power up if a * power cycle operation is selected when system power is down. For * consistency of operation, it is recommended that system * management software first check the system power state before * issuing a power cycle, and only issue the command if system * power is ON or in a lower sleep state than S4/S5. */ PowerCycle(0x02, "Power Cycle"), /** In some implementations, the BMC may not know * whether a reset will cause any particular effect and will pulse the * system reset signal regardless of power state. If the implementation * can tell that no action will occur if a reset is delivered in a given * power state, then it is recommended (but still optional) that a D5h * 'Request parameter(s) not supported in present state.' error * completion code be returned. */ HardReset(0x03, "Hard Reset"), /** Pulse a version of a diagnostic * interrupt that goes directly to the processor(s). This is typically used * to cause the operating system to do a diagnostic dump (OS * dependent). The interrupt is commonly an NMI on IA-32 systems * and an INIT on Intel(r) Itanium(tm) processor based systems. */ PulseDiagnosticInterrupt(0x04, "Pulse Diagnostic Interrupt"), ACPIOverTemperatureShutdown(0x05, "Initiate a soft-shutdown of OS via ACPI by emulating a fatal overtemperature"); private final byte code; private final String description; /* pp */ private ChassisCommand(@Nonnegative int code, @Nonnull String description) { this.code = UnsignedBytes.checkedCast(code); this.description = description; } @Override public byte getCode() { return code; } @Override public String getDescription() { return description; } @Override public String toString() { return Code.Utils.toString(this); } } public ChassisCommand chassisCommand; @Override public IpmiCommandName getCommandName() { return IpmiCommandName.ChassisControl; } @Override public void apply(IpmiClientIpmiCommandHandler handler, IpmiHandlerContext context) { handler.handleChassisControlRequest(context, this); } @Override protected int getDataWireLength() { return 1; } @Override protected void toWireData(ByteBuffer buffer) { buffer.put(chassisCommand.getCode()); } @Override protected void fromWireData(ByteBuffer buffer) { chassisCommand = Code.fromBuffer(ChassisCommand.class, buffer); } @Override public void toStringBuilder(StringBuilder buf, int depth) { super.toStringBuilder(buf, depth); appendValue(buf, depth, "ChassisCommand", chassisCommand); } }
3e1574179cc9fb03ba1fa40524cb6667ba8c8dcd
915
java
Java
xchange-coinone/src/main/java/org/knowm/xchange/coinone/dto/account/CoinoneAuthRequest.java
m13oas/XChange
b348497dfaa83b182824f58e7e82a6c34c19b2ed
[ "MIT" ]
1,909
2015-01-01T16:52:44.000Z
2018-04-05T17:08:44.000Z
xchange-coinone/src/main/java/org/knowm/xchange/coinone/dto/account/CoinoneAuthRequest.java
m13oas/XChange
b348497dfaa83b182824f58e7e82a6c34c19b2ed
[ "MIT" ]
1,055
2018-04-06T11:04:04.000Z
2022-03-31T23:52:18.000Z
xchange-coinone/src/main/java/org/knowm/xchange/coinone/dto/account/CoinoneAuthRequest.java
amitkhandelwal/XChange
8a1bf4ecc073db50417f682f0f4fa86a5824ae27
[ "MIT" ]
1,152
2018-04-06T11:08:35.000Z
2022-03-31T07:54:32.000Z
17.596154
75
0.684153
9,117
package org.knowm.xchange.coinone.dto.account; import com.fasterxml.jackson.annotation.JsonProperty; public class CoinoneAuthRequest { @JsonProperty("access_token") protected String accessTocken; @JsonProperty("nonce") protected Long nonce; @JsonProperty("type") protected String type; /** * Constructor * * @param nonce */ public CoinoneAuthRequest(String accessTocken, Long nonce, String type) { this.accessTocken = accessTocken; this.nonce = nonce; this.type = type; } public String getAccessTocken() { return accessTocken; } public void setAccessTocken(String accessTocken) { this.accessTocken = accessTocken; } public Long getNonce() { return nonce; } public void setNonce(Long nonce) { this.nonce = nonce; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
3e157437a5665220ea807267e9249c720dcf9083
1,231
java
Java
AndroidStudioProjects/ViewPager/app/src/main/java/org/hotpoor/pyq/viewpager/MyFragmentPagerAdapter2.java
pengyuanqi/pyq_learn_android
630f9d8721c57915352fe5cc24f588aec0d30e4e
[ "MIT" ]
null
null
null
AndroidStudioProjects/ViewPager/app/src/main/java/org/hotpoor/pyq/viewpager/MyFragmentPagerAdapter2.java
pengyuanqi/pyq_learn_android
630f9d8721c57915352fe5cc24f588aec0d30e4e
[ "MIT" ]
null
null
null
AndroidStudioProjects/ViewPager/app/src/main/java/org/hotpoor/pyq/viewpager/MyFragmentPagerAdapter2.java
pengyuanqi/pyq_learn_android
630f9d8721c57915352fe5cc24f588aec0d30e4e
[ "MIT" ]
null
null
null
26.191489
105
0.718928
9,118
package org.hotpoor.pyq.viewpager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import android.view.ViewGroup; import java.util.List; public class MyFragmentPagerAdapter2 extends FragmentStatePagerAdapter{ private List<Fragment>fragList; private List<String>titleList; public MyFragmentPagerAdapter2(FragmentManager fm , List<Fragment>fragList , List<String>titleList) { super(fm); this.fragList=fragList; this.titleList=titleList; } @Override public Fragment getItem(int arg0) { return fragList.get(arg0); } @Override public CharSequence getPageTitle(int position) { return titleList.get(position); } @Override public int getCount() { return fragList.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { return super.instantiateItem(container, position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); } }
3e15745ea0c51309823bcf780f7e204acfa78ce2
773
java
Java
src/main/java/tech/blacksource/blacknectar/service/json/AsJson.java
BlackWholeLabs/BlackNectar-Service
866a12638a8cca20c2f5dbc49c2d88b403bd88c5
[ "Apache-2.0" ]
6
2017-01-15T09:34:37.000Z
2020-09-07T02:15:59.000Z
src/main/java/tech/blacksource/blacknectar/service/json/AsJson.java
BlackSourceLabs/BlackNectar-Service
866a12638a8cca20c2f5dbc49c2d88b403bd88c5
[ "Apache-2.0" ]
88
2016-12-03T00:03:46.000Z
2017-04-27T17:36:33.000Z
src/main/java/tech/blacksource/blacknectar/service/json/AsJson.java
BlackWholeLabs/BlackNectar-Service
866a12638a8cca20c2f5dbc49c2d88b403bd88c5
[ "Apache-2.0" ]
1
2022-03-15T07:05:12.000Z
2022-03-15T07:05:12.000Z
27.607143
75
0.732212
9,119
/* * * Copyright 2017 BlackSource, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.blacksource.blacknectar.service.json; import com.google.gson.JsonObject; /** * @author SirWellington */ interface AsJson { JsonObject asJson(); }
3e157569a13690a81f44ff565a41bcc2fae3949a
1,531
java
Java
chi-maven-plugin/etc/comparator/new/interaction/OtherMedicationDetailQueryBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
1
2022-03-09T12:17:41.000Z
2022-03-09T12:17:41.000Z
chi-maven-plugin/etc/comparator/old/interaction/OtherMedicationDetailQueryBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
chi-maven-plugin/etc/comparator/old/interaction/OtherMedicationDetailQueryBean.java
CanadaHealthInfoway/message-builder
a24b368b6ad7330ce8e1319e6bae130cea981818
[ "Apache-2.0" ]
null
null
null
37.341463
132
0.779229
9,120
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ /* This class was auto-generated by the message builder generator tools. */ package ca.infoway.messagebuilder.model.interaction; import ca.infoway.messagebuilder.annotation.Hl7PartTypeMapping; import ca.infoway.messagebuilder.model.InteractionBean; import ca.infoway.messagebuilder.model.common.mcci_mt002100ca.HL7MessageBean; import ca.infoway.messagebuilder.model.common.porx_mt060220ca.ParameterListBean; import ca.infoway.messagebuilder.model.common.quqi_mt020000ca.TriggerEventBean; /** * <p>Requests retrieval of detailed information about a single * ""other medication"" record, referenced by identifier. */ @Hl7PartTypeMapping({"PORX_IN060450CA"}) public class OtherMedicationDetailQueryBean extends HL7MessageBean<TriggerEventBean<ParameterListBean>> implements InteractionBean { }
3e1576253d8a5f2253f25cf7766d7048a03d8957
1,046
java
Java
workflow/automatiko-workflow-compiler/src/main/java/io/automatiko/engine/workflow/compiler/xml/DefaultSemanticModule.java
automatiko-io/automatiko-engine
463ee717912c50c8e244f361c1948a0916f804fc
[ "Apache-2.0" ]
26
2021-01-25T19:56:07.000Z
2022-03-07T00:03:18.000Z
workflow/automatiko-workflow-compiler/src/main/java/io/automatiko/engine/workflow/compiler/xml/DefaultSemanticModule.java
automatiko-io/automatiko-engine
463ee717912c50c8e244f361c1948a0916f804fc
[ "Apache-2.0" ]
99
2021-01-28T10:57:27.000Z
2022-03-29T16:19:19.000Z
workflow/automatiko-workflow-compiler/src/main/java/io/automatiko/engine/workflow/compiler/xml/DefaultSemanticModule.java
automatiko-io/automatiko-engine
463ee717912c50c8e244f361c1948a0916f804fc
[ "Apache-2.0" ]
3
2021-01-25T22:06:10.000Z
2022-03-03T10:08:01.000Z
23.772727
64
0.711281
9,121
package io.automatiko.engine.workflow.compiler.xml; import java.util.HashMap; import java.util.Map; public class DefaultSemanticModule implements SemanticModule { public String uri; public Map<String, Handler> handlers; public Map<Class<?>, Handler> handlersByClass; public DefaultSemanticModule(String uri) { this.uri = uri; this.handlers = new HashMap<String, Handler>(); this.handlersByClass = new HashMap<Class<?>, Handler>(); } public String getUri() { return this.uri; } public void addHandler(String name, Handler handler) { this.handlers.put(name, handler); if (handler != null && handler.generateNodeFor() != null) { this.handlersByClass.put(handler.generateNodeFor(), handler); } } public Handler getHandler(String name) { return this.handlers.get(name); } public Handler getHandlerByClass(Class<?> clazz) { while (clazz != null) { Handler handler = this.handlersByClass.get(clazz); if (handler != null) { return handler; } clazz = clazz.getSuperclass(); } return null; } }
3e157661883c343fa1c653d73cd9cfa4358bd2a4
501
java
Java
00_framework/core/src/main/java/com/bizzan/bitrade/constant/WithdrawStatus.java
dinghung/CoinExchange-1
cc57cdd62fb9f144eae8521bd3c183d5a2684560
[ "Apache-2.0" ]
85
2021-02-05T11:33:05.000Z
2022-03-31T08:02:53.000Z
00_framework/core/src/main/java/com/bizzan/bitrade/constant/WithdrawStatus.java
dinghung/CoinExchange-1
cc57cdd62fb9f144eae8521bd3c183d5a2684560
[ "Apache-2.0" ]
1
2021-05-27T07:46:49.000Z
2021-05-27T07:46:49.000Z
00_framework/core/src/main/java/com/bizzan/bitrade/constant/WithdrawStatus.java
dinghung/CoinExchange-1
cc57cdd62fb9f144eae8521bd3c183d5a2684560
[ "Apache-2.0" ]
69
2021-02-08T05:01:38.000Z
2022-03-31T23:54:27.000Z
20.875
64
0.718563
9,122
package com.bizzan.bitrade.constant; import com.bizzan.bitrade.core.BaseEnum; import com.fasterxml.jackson.annotation.JsonValue; import lombok.AllArgsConstructor; import lombok.Getter; /** * @author Jammy * @date 2020年02月25日 */ @AllArgsConstructor @Getter public enum WithdrawStatus implements BaseEnum { PROCESSING("审核中"),WAITING("等待放币"),FAIL("失败"), SUCCESS("成功"); private String cnName; @Override @JsonValue public int getOrdinal() { return this.ordinal(); } }
3e15777220d5b6a5e620deba9616ac8fdb3837ff
2,735
java
Java
java/JARS/hibernate-release-5.6.0.Final/project/hibernate-core/src/main/java/org/hibernate/sql/InFragment.java
midnightbr/Faculdade
9a5a4b251e85fec002a2b1c7ddba25c2030d2e7c
[ "MIT" ]
1
2021-11-11T01:36:23.000Z
2021-11-11T01:36:23.000Z
java/JARS/hibernate-release-5.6.0.Final/project/hibernate-core/src/main/java/org/hibernate/sql/InFragment.java
midnightbr/Faculdade
9a5a4b251e85fec002a2b1c7ddba25c2030d2e7c
[ "MIT" ]
null
null
null
java/JARS/hibernate-release-5.6.0.Final/project/hibernate-core/src/main/java/org/hibernate/sql/InFragment.java
midnightbr/Faculdade
9a5a4b251e85fec002a2b1c7ddba25c2030d2e7c
[ "MIT" ]
null
null
null
21.706349
106
0.632541
9,123
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.sql; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.hibernate.internal.util.StringHelper; /** * An SQL IN expression. * <br> * <code>... in(...)</code> * <br> * * @author Gavin King */ public class InFragment { public static final String NULL = "null"; public static final String NOT_NULL = "not null"; protected String columnName; protected List<Object> values = new ArrayList<Object>(); /** * @param value an SQL literal, NULL, or NOT_NULL * * @return {@code this}, for method chaining */ public InFragment addValue(Object value) { values.add( value ); return this; } public InFragment addValues(Object[] values) { Collections.addAll( this.values, values ); return this; } public InFragment setColumn(String columnName) { this.columnName = columnName; return this; } public InFragment setColumn(String alias, String columnName) { this.columnName = StringHelper.qualify( alias, columnName ); return setColumn( this.columnName ); } public InFragment setFormula(String alias, String formulaTemplate) { this.columnName = StringHelper.replace( formulaTemplate, Template.TEMPLATE, alias ); return setColumn( this.columnName ); } public String toFragmentString() { if ( values.size() == 0 ) { return "1=2"; } StringBuilder buf = new StringBuilder( values.size() * 5 ); if ( values.size() == 1 ) { Object value = values.get( 0 ); buf.append( columnName ); if ( NULL.equals( value ) ) { buf.append( " is null" ); } else { if ( NOT_NULL.equals( value ) ) { buf.append( " is not null" ); } else { buf.append( '=' ).append( value ); } } return buf.toString(); } boolean allowNull = false; for ( Object value : values ) { if ( NULL.equals( value ) ) { allowNull = true; } else { if ( NOT_NULL.equals( value ) ) { throw new IllegalArgumentException( "not null makes no sense for in expression" ); } } } if ( allowNull ) { buf.append( '(' ).append( columnName ).append( " is null or " ).append( columnName ).append( " in (" ); } else { buf.append( columnName ).append( " in (" ); } for ( Object value : values ) { if ( !NULL.equals( value ) ) { buf.append( value ); buf.append( ", " ); } } buf.setLength( buf.length() - 2 ); if ( allowNull ) { buf.append( "))" ); } else { buf.append( ')' ); } return buf.toString(); } }
3e15782bbfbfd1fc68660297c31a8c68fd98ab06
1,094
java
Java
gedbrowser/src/main/java/org/schoellerfamily/gedbrowser/controller/exception/PersonNotFoundException.java
dickschoeller/gedbrowser
eb15573af066550c7c73b37aeb2b6a1a201ae8ca
[ "Apache-2.0" ]
1
2021-09-24T19:18:41.000Z
2021-09-24T19:18:41.000Z
gedbrowser/src/main/java/org/schoellerfamily/gedbrowser/controller/exception/PersonNotFoundException.java
dickschoeller/gedbrowser
eb15573af066550c7c73b37aeb2b6a1a201ae8ca
[ "Apache-2.0" ]
891
2016-02-22T02:21:32.000Z
2022-03-02T03:45:50.000Z
gedbrowser/src/main/java/org/schoellerfamily/gedbrowser/controller/exception/PersonNotFoundException.java
dickschoeller/gedbrowser
eb15573af066550c7c73b37aeb2b6a1a201ae8ca
[ "Apache-2.0" ]
2
2019-07-16T00:21:02.000Z
2022-02-19T04:04:04.000Z
31.257143
79
0.709324
9,124
package org.schoellerfamily.gedbrowser.controller.exception; import org.schoellerfamily.gedbrowser.renderer.RenderingContext; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * @author Dick Schoeller */ @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Person not found") public final class PersonNotFoundException extends ObjectNotFoundException { /** */ private static final long serialVersionUID = 3L; /** * @param message the message to display * @param personId the ID of the person not found * @param datasetName the name of the dataset being searched * @param context the rendering context */ public PersonNotFoundException(final String message, final String personId, final String datasetName, final RenderingContext context) { super(message, personId, datasetName, context); } /** * Get the ID of the person that was not found. * * @return the ID */ public String getPersonId() { return super.getId(); } }
3e1578798c876f6747e66738d3c7594967f7391f
18,171
java
Java
appfactory/org.wso2.developerstudio.appfactory.ui/src/org/wso2/developerstudio/appfactory/ui/views/PasswordDialog.java
knadikari/developer-studio
ed8b9e397bcf79e538c0f63397b3a8d8d7827660
[ "Apache-2.0" ]
null
null
null
appfactory/org.wso2.developerstudio.appfactory.ui/src/org/wso2/developerstudio/appfactory/ui/views/PasswordDialog.java
knadikari/developer-studio
ed8b9e397bcf79e538c0f63397b3a8d8d7827660
[ "Apache-2.0" ]
null
null
null
appfactory/org.wso2.developerstudio.appfactory.ui/src/org/wso2/developerstudio/appfactory/ui/views/PasswordDialog.java
knadikari/developer-studio
ed8b9e397bcf79e538c0f63397b3a8d8d7827660
[ "Apache-2.0" ]
1
2018-10-26T12:52:03.000Z
2018-10-26T12:52:03.000Z
32.218085
108
0.704254
9,125
/* * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.appfactory.ui.views; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.eclipse.equinox.security.storage.ISecurePreferences; import org.eclipse.equinox.security.storage.SecurePreferencesFactory; import org.eclipse.equinox.security.storage.StorageException; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ListDialog; import org.wso2.developerstudio.appfactory.core.authentication.Authenticator; import org.wso2.developerstudio.appfactory.core.authentication.UserPasswordCredentials; import org.wso2.developerstudio.appfactory.core.client.CloudAdminServiceClient; import org.wso2.developerstudio.appfactory.core.jag.api.JagApiProperties; import org.wso2.developerstudio.appfactory.core.model.ErrorType; import org.wso2.developerstudio.appfactory.ui.Activator; import org.wso2.developerstudio.appfactory.ui.actions.LoginAction; import org.wso2.developerstudio.appfactory.ui.utils.Messages; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.platform.core.utils.ResourceManager; import org.wso2.developerstudio.eclipse.platform.core.utils.SWTResourceManager; public class PasswordDialog extends Dialog { private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID); static final String DASHBOARD_VIEW_ID = "org.wso2.developerstudio.eclipse.dashboard"; private Text userText; private Text passwordText; private Text hostText; private String user; private String password; private String host; private boolean isSave; private boolean isOT; private Label error; private boolean isAppCloud; private UserPasswordCredentials credentials; private boolean fromDashboad; private ISecurePreferences gitTempNode; private Button btnCheckButton; private Button btnCloudCheckButton; private Button btnAFCheckButton; private ISecurePreferences preferences; private LoginAction action; private Label lblHost; private Label lblUser; /** * Create the dialog. * * @param parentShell * @param loginAction */ public PasswordDialog(Shell parentShell, LoginAction loginAction) { super(parentShell); setDefaultImage(ResourceManager.getPluginImage( "org.wso2.developerstudio.appfactory.ui", //$NON-NLS-1$ "icons/users.gif")); //$NON-NLS-1$ this.action = loginAction; this.isAppCloud = true; } protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.PasswordDialog_LoginDialog_title); newShell.setImage(ResourceManager.getPluginImage( "org.wso2.developerstudio.appfactory.ui", //$NON-NLS-1$ "icons/users.gif")); } /** * Create contents of the dialog. * * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); //container.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); GridLayout gl_container = new GridLayout(2, false); gl_container.marginRight = 10; gl_container.marginLeft = 10; gl_container.marginTop = 15; gl_container.marginBottom = 5; container.setLayout(gl_container); // Label lblNewLabel = new Label(container, SWT.NONE); // lblNewLabel.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); // lblNewLabel.setImage(ResourceManager.getPluginImage( // "org.wso2.developerstudio.appfactory.ui", //$NON-NLS-1$ // "icons/appfactory_logo.png")); //$NON-NLS-1$ // GridData gd_lblNewLabel = new GridData(SWT.LEFT, SWT.TOP, false, // true, 2, 1); // gd_lblNewLabel.widthHint = 509; // gd_lblNewLabel.heightHint = 38; // lblNewLabel.setLayoutData(gd_lblNewLabel); Label lblTmp =new Label(container, SWT.NONE); lblTmp.setText("Connect to :"); Composite composite = new Composite(container, SWT.NULL); composite.setLayout( new RowLayout()); composite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); btnCloudCheckButton = new Button(composite, SWT.RADIO); btnCloudCheckButton.setText("App Cloud"); btnCloudCheckButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button button = (Button) e.widget; isAppCloud = button.getSelection(); swapLookAndFeel(); } }); btnCloudCheckButton.setSelection(isAppCloud); btnAFCheckButton = new Button(composite, SWT.RADIO); btnAFCheckButton.setText("App Factory"); btnAFCheckButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button button = (Button) e.widget; isAppCloud = !button.getSelection(); swapLookAndFeel(); } }); btnAFCheckButton.setSelection(!isAppCloud); lblHost = new Label(container, SWT.NONE); lblHost.setText(Messages.PasswordDialog_URL); hostText = new Text(container, SWT.BORDER); hostText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); hostText.setText(host); lblUser = new Label(container, SWT.NONE); lblUser.setText(Messages.PasswordDialog_USER); userText = new Text(container, SWT.BORDER); userText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); userText.setText(user); Label lblNewLabel1 = new Label(container, SWT.NONE); GridData gd_lblNewLabel1= new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblNewLabel1.horizontalIndent = 1; lblNewLabel1.setLayoutData(gd_lblNewLabel1); lblNewLabel1.setText(Messages.PasswordDialog_Password); passwordText = new Text(container, SWT.PASSWORD|SWT.BORDER); passwordText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); passwordText.setText(password); new Label(container, SWT.NONE); error = new Label(container, SWT.NONE); GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); data.heightHint = 35; error.setLayoutData(data); error.setForeground(container.getDisplay().getSystemColor(SWT.COLOR_RED)); FocusAdapter adapter = new FocusAdapter() { @Override public void focusGained(FocusEvent e) { error.setText(""); super.focusGained(e); } }; hostText.addFocusListener(adapter); userText.addFocusListener(adapter); passwordText.addFocusListener(adapter); new Label(container, SWT.NONE); btnCheckButton = new Button(container, SWT.CHECK); btnCheckButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnCheckButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Button button = (Button) e.widget; if("".equals(userText.getText())||"".equals( passwordText.getText())){ error.setText("Username or Password cannot be empty !"); btnCheckButton.setSelection(false); }else{ if (button.getSelection()){ setSave(true); try { preferences = SecurePreferencesFactory.getDefault(); gitTempNode = preferences.node("Test"); gitTempNode.put("user","testUser", true);/*get secure store password*/ } catch (StorageException e1) { btnCheckButton.setSelection(false); log.error(e1); } }else{ setSave(false); } } } }); btnCheckButton.setText("Save connection details"); swapLookAndFeel(); return container; } private void swapLookAndFeel(){ if(isAppCloud){ hostText.setText(Messages.APP_CLOUD_URL); hostText.setEditable(false); lblHost.setText(Messages.PasswordDialog_Cloud_URL); lblUser.setText(Messages.PasswordDialog_Cloud_USER); }else{ hostText.setEditable(true); lblHost.setText(Messages.PasswordDialog_URL); lblUser.setText(Messages.PasswordDialog_USER); } } /** * Create contents of the button bar. * * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return new Point(539, 300); } @Override protected void okPressed() { user = userText.getText(); /* if((isOT)&&(user!=null)&&(!user.isEmpty())){ String[] temp = user.split("@"); user = temp[0]+".."+temp[1]+"@wso2.org"; }*/ password = passwordText.getText(); host =hostText.getText().trim(); if(!host.startsWith("http")||!host.startsWith("https")){ //$NON-NLS-1$ //$NON-NLS-2$ host = "https://"+host; //$NON-NLS-1$ } if("".equals(getUser())||"".equals(getPassword())){ error.setText("Username or Password cannot be empty !"); return; } action.setUsername(getUser()); action.setPassword(getPassword()); action.setLoginUrl(getHost()); action.setSave(isSave()); action.setAppCloud(isAppCloud()); Authenticator.getInstance().setAppCloud(isAppCloud()); if(login()){ try { if (isSave) { gitTempNode.removeNode(); ISecurePreferences preferences = SecurePreferencesFactory.getDefault(); ISecurePreferences node = preferences.node("GIT"); node.put("user",getUser(), true); node.put("password",Authenticator.getInstance().getCredentials().getPassword(), true); } } catch (StorageException e) { error.setText("Failed to save Credentials in secure storage"); log.error(e); } super.okPressed(); }else { ErrorType errorcode = Authenticator.getInstance().getErrorcode(); switch (errorcode) { case INVALID: error.setText("Invalid username or password"); break; case FAILD: error.setText(Authenticator.getInstance().getErrormsg()); break; case ERROR: error.setText("Connection failed"); break; } } } private boolean login() { boolean val = true; UserPasswordCredentials oldCredentials = null; String oldServerURL = null; setCursorBusy(); try { if(Authenticator.getInstance().isLoaded()){ oldCredentials = Authenticator.getInstance().getCredentials(); oldServerURL = Authenticator.getInstance().getServerURL(); } credentials = new UserPasswordCredentials(getUser(),getPassword()); if(isAppCloud()) { Map<String, String> tenants = CloudAdminServiceClient .getTenantDomains(new UserPasswordCredentials(getUser(), getPassword())); if(tenants.size()==0){ error.setText(Messages.APP_CLOUD_ZERO_TENANTS_WARNING); val = false; } else if(tenants.size()==1){ Authenticator.getInstance().setSelectedTenant(tenants.entrySet().iterator().next().getValue()); val = Authenticator.getInstance().Authenticate(JagApiProperties.getLoginUrl(), credentials); }else{ List<String[]> tenantList = new ArrayList<String[]>(); for(Entry<String, String> tenant:tenants.entrySet()){ tenantList.add(new String[]{tenant.getKey(), tenant.getValue()}); } ListDialog dialog = getTenantSeclectionDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell()); dialog.setInput(tenantList); String selectedTenant = getSelectedTenant(dialog); if(selectedTenant!=null) { Authenticator.getInstance().setSelectedTenant(selectedTenant); val = Authenticator.getInstance().Authenticate(JagApiProperties.getLoginUrl(), credentials); }else{ val = false; } } }else{ val = Authenticator.getInstance().Authenticate(JagApiProperties.getLoginUrl(), credentials); } if(val && isfromDashboad()){ Authenticator.getInstance().setFromDashboad(isfromDashboad()); } resetCredintials(val, oldCredentials, oldServerURL); } catch (Exception e) { log.error("Login failed", e); error.setText("Login failed."); setCursorNormal(); resetCredintials(val, oldCredentials, oldServerURL); return false; } setCursorNormal(); return val; } private String getSelectedTenant(ListDialog dialog) { int feedback = dialog.open(); if (feedback == Window.OK) { Object[] result = dialog.getResult(); for (int i = 0; i < result.length; i++) { String[] ss = (String[]) result[i]; return ss[1]; } } else if (feedback == Window.CANCEL) { error.setText(Messages.APP_CLOUD_ORG_NOT_SELECT_ERROR); } return null; } private ListDialog getTenantSeclectionDialog(Shell shell){ ListDialog dialog = new ListDialog(shell); dialog.setContentProvider(new ArrayContentProvider()); dialog.setTitle(Messages.TenantSelectionDialog_Title); dialog.setMessage(Messages.TenantSelectionDialog_Title_2); dialog.setLabelProvider(new ArrayLabelProvider()); return dialog; } private static class ArrayLabelProvider extends LabelProvider implements ITableLabelProvider { public String getText(Object element) { return ((String[]) element)[0].toString(); } @Override public Image getColumnImage(Object element, int columnIndex) { return null; } @Override public String getColumnText(Object element, int columnIndex) { String[] ss = (String[]) element; return ss[columnIndex]; } } private void resetCredintials(boolean val, UserPasswordCredentials oldCredentials, String oldServerURL) { if(!val){ if(Authenticator.getInstance().isLoaded()){ Authenticator.getInstance().setCredentials(oldCredentials); Authenticator.getInstance().setServerURL(oldServerURL); }else{ Authenticator.getInstance().setCredentials(null); } } } private void hideDashboards(){ try { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); List<IEditorReference> openEditors = new ArrayList<IEditorReference>(); IEditorReference[] editorReferences = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage().getEditorReferences(); for (IEditorReference iEditorReference : editorReferences) { if (DASHBOARD_VIEW_ID.equals(iEditorReference.getId())) { openEditors.add(iEditorReference); } } if (openEditors.size() > 0) { page.closeEditors(openEditors.toArray(new IEditorReference[] {}), false); } } catch (Exception e) { /* safe to ignore */ } } private void setCursorNormal() { try { Display.getCurrent().getActiveShell().setCursor((new Cursor(Display.getCurrent(), SWT.CURSOR_ARROW))); } catch (Throwable e) { /*safe to ignore*/ } } private void setCursorBusy() { try { Display.getCurrent().getActiveShell().setCursor((new Cursor(Display.getCurrent(), SWT.CURSOR_WAIT))); } catch (Throwable e) { /*safe to ignore*/ } } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public boolean isSave() { return isSave; } public void setSave(boolean isSave) { this.isSave = isSave; } public boolean isOT() { return isOT; } public void setOT(boolean isOT) { this.isOT = isOT; } public boolean isfromDashboad() { return fromDashboad; } public void setIsfromDashboad(boolean isfromDashboad) { this.fromDashboad = isfromDashboad; } public boolean isAppCloud() { return isAppCloud; } public void setAppCloud(boolean isAppCloud) { this.isAppCloud = isAppCloud; } }
3e1578a3e57f321237c87566c296294b88a052f3
3,435
java
Java
modules/flowable-json-converter/src/test/java/org/flowable/editor/language/BoundaryEventConverterTest.java
gaoyida/flowable-engine
b6875949741c9807da6d2c34121bc4dee1e63b3f
[ "Apache-2.0" ]
3
2019-05-07T02:58:38.000Z
2021-03-12T05:50:45.000Z
modules/flowable-json-converter/src/test/java/org/flowable/editor/language/BoundaryEventConverterTest.java
gaoyida/flowable-engine
b6875949741c9807da6d2c34121bc4dee1e63b3f
[ "Apache-2.0" ]
6
2018-10-16T06:04:06.000Z
2021-12-08T05:59:47.000Z
modules/flowable-json-converter/src/test/java/org/flowable/editor/language/BoundaryEventConverterTest.java
gaoyida/flowable-engine
b6875949741c9807da6d2c34121bc4dee1e63b3f
[ "Apache-2.0" ]
4
2018-12-17T10:44:45.000Z
2020-05-25T11:36:33.000Z
45.197368
115
0.755459
9,126
/* 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.flowable.editor.language; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.flowable.bpmn.model.BoundaryEvent; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.ErrorEventDefinition; import org.flowable.bpmn.model.MessageEventDefinition; import org.flowable.bpmn.model.SignalEventDefinition; import org.flowable.bpmn.model.TimerEventDefinition; import org.junit.Test; public class BoundaryEventConverterTest extends AbstractConverterTest { @Test public void convertJsonToModel() throws Exception { BpmnModel bpmnModel = readJsonFile(); validateModel(bpmnModel); } @Test public void doubleConversionValidation() throws Exception { BpmnModel bpmnModel = readJsonFile(); bpmnModel = convertToJsonAndBack(bpmnModel); validateModel(bpmnModel); } @Override protected String getResource() { return "test.boundaryeventmodel.json"; } private void validateModel(BpmnModel model) { BoundaryEvent errorElement = (BoundaryEvent) model.getMainProcess().getFlowElement("errorEvent", true); ErrorEventDefinition errorEvent = (ErrorEventDefinition) extractEventDefinition(errorElement); assertTrue(errorElement.isCancelActivity()); // always true assertEquals("errorRef", errorEvent.getErrorCode()); assertEquals("sid-F21E9F4D-EA19-44DF-B1D3-14663A809CAE", errorElement.getAttachedToRefId()); BoundaryEvent signalElement = (BoundaryEvent) model.getMainProcess().getFlowElement("signalEvent", true); SignalEventDefinition signalEvent = (SignalEventDefinition) extractEventDefinition(signalElement); assertFalse(signalElement.isCancelActivity()); assertEquals("signalRef", signalEvent.getSignalRef()); assertEquals("sid-F21E9F4D-EA19-44DF-B1D3-14663A809CAE", errorElement.getAttachedToRefId()); BoundaryEvent messageElement = (BoundaryEvent) model.getMainProcess().getFlowElement("messageEvent", true); MessageEventDefinition messageEvent = (MessageEventDefinition) extractEventDefinition(messageElement); assertFalse(messageElement.isCancelActivity()); assertEquals("messageRef", messageEvent.getMessageRef()); assertEquals("sid-F21E9F4D-EA19-44DF-B1D3-14663A809CAE", errorElement.getAttachedToRefId()); BoundaryEvent timerElement = (BoundaryEvent) model.getMainProcess().getFlowElement("timerEvent", true); TimerEventDefinition timerEvent = (TimerEventDefinition) extractEventDefinition(timerElement); assertFalse(timerElement.isCancelActivity()); assertEquals("PT5M", timerEvent.getTimeDuration()); assertEquals("sid-F21E9F4D-EA19-44DF-B1D3-14663A809CAE", errorElement.getAttachedToRefId()); } }
3e1578e9596d45b4010fe8fca01090a513a4d693
2,186
java
Java
src/main/java/com/swiftmq/amqp/v091/generated/basic/CancelOk.java
iitsoftware/swiftmq-client
1222f3cccee710081fdc1c9131b925b27253d79f
[ "Apache-2.0" ]
4
2019-11-01T23:52:01.000Z
2022-02-01T06:50:39.000Z
src/main/java/com/swiftmq/amqp/v091/generated/basic/CancelOk.java
iitsoftware/swiftmq-client
1222f3cccee710081fdc1c9131b925b27253d79f
[ "Apache-2.0" ]
9
2019-09-24T08:08:48.000Z
2021-08-05T14:35:50.000Z
src/main/java/com/swiftmq/amqp/v091/generated/basic/CancelOk.java
iitsoftware/swiftmq-client
1222f3cccee710081fdc1c9131b925b27253d79f
[ "Apache-2.0" ]
null
null
null
27.670886
84
0.673833
9,127
/* * Copyright 2019 IIT Software GmbH * * IIT Software GmbH licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.swiftmq.amqp.v091.generated.basic; /** * AMQP-Protocol Version 091 * Automatically generated, don't change! * Generation Date: Thu Apr 12 12:18:24 CEST 2012 * (c) 2012, IIT Software GmbH, Bremen/Germany * All Rights Reserved **/ import com.swiftmq.amqp.v091.io.BitSupportDataInput; import com.swiftmq.amqp.v091.io.BitSupportDataOutput; import com.swiftmq.amqp.v091.types.Coder; import java.io.IOException; public class CancelOk extends BasicMethod { String consumerTag; public CancelOk() { _classId = 60; _methodId = 31; } public void accept(BasicMethodVisitor visitor) { visitor.visit(this); } public String getConsumerTag() { return consumerTag; } public void setConsumerTag(String consumerTag) { this.consumerTag = consumerTag; } protected void readBody(BitSupportDataInput in) throws IOException { consumerTag = Coder.readShortString(in); } protected void writeBody(BitSupportDataOutput out) throws IOException { Coder.writeShortString(consumerTag, out); out.bitFlush(); } private String getDisplayString() { boolean _first = true; StringBuffer b = new StringBuffer(" "); if (!_first) b.append(", "); else _first = false; b.append("consumerTag="); b.append(consumerTag); return b.toString(); } public String toString() { return "[CancelOk " + super.toString() + getDisplayString() + "]"; } }
3e157a2018c99d65302c2c55abac7c175b1f6957
7,878
java
Java
easy-spring-practice/07-init-destroy-bean/src/main/java/cn/duktig/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
duktig666/simple-spring
df973ae00b3b57447ef78c87bc521d434258ff39
[ "Apache-2.0" ]
2
2021-09-25T12:01:47.000Z
2021-09-26T03:02:00.000Z
easy-spring-practice/07-init-destroy-bean/src/main/java/cn/duktig/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
duktig666/simple-spring
df973ae00b3b57447ef78c87bc521d434258ff39
[ "Apache-2.0" ]
null
null
null
easy-spring-practice/07-init-destroy-bean/src/main/java/cn/duktig/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
duktig666/simple-spring
df973ae00b3b57447ef78c87bc521d434258ff39
[ "Apache-2.0" ]
null
null
null
36.985915
124
0.651054
9,128
package cn.duktig.springframework.beans.factory.support; import cn.duktig.springframework.beans.BeansException; import cn.duktig.springframework.beans.PropertyValue; import cn.duktig.springframework.beans.PropertyValues; import cn.duktig.springframework.beans.factory.DisposableBean; import cn.duktig.springframework.beans.factory.InitializingBean; import cn.duktig.springframework.beans.factory.config.AutowireCapableBeanFactory; import cn.duktig.springframework.beans.factory.config.BeanDefinition; import cn.duktig.springframework.beans.factory.config.BeanPostProcessor; import cn.duktig.springframework.beans.factory.config.BeanReference; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.StrUtil; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * description:可自动装配的抽象工厂 * * @author RenShiWei * Date: 2021/8/25 14:28 **/ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory { /** 现在默认使用的Cglib的方式,正确是根据不同的情况自动进行选择 */ private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy(); /** * 创建bean对象 * * @param beanName bean名称 * @param beanDefinition bean定义 * @param args 构造器参数 * @return 创建后的bean对象 * @throws BeansException bean异常 */ @Override protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) { Object bean = null; try { //反射 创建bean对象 bean = this.createBeanInstance(beanDefinition, beanName, args); // 给 Bean 填充属性 this.applyPropertyValues(beanName, bean, beanDefinition); // 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置 bean = initializeBean(beanName, bean, beanDefinition); } catch (Exception e) { throw new BeansException("Instantiation of bean failed", e); } // 注册实现了 DisposableBean 接口的 Bean 对象 (创建Bean时注册销毁方法对象) registerDisposableBeanIfNecessary(beanName, bean, beanDefinition); addSingleton(beanName, bean); return bean; } /** * 如果需要注册需要销毁的bean * * @param beanName / * @param bean / * @param beanDefinition / */ protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) { if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) { this.registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition)); } } /** * 创建bean对象实例(支持有参构造器创建) * * @param beanDefinition bean定义 * @param beanName bean名称 * @param args 构造器参数 * @return bean对象实例 */ protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) { Constructor<?> constructorToUse = null; Class<?> beanClass = beanDefinition.getBeanClass(); Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors(); //? 只判断参数个数一致,能确定一个构造器吗? 万一类型不同 for (Constructor<?> ctor : declaredConstructors) { if (null != args && ctor.getParameterTypes().length == args.length) { constructorToUse = ctor; break; } } //使用分配好的策略进行创建对象实例 return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args); } /** * Bean 属性填充 */ protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) { try { PropertyValues propertyValues = beanDefinition.getPropertyValues(); for (PropertyValue propertyValue : propertyValues.getPropertyValues()) { String name = propertyValue.getName(); Object value = propertyValue.getValue(); if (value instanceof BeanReference) { // A 依赖 B,获取 B 的实例化 BeanReference beanReference = (BeanReference) value; value = getBean(beanReference.getBeanName()); } // 属性填充 BeanUtil.setFieldValue(bean, name, value); } } catch (Exception e) { throw new BeansException("Error setting property values:" + beanName); } } public InstantiationStrategy getInstantiationStrategy() { return instantiationStrategy; } public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) { this.instantiationStrategy = instantiationStrategy; } /** * 实例化bean的操作 * * @param beanName bean名称 * @param bean bean对象 * @param beanDefinition bean定义 * @return 实例化完成后的bean对象 */ private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) throws Exception { // 1. 执行 BeanPostProcessor Before 处理 Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName); // 执行 Bean 对象的初始化方法 try { invokeInitMethods(beanName, wrappedBean, beanDefinition); } catch (Exception e) { throw new BeansException("Invocation of init method of bean[" + beanName + "] failed", e); } // 2. 执行 BeanPostProcessor After 处理 wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName); return wrappedBean; } private void invokeInitMethods(String beanName, Object bean, BeanDefinition beanDefinition) throws Exception { // 1. 实现接口 InitializingBean if (bean instanceof InitializingBean) { ((InitializingBean) bean).afterPropertiesSet(); } // 2. 配置信息 init-method {判断是为了避免二次执行销毁} String initMethodName = beanDefinition.getInitMethodName(); if (StrUtil.isNotEmpty(initMethodName)) { Method initMethod = beanDefinition.getBeanClass().getMethod(initMethodName); if (null == initMethod) { throw new BeansException("Could not find an init method named '" + initMethodName + "' on bean with " + "name '" + beanName + "'"); } initMethod.invoke(bean); } } /** * 执行 BeanPostProcessors 接口实现类的 postProcessBeforeInitialization 方法 * <p> * 实现自 AutowireCapableBeanFactory 接口 * * @param existingBean 已经存在的Bean对象 * @param beanName bean名称 * @return 实例化前的bean对象 * @throws BeansException / */ @Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName); if (null == current) { return result; } result = current; } return result; } /** * 执行 BeanPostProcessors 接口实现类的 postProcessorsAfterInitialization 方法 * <p> * 实现自 AutowireCapableBeanFactory 接口 * * @param existingBean 已经存在的Bean对象 * @param beanName bean名称 * @return 实例化后的bean对象 * @throws BeansException / */ @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName); if (null == current) { return result; } result = current; } return result; } }
3e157b1cc1f8a3e835fd62a6f22926756bf5b732
718
java
Java
src/main/java/com/stephenboyer/sbhome2/SecurityConfig.java
steveboyer/SBHome2
323491eb68ab88a39380965f599f951307315212
[ "MIT" ]
null
null
null
src/main/java/com/stephenboyer/sbhome2/SecurityConfig.java
steveboyer/SBHome2
323491eb68ab88a39380965f599f951307315212
[ "MIT" ]
null
null
null
src/main/java/com/stephenboyer/sbhome2/SecurityConfig.java
steveboyer/SBHome2
323491eb68ab88a39380965f599f951307315212
[ "MIT" ]
null
null
null
37.789474
102
0.827298
9,129
package com.stephenboyer.sbhome2; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import javax.inject.Inject; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Inject private SecurityProperties securityProperties; @Override protected void configure(HttpSecurity http) throws Exception { // if (securityProperties.isRequireSsl()) http.requiresChannel().anyRequest().requiresSecure(); } }
3e157b3a4d1c249c95e7d50257dcd34847621900
3,576
java
Java
buildSrc/src/main/java/com/uber/okbuck/extension/ExternalDependenciesExtension.java
msridhar/okbuck
b7c325657c1f797bb28a71cf4ee7e9c9533cdb21
[ "Apache-2.0" ]
null
null
null
buildSrc/src/main/java/com/uber/okbuck/extension/ExternalDependenciesExtension.java
msridhar/okbuck
b7c325657c1f797bb28a71cf4ee7e9c9533cdb21
[ "Apache-2.0" ]
null
null
null
buildSrc/src/main/java/com/uber/okbuck/extension/ExternalDependenciesExtension.java
msridhar/okbuck
b7c325657c1f797bb28a71cf4ee7e9c9533cdb21
[ "Apache-2.0" ]
null
null
null
29.073171
99
0.737975
9,130
package com.uber.okbuck.extension; import com.google.common.collect.ImmutableSet; import com.uber.okbuck.core.dependency.VersionlessDependency; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.gradle.api.tasks.Input; public class ExternalDependenciesExtension { /** Specifies the folder where all external dependency rules gets generated. */ @Input private String cache = ".okbuck/ext"; /** Specifies whether the external dependencies should be downloaded by buck or not. */ @Input private boolean downloadInBuck = true; /** Specifies what resolution action to use for external dependencies. */ @Input private ResolutionAction resolutionAction = ResolutionAction.ALL; /** Specifies whether to enable exported_deps for external dependencies or not. */ @Input private boolean enableExportedDeps = false; @Input private Set<String> autoValueConfigurations = new HashSet<>(); /** * Stores the dependencies which are allowed to have more than 1 version. This is needed for few * dependencies like robolectric runtime deps. */ @Input private List<String> allowAllVersions = Collections.singletonList("org.robolectric:android-all"); /** * Stores the dependency versions to be used for dynamic notations that have , or + in their * versions */ @Input private Map<String, String> dynamicDependencyVersionMap = new HashMap<>(); /** * Stores the dynamic dependencies to ignore if they are resolved with other gradle resolution * mechanisms */ @Input private Set<String> dynamicDependenciesToIgnore = new HashSet<>(); @Nullable private Set<VersionlessDependency> allowAllVersionsSet; public ExternalDependenciesExtension() {} private synchronized Set<VersionlessDependency> getAllowAllVersionsSet() { if (allowAllVersionsSet == null) { allowAllVersionsSet = allowAllVersions .stream() .map(VersionlessDependency::fromMavenCoords) .collect(ImmutableSet.toImmutableSet()); } return allowAllVersionsSet; } public boolean useLatest() { return resolutionAction.equals(ResolutionAction.LATEST); } public boolean useLatest(VersionlessDependency versionlessDependency) { if (getAllowAllVersionsSet().contains(versionlessDependency)) { return false; } return useLatest(); } public boolean useSingle() { return resolutionAction.equals(ResolutionAction.SINGLE); } public boolean useSingle(VersionlessDependency versionlessDependency) { if (getAllowAllVersionsSet().contains(versionlessDependency)) { return false; } return useSingle(); } public boolean versionlessEnabled() { return useLatest() || useSingle(); } public boolean isVersioned(VersionlessDependency versionlessDependency) { if (getAllowAllVersionsSet().contains(versionlessDependency)) { return true; } return !versionlessEnabled(); } public String getCache() { return cache; } public boolean shouldDownloadInBuck() { return downloadInBuck; } public boolean exportedDepsEnabled() { return enableExportedDeps; } public Set<String> getAutoValueConfigurations() { return autoValueConfigurations; } public Map<String, String> getDynamicDependencyVersionMap() { return dynamicDependencyVersionMap; } public Set<String> getDynamicDependenciesToIgnore() { return dynamicDependenciesToIgnore; } }
3e157d3e70adf014e660216dd30a7dbfd51c53b8
2,521
java
Java
test/resources/org/apache/pig/test/RegisteredJarVisibilityLoader.java
mateiz/spork
7976eea669156fa226aa80d7e0f5e9be6312267e
[ "Apache-2.0" ]
4
2015-04-02T15:05:41.000Z
2020-07-06T20:51:31.000Z
test/resources/org/apache/pig/test/RegisteredJarVisibilityLoader.java
mateiz/spork
7976eea669156fa226aa80d7e0f5e9be6312267e
[ "Apache-2.0" ]
null
null
null
test/resources/org/apache/pig/test/RegisteredJarVisibilityLoader.java
mateiz/spork
7976eea669156fa226aa80d7e0f5e9be6312267e
[ "Apache-2.0" ]
2
2017-03-20T08:36:55.000Z
2020-07-06T20:51:32.000Z
45.836364
102
0.744942
9,131
/* * 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.pig.test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.mapreduce.Job; import org.apache.pig.builtin.PigStorage; import org.apache.pig.impl.util.UDFContext; import java.io.IOException; import java.util.Properties; /** * Please see {@link TestRegisteredJarVisibility} for information about this class. */ public class RegisteredJarVisibilityLoader extends PigStorage { private static final Log LOG = LogFactory.getLog(RegisteredJarVisibilityLoader.class); private static final String REGISTERED_JAR_VISIBILITY_SCHEMA = "registered.jar.visibility.schema"; @Override public void setLocation(String location, Job job) throws IOException { UDFContext udfContext = UDFContext.getUDFContext(); Properties properties = udfContext.getUDFProperties(RegisteredJarVisibilityLoader.class); if (!properties.containsKey(REGISTERED_JAR_VISIBILITY_SCHEMA)) { LOG.info("Storing " + RegisteredJarVisibilitySchema.class.getName() + " in UDFContext."); properties.put(REGISTERED_JAR_VISIBILITY_SCHEMA, new RegisteredJarVisibilitySchema()); LOG.info("Stored " + RegisteredJarVisibilitySchema.class.getName() + " in UDFContext."); } else { LOG.info("Retrieving " + REGISTERED_JAR_VISIBILITY_SCHEMA + " from UDFContext."); RegisteredJarVisibilitySchema registeredJarVisibilitySchema = (RegisteredJarVisibilitySchema) properties.get(REGISTERED_JAR_VISIBILITY_SCHEMA); LOG.info("Retrieved " + REGISTERED_JAR_VISIBILITY_SCHEMA + " from UDFContext."); } super.setLocation(location, job); } }
3e157d54c50bbf82374e00a6e893d453484a09a1
1,621
java
Java
src/com/isode/stroke/parser/payloadparsers/PubSubEventRedirectParser.java
senagbe/stroke
9b518dcdd98d694a4464895fce17a3c7a8caf569
[ "BSD-3-Clause" ]
9
2015-06-01T08:57:02.000Z
2021-07-01T19:33:28.000Z
src/com/isode/stroke/parser/payloadparsers/PubSubEventRedirectParser.java
senagbe/stroke
9b518dcdd98d694a4464895fce17a3c7a8caf569
[ "BSD-3-Clause" ]
7
2015-03-11T17:27:13.000Z
2019-01-06T05:30:26.000Z
src/com/isode/stroke/parser/payloadparsers/PubSubEventRedirectParser.java
senagbe/stroke
9b518dcdd98d694a4464895fce17a3c7a8caf569
[ "BSD-3-Clause" ]
12
2015-03-09T20:59:14.000Z
2021-08-13T07:06:18.000Z
25.328125
90
0.762492
9,132
/* * Copyright (c) 2014, Isode Limited, London, England. * All rights reserved. */ /* * Copyright (c) 2014, Remko Tronçon. * All rights reserved. */ package com.isode.stroke.parser.payloadparsers; import com.isode.stroke.parser.AttributeMap; import com.isode.stroke.parser.GenericPayloadParser; import com.isode.stroke.parser.PayloadParser; import com.isode.stroke.parser.PayloadParserFactoryCollection; import com.isode.stroke.elements.PubSubEventRedirect; public class PubSubEventRedirectParser extends GenericPayloadParser<PubSubEventRedirect> { public PubSubEventRedirectParser(PayloadParserFactoryCollection parsers) { super(new PubSubEventRedirect()); parsers_ = parsers; level_ = 0; } public void handleStartElement(String element, String ns, AttributeMap attributes) { if (level_ == 0) { String attributeValue; attributeValue = attributes.getAttribute("uri"); if (!attributeValue.isEmpty()) { getPayloadInternal().setURI(attributeValue); } } if (level_ >= 1 && currentPayloadParser_ != null) { currentPayloadParser_.handleStartElement(element, ns, attributes); } ++level_; } public void handleEndElement(String element, String ns) { --level_; if (currentPayloadParser_ != null) { if (level_ >= 1) { currentPayloadParser_.handleEndElement(element, ns); } if (level_ != 1) { return; } currentPayloadParser_ = null; } } public void handleCharacterData(String data) { if (level_ > 1 && currentPayloadParser_ != null) { currentPayloadParser_.handleCharacterData(data); } } PayloadParserFactoryCollection parsers_; int level_; PayloadParser currentPayloadParser_; }
3e157da7c8dc0534a54b5eff604c503f9bef80b3
81,176
java
Java
src/main/java/ru/gov/zakupki/oos/common/_1/ParticipantType.java
simokhov/schemas44
59cff63363b36c55e188a820c0623ff3d28f8c50
[ "MIT" ]
null
null
null
src/main/java/ru/gov/zakupki/oos/common/_1/ParticipantType.java
simokhov/schemas44
59cff63363b36c55e188a820c0623ff3d28f8c50
[ "MIT" ]
null
null
null
src/main/java/ru/gov/zakupki/oos/common/_1/ParticipantType.java
simokhov/schemas44
59cff63363b36c55e188a820c0623ff3d28f8c50
[ "MIT" ]
null
null
null
34.136249
137
0.488198
9,133
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.07.02 at 03:35:23 PM MSK // package ru.gov.zakupki.oos.common._1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import ru.gov.zakupki.oos.base._1.OKOPFRef; import ru.gov.zakupki.oos.base._1.OKSMRef; /** * Тип: Поставщик для протоколов электронных процедур * * <p>Java class for participantType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="participantType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice> * &lt;element name="legalEntityRFInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="fullName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="shortName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="firmName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innEntityType"/> * &lt;element name="KPP" type="{http://zakupki.gov.ru/oos/base/1}kppType"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;element name="ogrn" type="{http://zakupki.gov.ru/oos/base/1}ogrnCodeType" minOccurs="0"/> * &lt;element name="legalForm" type="{http://zakupki.gov.ru/oos/base/1}OKOPFRef" minOccurs="0"/> * &lt;element name="contactInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactPersonInfo" type="{http://zakupki.gov.ru/oos/common/1}personType" minOccurs="0"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="legalEntityForeignStateInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="fullName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="shortName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="firmName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="fullNameLat" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="taxPayerCode" type="{http://zakupki.gov.ru/oos/base/1}taxPayerCode" minOccurs="0"/> * &lt;element name="ogrn" type="{http://zakupki.gov.ru/oos/base/1}ogrnCodeType" minOccurs="0"/> * &lt;element name="legalForm" type="{http://zakupki.gov.ru/oos/base/1}OKOPFRef" minOccurs="0"/> * &lt;element name="registerInRFTaxBodiesInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innEntityType"/> * &lt;element name="KPP" type="{http://zakupki.gov.ru/oos/base/1}kppType" minOccurs="0"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRegCountryInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="country" type="{http://zakupki.gov.ru/oos/base/1}OKSMRef"/> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRFInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="individualPersonRFInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="nameInfo" type="{http://zakupki.gov.ru/oos/common/1}personType"/> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innIndividualType"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;element name="isIP" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="individualPersonForeignStateInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="nameInfo" type="{http://zakupki.gov.ru/oos/common/1}personType"/> * &lt;element name="nameLatInfo" type="{http://zakupki.gov.ru/oos/common/1}personType" minOccurs="0"/> * &lt;element name="taxPayerCode" type="{http://zakupki.gov.ru/oos/base/1}taxPayerCode"/> * &lt;element name="registerInRFTaxBodiesInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innIndividualType"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRegCountryInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="country" type="{http://zakupki.gov.ru/oos/base/1}OKSMRef" minOccurs="0"/> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRFInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/choice> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "participantType", propOrder = { "legalEntityRFInfo", "legalEntityForeignStateInfo", "individualPersonRFInfo", "individualPersonForeignStateInfo" }) public class ParticipantType { protected ParticipantType.LegalEntityRFInfo legalEntityRFInfo; protected ParticipantType.LegalEntityForeignStateInfo legalEntityForeignStateInfo; protected ParticipantType.IndividualPersonRFInfo individualPersonRFInfo; protected ParticipantType.IndividualPersonForeignStateInfo individualPersonForeignStateInfo; /** * Gets the value of the legalEntityRFInfo property. * * @return * possible object is * {@link ParticipantType.LegalEntityRFInfo } * */ public ParticipantType.LegalEntityRFInfo getLegalEntityRFInfo() { return legalEntityRFInfo; } /** * Sets the value of the legalEntityRFInfo property. * * @param value * allowed object is * {@link ParticipantType.LegalEntityRFInfo } * */ public void setLegalEntityRFInfo(ParticipantType.LegalEntityRFInfo value) { this.legalEntityRFInfo = value; } /** * Gets the value of the legalEntityForeignStateInfo property. * * @return * possible object is * {@link ParticipantType.LegalEntityForeignStateInfo } * */ public ParticipantType.LegalEntityForeignStateInfo getLegalEntityForeignStateInfo() { return legalEntityForeignStateInfo; } /** * Sets the value of the legalEntityForeignStateInfo property. * * @param value * allowed object is * {@link ParticipantType.LegalEntityForeignStateInfo } * */ public void setLegalEntityForeignStateInfo(ParticipantType.LegalEntityForeignStateInfo value) { this.legalEntityForeignStateInfo = value; } /** * Gets the value of the individualPersonRFInfo property. * * @return * possible object is * {@link ParticipantType.IndividualPersonRFInfo } * */ public ParticipantType.IndividualPersonRFInfo getIndividualPersonRFInfo() { return individualPersonRFInfo; } /** * Sets the value of the individualPersonRFInfo property. * * @param value * allowed object is * {@link ParticipantType.IndividualPersonRFInfo } * */ public void setIndividualPersonRFInfo(ParticipantType.IndividualPersonRFInfo value) { this.individualPersonRFInfo = value; } /** * Gets the value of the individualPersonForeignStateInfo property. * * @return * possible object is * {@link ParticipantType.IndividualPersonForeignStateInfo } * */ public ParticipantType.IndividualPersonForeignStateInfo getIndividualPersonForeignStateInfo() { return individualPersonForeignStateInfo; } /** * Sets the value of the individualPersonForeignStateInfo property. * * @param value * allowed object is * {@link ParticipantType.IndividualPersonForeignStateInfo } * */ public void setIndividualPersonForeignStateInfo(ParticipantType.IndividualPersonForeignStateInfo value) { this.individualPersonForeignStateInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="nameInfo" type="{http://zakupki.gov.ru/oos/common/1}personType"/> * &lt;element name="nameLatInfo" type="{http://zakupki.gov.ru/oos/common/1}personType" minOccurs="0"/> * &lt;element name="taxPayerCode" type="{http://zakupki.gov.ru/oos/base/1}taxPayerCode"/> * &lt;element name="registerInRFTaxBodiesInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innIndividualType"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRegCountryInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="country" type="{http://zakupki.gov.ru/oos/base/1}OKSMRef" minOccurs="0"/> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRFInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "nameInfo", "nameLatInfo", "taxPayerCode", "registerInRFTaxBodiesInfo", "placeOfStayInRegCountryInfo", "placeOfStayInRFInfo" }) public static class IndividualPersonForeignStateInfo { @XmlElement(required = true) protected PersonType nameInfo; protected PersonType nameLatInfo; @XmlElement(required = true) protected String taxPayerCode; protected ParticipantType.IndividualPersonForeignStateInfo.RegisterInRFTaxBodiesInfo registerInRFTaxBodiesInfo; @XmlElement(required = true) protected ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRegCountryInfo placeOfStayInRegCountryInfo; protected ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRFInfo placeOfStayInRFInfo; /** * Gets the value of the nameInfo property. * * @return * possible object is * {@link PersonType } * */ public PersonType getNameInfo() { return nameInfo; } /** * Sets the value of the nameInfo property. * * @param value * allowed object is * {@link PersonType } * */ public void setNameInfo(PersonType value) { this.nameInfo = value; } /** * Gets the value of the nameLatInfo property. * * @return * possible object is * {@link PersonType } * */ public PersonType getNameLatInfo() { return nameLatInfo; } /** * Sets the value of the nameLatInfo property. * * @param value * allowed object is * {@link PersonType } * */ public void setNameLatInfo(PersonType value) { this.nameLatInfo = value; } /** * Gets the value of the taxPayerCode property. * * @return * possible object is * {@link String } * */ public String getTaxPayerCode() { return taxPayerCode; } /** * Sets the value of the taxPayerCode property. * * @param value * allowed object is * {@link String } * */ public void setTaxPayerCode(String value) { this.taxPayerCode = value; } /** * Gets the value of the registerInRFTaxBodiesInfo property. * * @return * possible object is * {@link ParticipantType.IndividualPersonForeignStateInfo.RegisterInRFTaxBodiesInfo } * */ public ParticipantType.IndividualPersonForeignStateInfo.RegisterInRFTaxBodiesInfo getRegisterInRFTaxBodiesInfo() { return registerInRFTaxBodiesInfo; } /** * Sets the value of the registerInRFTaxBodiesInfo property. * * @param value * allowed object is * {@link ParticipantType.IndividualPersonForeignStateInfo.RegisterInRFTaxBodiesInfo } * */ public void setRegisterInRFTaxBodiesInfo(ParticipantType.IndividualPersonForeignStateInfo.RegisterInRFTaxBodiesInfo value) { this.registerInRFTaxBodiesInfo = value; } /** * Gets the value of the placeOfStayInRegCountryInfo property. * * @return * possible object is * {@link ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRegCountryInfo } * */ public ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRegCountryInfo getPlaceOfStayInRegCountryInfo() { return placeOfStayInRegCountryInfo; } /** * Sets the value of the placeOfStayInRegCountryInfo property. * * @param value * allowed object is * {@link ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRegCountryInfo } * */ public void setPlaceOfStayInRegCountryInfo(ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRegCountryInfo value) { this.placeOfStayInRegCountryInfo = value; } /** * Gets the value of the placeOfStayInRFInfo property. * * @return * possible object is * {@link ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRFInfo } * */ public ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRFInfo getPlaceOfStayInRFInfo() { return placeOfStayInRFInfo; } /** * Sets the value of the placeOfStayInRFInfo property. * * @param value * allowed object is * {@link ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRFInfo } * */ public void setPlaceOfStayInRFInfo(ParticipantType.IndividualPersonForeignStateInfo.PlaceOfStayInRFInfo value) { this.placeOfStayInRFInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="country" type="{http://zakupki.gov.ru/oos/base/1}OKSMRef" minOccurs="0"/> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "country", "postAddress", "factAddress", "contactEMail", "contactPhone" }) public static class PlaceOfStayInRegCountryInfo { protected OKSMRef country; protected String postAddress; protected String factAddress; @XmlElement(required = true) protected String contactEMail; @XmlElement(required = true) protected String contactPhone; /** * Gets the value of the country property. * * @return * possible object is * {@link OKSMRef } * */ public OKSMRef getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link OKSMRef } * */ public void setCountry(OKSMRef value) { this.country = value; } /** * Gets the value of the postAddress property. * * @return * possible object is * {@link String } * */ public String getPostAddress() { return postAddress; } /** * Sets the value of the postAddress property. * * @param value * allowed object is * {@link String } * */ public void setPostAddress(String value) { this.postAddress = value; } /** * Gets the value of the factAddress property. * * @return * possible object is * {@link String } * */ public String getFactAddress() { return factAddress; } /** * Sets the value of the factAddress property. * * @param value * allowed object is * {@link String } * */ public void setFactAddress(String value) { this.factAddress = value; } /** * Gets the value of the contactEMail property. * * @return * possible object is * {@link String } * */ public String getContactEMail() { return contactEMail; } /** * Sets the value of the contactEMail property. * * @param value * allowed object is * {@link String } * */ public void setContactEMail(String value) { this.contactEMail = value; } /** * Gets the value of the contactPhone property. * * @return * possible object is * {@link String } * */ public String getContactPhone() { return contactPhone; } /** * Sets the value of the contactPhone property. * * @param value * allowed object is * {@link String } * */ public void setContactPhone(String value) { this.contactPhone = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "postAddress", "factAddress", "contactEMail", "contactPhone" }) public static class PlaceOfStayInRFInfo { @XmlElement(required = true) protected String postAddress; @XmlElement(required = true) protected String factAddress; protected String contactEMail; protected String contactPhone; /** * Gets the value of the postAddress property. * * @return * possible object is * {@link String } * */ public String getPostAddress() { return postAddress; } /** * Sets the value of the postAddress property. * * @param value * allowed object is * {@link String } * */ public void setPostAddress(String value) { this.postAddress = value; } /** * Gets the value of the factAddress property. * * @return * possible object is * {@link String } * */ public String getFactAddress() { return factAddress; } /** * Sets the value of the factAddress property. * * @param value * allowed object is * {@link String } * */ public void setFactAddress(String value) { this.factAddress = value; } /** * Gets the value of the contactEMail property. * * @return * possible object is * {@link String } * */ public String getContactEMail() { return contactEMail; } /** * Sets the value of the contactEMail property. * * @param value * allowed object is * {@link String } * */ public void setContactEMail(String value) { this.contactEMail = value; } /** * Gets the value of the contactPhone property. * * @return * possible object is * {@link String } * */ public String getContactPhone() { return contactPhone; } /** * Sets the value of the contactPhone property. * * @param value * allowed object is * {@link String } * */ public void setContactPhone(String value) { this.contactPhone = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innIndividualType"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "inn", "registrationDate" }) public static class RegisterInRFTaxBodiesInfo { @XmlElement(name = "INN", required = true) protected String inn; @XmlSchemaType(name = "date") protected XMLGregorianCalendar registrationDate; /** * Gets the value of the inn property. * * @return * possible object is * {@link String } * */ public String getINN() { return inn; } /** * Sets the value of the inn property. * * @param value * allowed object is * {@link String } * */ public void setINN(String value) { this.inn = value; } /** * Gets the value of the registrationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRegistrationDate() { return registrationDate; } /** * Sets the value of the registrationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRegistrationDate(XMLGregorianCalendar value) { this.registrationDate = value; } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="nameInfo" type="{http://zakupki.gov.ru/oos/common/1}personType"/> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innIndividualType"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;element name="postAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="factAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;element name="isIP" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "nameInfo", "inn", "registrationDate", "postAddress", "factAddress", "contactEMail", "contactPhone", "isIP" }) public static class IndividualPersonRFInfo { @XmlElement(required = true) protected PersonType nameInfo; @XmlElement(name = "INN", required = true) protected String inn; @XmlSchemaType(name = "date") protected XMLGregorianCalendar registrationDate; @XmlElement(required = true) protected String postAddress; @XmlElement(required = true) protected String factAddress; protected String contactEMail; @XmlElement(required = true) protected String contactPhone; protected boolean isIP; /** * Gets the value of the nameInfo property. * * @return * possible object is * {@link PersonType } * */ public PersonType getNameInfo() { return nameInfo; } /** * Sets the value of the nameInfo property. * * @param value * allowed object is * {@link PersonType } * */ public void setNameInfo(PersonType value) { this.nameInfo = value; } /** * Gets the value of the inn property. * * @return * possible object is * {@link String } * */ public String getINN() { return inn; } /** * Sets the value of the inn property. * * @param value * allowed object is * {@link String } * */ public void setINN(String value) { this.inn = value; } /** * Gets the value of the registrationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRegistrationDate() { return registrationDate; } /** * Sets the value of the registrationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRegistrationDate(XMLGregorianCalendar value) { this.registrationDate = value; } /** * Gets the value of the postAddress property. * * @return * possible object is * {@link String } * */ public String getPostAddress() { return postAddress; } /** * Sets the value of the postAddress property. * * @param value * allowed object is * {@link String } * */ public void setPostAddress(String value) { this.postAddress = value; } /** * Gets the value of the factAddress property. * * @return * possible object is * {@link String } * */ public String getFactAddress() { return factAddress; } /** * Sets the value of the factAddress property. * * @param value * allowed object is * {@link String } * */ public void setFactAddress(String value) { this.factAddress = value; } /** * Gets the value of the contactEMail property. * * @return * possible object is * {@link String } * */ public String getContactEMail() { return contactEMail; } /** * Sets the value of the contactEMail property. * * @param value * allowed object is * {@link String } * */ public void setContactEMail(String value) { this.contactEMail = value; } /** * Gets the value of the contactPhone property. * * @return * possible object is * {@link String } * */ public String getContactPhone() { return contactPhone; } /** * Sets the value of the contactPhone property. * * @param value * allowed object is * {@link String } * */ public void setContactPhone(String value) { this.contactPhone = value; } /** * Gets the value of the isIP property. * */ public boolean isIsIP() { return isIP; } /** * Sets the value of the isIP property. * */ public void setIsIP(boolean value) { this.isIP = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="fullName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="shortName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="firmName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="fullNameLat" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="taxPayerCode" type="{http://zakupki.gov.ru/oos/base/1}taxPayerCode" minOccurs="0"/> * &lt;element name="ogrn" type="{http://zakupki.gov.ru/oos/base/1}ogrnCodeType" minOccurs="0"/> * &lt;element name="legalForm" type="{http://zakupki.gov.ru/oos/base/1}OKOPFRef" minOccurs="0"/> * &lt;element name="registerInRFTaxBodiesInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innEntityType"/> * &lt;element name="KPP" type="{http://zakupki.gov.ru/oos/base/1}kppType" minOccurs="0"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRegCountryInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="country" type="{http://zakupki.gov.ru/oos/base/1}OKSMRef"/> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="placeOfStayInRFInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "fullName", "shortName", "firmName", "fullNameLat", "taxPayerCode", "ogrn", "legalForm", "registerInRFTaxBodiesInfo", "placeOfStayInRegCountryInfo", "placeOfStayInRFInfo" }) public static class LegalEntityForeignStateInfo { @XmlElement(required = true) protected String fullName; protected String shortName; protected String firmName; protected String fullNameLat; protected String taxPayerCode; protected String ogrn; protected OKOPFRef legalForm; protected ParticipantType.LegalEntityForeignStateInfo.RegisterInRFTaxBodiesInfo registerInRFTaxBodiesInfo; @XmlElement(required = true) protected ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRegCountryInfo placeOfStayInRegCountryInfo; protected ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRFInfo placeOfStayInRFInfo; /** * Gets the value of the fullName property. * * @return * possible object is * {@link String } * */ public String getFullName() { return fullName; } /** * Sets the value of the fullName property. * * @param value * allowed object is * {@link String } * */ public void setFullName(String value) { this.fullName = value; } /** * Gets the value of the shortName property. * * @return * possible object is * {@link String } * */ public String getShortName() { return shortName; } /** * Sets the value of the shortName property. * * @param value * allowed object is * {@link String } * */ public void setShortName(String value) { this.shortName = value; } /** * Gets the value of the firmName property. * * @return * possible object is * {@link String } * */ public String getFirmName() { return firmName; } /** * Sets the value of the firmName property. * * @param value * allowed object is * {@link String } * */ public void setFirmName(String value) { this.firmName = value; } /** * Gets the value of the fullNameLat property. * * @return * possible object is * {@link String } * */ public String getFullNameLat() { return fullNameLat; } /** * Sets the value of the fullNameLat property. * * @param value * allowed object is * {@link String } * */ public void setFullNameLat(String value) { this.fullNameLat = value; } /** * Gets the value of the taxPayerCode property. * * @return * possible object is * {@link String } * */ public String getTaxPayerCode() { return taxPayerCode; } /** * Sets the value of the taxPayerCode property. * * @param value * allowed object is * {@link String } * */ public void setTaxPayerCode(String value) { this.taxPayerCode = value; } /** * Gets the value of the ogrn property. * * @return * possible object is * {@link String } * */ public String getOgrn() { return ogrn; } /** * Sets the value of the ogrn property. * * @param value * allowed object is * {@link String } * */ public void setOgrn(String value) { this.ogrn = value; } /** * Gets the value of the legalForm property. * * @return * possible object is * {@link OKOPFRef } * */ public OKOPFRef getLegalForm() { return legalForm; } /** * Sets the value of the legalForm property. * * @param value * allowed object is * {@link OKOPFRef } * */ public void setLegalForm(OKOPFRef value) { this.legalForm = value; } /** * Gets the value of the registerInRFTaxBodiesInfo property. * * @return * possible object is * {@link ParticipantType.LegalEntityForeignStateInfo.RegisterInRFTaxBodiesInfo } * */ public ParticipantType.LegalEntityForeignStateInfo.RegisterInRFTaxBodiesInfo getRegisterInRFTaxBodiesInfo() { return registerInRFTaxBodiesInfo; } /** * Sets the value of the registerInRFTaxBodiesInfo property. * * @param value * allowed object is * {@link ParticipantType.LegalEntityForeignStateInfo.RegisterInRFTaxBodiesInfo } * */ public void setRegisterInRFTaxBodiesInfo(ParticipantType.LegalEntityForeignStateInfo.RegisterInRFTaxBodiesInfo value) { this.registerInRFTaxBodiesInfo = value; } /** * Gets the value of the placeOfStayInRegCountryInfo property. * * @return * possible object is * {@link ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRegCountryInfo } * */ public ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRegCountryInfo getPlaceOfStayInRegCountryInfo() { return placeOfStayInRegCountryInfo; } /** * Sets the value of the placeOfStayInRegCountryInfo property. * * @param value * allowed object is * {@link ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRegCountryInfo } * */ public void setPlaceOfStayInRegCountryInfo(ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRegCountryInfo value) { this.placeOfStayInRegCountryInfo = value; } /** * Gets the value of the placeOfStayInRFInfo property. * * @return * possible object is * {@link ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRFInfo } * */ public ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRFInfo getPlaceOfStayInRFInfo() { return placeOfStayInRFInfo; } /** * Sets the value of the placeOfStayInRFInfo property. * * @param value * allowed object is * {@link ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRFInfo } * */ public void setPlaceOfStayInRFInfo(ParticipantType.LegalEntityForeignStateInfo.PlaceOfStayInRFInfo value) { this.placeOfStayInRFInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="country" type="{http://zakupki.gov.ru/oos/base/1}OKSMRef"/> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "country", "orgPostAddress", "orgFactAddress", "contactEMail", "contactPhone" }) public static class PlaceOfStayInRegCountryInfo { @XmlElement(required = true) protected OKSMRef country; @XmlElement(required = true) protected String orgPostAddress; @XmlElement(required = true) protected String orgFactAddress; @XmlElement(required = true) protected String contactEMail; @XmlElement(required = true) protected String contactPhone; /** * Gets the value of the country property. * * @return * possible object is * {@link OKSMRef } * */ public OKSMRef getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link OKSMRef } * */ public void setCountry(OKSMRef value) { this.country = value; } /** * Gets the value of the orgPostAddress property. * * @return * possible object is * {@link String } * */ public String getOrgPostAddress() { return orgPostAddress; } /** * Sets the value of the orgPostAddress property. * * @param value * allowed object is * {@link String } * */ public void setOrgPostAddress(String value) { this.orgPostAddress = value; } /** * Gets the value of the orgFactAddress property. * * @return * possible object is * {@link String } * */ public String getOrgFactAddress() { return orgFactAddress; } /** * Sets the value of the orgFactAddress property. * * @param value * allowed object is * {@link String } * */ public void setOrgFactAddress(String value) { this.orgFactAddress = value; } /** * Gets the value of the contactEMail property. * * @return * possible object is * {@link String } * */ public String getContactEMail() { return contactEMail; } /** * Sets the value of the contactEMail property. * * @param value * allowed object is * {@link String } * */ public void setContactEMail(String value) { this.contactEMail = value; } /** * Gets the value of the contactPhone property. * * @return * possible object is * {@link String } * */ public String getContactPhone() { return contactPhone; } /** * Sets the value of the contactPhone property. * * @param value * allowed object is * {@link String } * */ public void setContactPhone(String value) { this.contactPhone = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "orgPostAddress", "orgFactAddress", "contactEMail", "contactPhone" }) public static class PlaceOfStayInRFInfo { @XmlElement(required = true) protected String orgPostAddress; @XmlElement(required = true) protected String orgFactAddress; protected String contactEMail; protected String contactPhone; /** * Gets the value of the orgPostAddress property. * * @return * possible object is * {@link String } * */ public String getOrgPostAddress() { return orgPostAddress; } /** * Sets the value of the orgPostAddress property. * * @param value * allowed object is * {@link String } * */ public void setOrgPostAddress(String value) { this.orgPostAddress = value; } /** * Gets the value of the orgFactAddress property. * * @return * possible object is * {@link String } * */ public String getOrgFactAddress() { return orgFactAddress; } /** * Sets the value of the orgFactAddress property. * * @param value * allowed object is * {@link String } * */ public void setOrgFactAddress(String value) { this.orgFactAddress = value; } /** * Gets the value of the contactEMail property. * * @return * possible object is * {@link String } * */ public String getContactEMail() { return contactEMail; } /** * Sets the value of the contactEMail property. * * @param value * allowed object is * {@link String } * */ public void setContactEMail(String value) { this.contactEMail = value; } /** * Gets the value of the contactPhone property. * * @return * possible object is * {@link String } * */ public String getContactPhone() { return contactPhone; } /** * Sets the value of the contactPhone property. * * @param value * allowed object is * {@link String } * */ public void setContactPhone(String value) { this.contactPhone = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innEntityType"/> * &lt;element name="KPP" type="{http://zakupki.gov.ru/oos/base/1}kppType" minOccurs="0"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "inn", "kpp", "registrationDate" }) public static class RegisterInRFTaxBodiesInfo { @XmlElement(name = "INN", required = true) protected String inn; @XmlElement(name = "KPP") protected String kpp; @XmlSchemaType(name = "date") protected XMLGregorianCalendar registrationDate; /** * Gets the value of the inn property. * * @return * possible object is * {@link String } * */ public String getINN() { return inn; } /** * Sets the value of the inn property. * * @param value * allowed object is * {@link String } * */ public void setINN(String value) { this.inn = value; } /** * Gets the value of the kpp property. * * @return * possible object is * {@link String } * */ public String getKPP() { return kpp; } /** * Sets the value of the kpp property. * * @param value * allowed object is * {@link String } * */ public void setKPP(String value) { this.kpp = value; } /** * Gets the value of the registrationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRegistrationDate() { return registrationDate; } /** * Sets the value of the registrationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRegistrationDate(XMLGregorianCalendar value) { this.registrationDate = value; } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="fullName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="shortName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="firmName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/> * &lt;element name="INN" type="{http://zakupki.gov.ru/oos/base/1}innEntityType"/> * &lt;element name="KPP" type="{http://zakupki.gov.ru/oos/base/1}kppType"/> * &lt;element name="registrationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;element name="ogrn" type="{http://zakupki.gov.ru/oos/base/1}ogrnCodeType" minOccurs="0"/> * &lt;element name="legalForm" type="{http://zakupki.gov.ru/oos/base/1}OKOPFRef" minOccurs="0"/> * &lt;element name="contactInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactPersonInfo" type="{http://zakupki.gov.ru/oos/common/1}personType" minOccurs="0"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "fullName", "shortName", "firmName", "inn", "kpp", "registrationDate", "ogrn", "legalForm", "contactInfo" }) public static class LegalEntityRFInfo { @XmlElement(required = true) protected String fullName; protected String shortName; protected String firmName; @XmlElement(name = "INN", required = true) protected String inn; @XmlElement(name = "KPP", required = true) protected String kpp; @XmlSchemaType(name = "date") protected XMLGregorianCalendar registrationDate; protected String ogrn; protected OKOPFRef legalForm; @XmlElement(required = true) protected ParticipantType.LegalEntityRFInfo.ContactInfo contactInfo; /** * Gets the value of the fullName property. * * @return * possible object is * {@link String } * */ public String getFullName() { return fullName; } /** * Sets the value of the fullName property. * * @param value * allowed object is * {@link String } * */ public void setFullName(String value) { this.fullName = value; } /** * Gets the value of the shortName property. * * @return * possible object is * {@link String } * */ public String getShortName() { return shortName; } /** * Sets the value of the shortName property. * * @param value * allowed object is * {@link String } * */ public void setShortName(String value) { this.shortName = value; } /** * Gets the value of the firmName property. * * @return * possible object is * {@link String } * */ public String getFirmName() { return firmName; } /** * Sets the value of the firmName property. * * @param value * allowed object is * {@link String } * */ public void setFirmName(String value) { this.firmName = value; } /** * Gets the value of the inn property. * * @return * possible object is * {@link String } * */ public String getINN() { return inn; } /** * Sets the value of the inn property. * * @param value * allowed object is * {@link String } * */ public void setINN(String value) { this.inn = value; } /** * Gets the value of the kpp property. * * @return * possible object is * {@link String } * */ public String getKPP() { return kpp; } /** * Sets the value of the kpp property. * * @param value * allowed object is * {@link String } * */ public void setKPP(String value) { this.kpp = value; } /** * Gets the value of the registrationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRegistrationDate() { return registrationDate; } /** * Sets the value of the registrationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRegistrationDate(XMLGregorianCalendar value) { this.registrationDate = value; } /** * Gets the value of the ogrn property. * * @return * possible object is * {@link String } * */ public String getOgrn() { return ogrn; } /** * Sets the value of the ogrn property. * * @param value * allowed object is * {@link String } * */ public void setOgrn(String value) { this.ogrn = value; } /** * Gets the value of the legalForm property. * * @return * possible object is * {@link OKOPFRef } * */ public OKOPFRef getLegalForm() { return legalForm; } /** * Sets the value of the legalForm property. * * @param value * allowed object is * {@link OKOPFRef } * */ public void setLegalForm(OKOPFRef value) { this.legalForm = value; } /** * Gets the value of the contactInfo property. * * @return * possible object is * {@link ParticipantType.LegalEntityRFInfo.ContactInfo } * */ public ParticipantType.LegalEntityRFInfo.ContactInfo getContactInfo() { return contactInfo; } /** * Sets the value of the contactInfo property. * * @param value * allowed object is * {@link ParticipantType.LegalEntityRFInfo.ContactInfo } * */ public void setContactInfo(ParticipantType.LegalEntityRFInfo.ContactInfo value) { this.contactInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="orgPostAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="orgFactAddress" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="contactPersonInfo" type="{http://zakupki.gov.ru/oos/common/1}personType" minOccurs="0"/> * &lt;element name="contactEMail" type="{http://zakupki.gov.ru/oos/base/1}eMailType" minOccurs="0"/> * &lt;element name="contactPhone" type="{http://zakupki.gov.ru/oos/base/1}phoneType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "orgPostAddress", "orgFactAddress", "contactPersonInfo", "contactEMail", "contactPhone" }) public static class ContactInfo { @XmlElement(required = true) protected String orgPostAddress; @XmlElement(required = true) protected String orgFactAddress; protected PersonType contactPersonInfo; protected String contactEMail; @XmlElement(required = true) protected String contactPhone; /** * Gets the value of the orgPostAddress property. * * @return * possible object is * {@link String } * */ public String getOrgPostAddress() { return orgPostAddress; } /** * Sets the value of the orgPostAddress property. * * @param value * allowed object is * {@link String } * */ public void setOrgPostAddress(String value) { this.orgPostAddress = value; } /** * Gets the value of the orgFactAddress property. * * @return * possible object is * {@link String } * */ public String getOrgFactAddress() { return orgFactAddress; } /** * Sets the value of the orgFactAddress property. * * @param value * allowed object is * {@link String } * */ public void setOrgFactAddress(String value) { this.orgFactAddress = value; } /** * Gets the value of the contactPersonInfo property. * * @return * possible object is * {@link PersonType } * */ public PersonType getContactPersonInfo() { return contactPersonInfo; } /** * Sets the value of the contactPersonInfo property. * * @param value * allowed object is * {@link PersonType } * */ public void setContactPersonInfo(PersonType value) { this.contactPersonInfo = value; } /** * Gets the value of the contactEMail property. * * @return * possible object is * {@link String } * */ public String getContactEMail() { return contactEMail; } /** * Sets the value of the contactEMail property. * * @param value * allowed object is * {@link String } * */ public void setContactEMail(String value) { this.contactEMail = value; } /** * Gets the value of the contactPhone property. * * @return * possible object is * {@link String } * */ public String getContactPhone() { return contactPhone; } /** * Sets the value of the contactPhone property. * * @param value * allowed object is * {@link String } * */ public void setContactPhone(String value) { this.contactPhone = value; } } } }
3e157db9bf672290d927003b902b9349faa8bc1c
1,018
java
Java
mojo/test/editor/MojoFoldingTest.java
jbakerdev/Perl5-IDEA
32ca0a29ea523c4f1f01ed7cc8c406e8583215e1
[ "Apache-2.0" ]
273
2016-06-01T22:04:50.000Z
2022-03-06T01:52:02.000Z
mojo/test/editor/MojoFoldingTest.java
jbakerdev/Perl5-IDEA
32ca0a29ea523c4f1f01ed7cc8c406e8583215e1
[ "Apache-2.0" ]
1,317
2016-05-31T06:49:50.000Z
2022-03-25T17:13:51.000Z
mojo/test/editor/MojoFoldingTest.java
jbakerdev/Perl5-IDEA
32ca0a29ea523c4f1f01ed7cc8c406e8583215e1
[ "Apache-2.0" ]
62
2016-06-03T20:17:17.000Z
2022-03-02T19:02:04.000Z
29.085714
75
0.759332
9,134
/* * Copyright 2015-2020 Alexandr Evstigneev * * 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 editor; import base.MojoLightTestCase; import com.perl5.lang.mojolicious.filetypes.MojoliciousFileType; import org.junit.Test; public class MojoFoldingTest extends MojoLightTestCase { @Override protected String getBaseDataPath() { return "testData/folding/templates"; } @Test public void testMojolicious() { testFoldingRegions(getTestName(true), MojoliciousFileType.INSTANCE); } }
3e157e3c6d8ba89f97a1c75c4ad2ad5a082cf78e
6,078
java
Java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/ExternalVpnGatewayInterface.java
xiesheng211/google-cloud-java
d1372d448004763cec7f1c7a636bd0fcee990a15
[ "Apache-2.0" ]
1
2021-06-23T07:47:58.000Z
2021-06-23T07:47:58.000Z
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/ExternalVpnGatewayInterface.java
xiesheng211/google-cloud-java
d1372d448004763cec7f1c7a636bd0fcee990a15
[ "Apache-2.0" ]
2
2021-03-31T19:17:29.000Z
2021-12-13T20:18:39.000Z
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/ExternalVpnGatewayInterface.java
xiesheng211/google-cloud-java
d1372d448004763cec7f1c7a636bd0fcee990a15
[ "Apache-2.0" ]
1
2020-02-15T13:41:55.000Z
2020-02-15T13:41:55.000Z
29.362319
100
0.689536
9,135
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.compute.v1; import com.google.api.core.BetaApi; import com.google.api.gax.httpjson.ApiMessage; import java.util.List; import java.util.Objects; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("by GAPIC") @BetaApi /** The interface for the external VPN gateway. */ public final class ExternalVpnGatewayInterface implements ApiMessage { private final Integer id; private final String ipAddress; private ExternalVpnGatewayInterface() { this.id = null; this.ipAddress = null; } private ExternalVpnGatewayInterface(Integer id, String ipAddress) { this.id = id; this.ipAddress = ipAddress; } @Override public Object getFieldValue(String fieldName) { if ("id".equals(fieldName)) { return id; } if ("ipAddress".equals(fieldName)) { return ipAddress; } return null; } @Nullable @Override public ApiMessage getApiMessageRequestBody() { return null; } @Nullable @Override /** * The fields that should be serialized (even if they have empty values). If the containing * message object has a non-null fieldmask, then all the fields in the field mask (and only those * fields in the field mask) will be serialized. If the containing object does not have a * fieldmask, then only non-empty fields will be serialized. */ public List<String> getFieldMask() { return null; } /** * The numeric ID of this interface. The allowed input values for this id for different redundancy * types of external VPN gateway: SINGLE_IP_INTERNALLY_REDUNDANT - 0 TWO_IPS_REDUNDANCY - 0, 1 * FOUR_IPS_REDUNDANCY - 0, 1, 2, 3 */ public Integer getId() { return id; } /** * IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP * address can be either from your on-premise gateway or another Cloud provider?s VPN gateway, it * cannot be an IP address from Google Compute Engine. */ public String getIpAddress() { return ipAddress; } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(ExternalVpnGatewayInterface prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } public static ExternalVpnGatewayInterface getDefaultInstance() { return DEFAULT_INSTANCE; } private static final ExternalVpnGatewayInterface DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new ExternalVpnGatewayInterface(); } public static class Builder { private Integer id; private String ipAddress; Builder() {} public Builder mergeFrom(ExternalVpnGatewayInterface other) { if (other == ExternalVpnGatewayInterface.getDefaultInstance()) return this; if (other.getId() != null) { this.id = other.id; } if (other.getIpAddress() != null) { this.ipAddress = other.ipAddress; } return this; } Builder(ExternalVpnGatewayInterface source) { this.id = source.id; this.ipAddress = source.ipAddress; } /** * The numeric ID of this interface. The allowed input values for this id for different * redundancy types of external VPN gateway: SINGLE_IP_INTERNALLY_REDUNDANT - 0 * TWO_IPS_REDUNDANCY - 0, 1 FOUR_IPS_REDUNDANCY - 0, 1, 2, 3 */ public Integer getId() { return id; } /** * The numeric ID of this interface. The allowed input values for this id for different * redundancy types of external VPN gateway: SINGLE_IP_INTERNALLY_REDUNDANT - 0 * TWO_IPS_REDUNDANCY - 0, 1 FOUR_IPS_REDUNDANCY - 0, 1, 2, 3 */ public Builder setId(Integer id) { this.id = id; return this; } /** * IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP * address can be either from your on-premise gateway or another Cloud provider?s VPN gateway, * it cannot be an IP address from Google Compute Engine. */ public String getIpAddress() { return ipAddress; } /** * IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP * address can be either from your on-premise gateway or another Cloud provider?s VPN gateway, * it cannot be an IP address from Google Compute Engine. */ public Builder setIpAddress(String ipAddress) { this.ipAddress = ipAddress; return this; } public ExternalVpnGatewayInterface build() { return new ExternalVpnGatewayInterface(id, ipAddress); } public Builder clone() { Builder newBuilder = new Builder(); newBuilder.setId(this.id); newBuilder.setIpAddress(this.ipAddress); return newBuilder; } } @Override public String toString() { return "ExternalVpnGatewayInterface{" + "id=" + id + ", " + "ipAddress=" + ipAddress + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ExternalVpnGatewayInterface) { ExternalVpnGatewayInterface that = (ExternalVpnGatewayInterface) o; return Objects.equals(this.id, that.getId()) && Objects.equals(this.ipAddress, that.getIpAddress()); } return false; } @Override public int hashCode() { return Objects.hash(id, ipAddress); } }
3e157ef9a84e8bee135c6ece0265b77a218dfdbb
10,150
java
Java
src/main/java/com/jsoniter/output/Codegen.java
Sanzo95/maxibonprova
dc09e29c8fe585da99f5294ed19624904956889f
[ "MIT" ]
null
null
null
src/main/java/com/jsoniter/output/Codegen.java
Sanzo95/maxibonprova
dc09e29c8fe585da99f5294ed19624904956889f
[ "MIT" ]
null
null
null
src/main/java/com/jsoniter/output/Codegen.java
Sanzo95/maxibonprova
dc09e29c8fe585da99f5294ed19624904956889f
[ "MIT" ]
null
null
null
31.521739
115
0.693695
9,136
package com.jsoniter.output; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.jsoniter.spi.ClassInfo; import com.jsoniter.spi.Encoder; import com.jsoniter.spi.Extension; import com.jsoniter.spi.GenericsHelper; import com.jsoniter.spi.JsonException; import com.jsoniter.spi.JsoniterSpi; import com.jsoniter.spi.TypeLiteral; /** * class Codegen * * @author MaxiBon * */ class Codegen { private Codegen() { } /** * static CodegenAccess.StaticCodegenTarget isDoingStaticCodegen */ static CodegenAccess.StaticCodegenTarget isDoingStaticCodegen = new CodegenAccess.StaticCodegenTarget(""); // only read/write when generating code with synchronized protection private final static Map<String, CodegenResult> generatedSources = new HashMap<String, CodegenResult>(); /** * getReflectionEncoder * * @param cacheKey * @param type * @return */ public static Encoder.ReflectionEncoder getReflectionEncoder(String cacheKey, Type type) { Map<String, Encoder.ReflectionEncoder> reflectionEncoders = new HashMap<String, Encoder.ReflectionEncoder>(); Encoder.ReflectionEncoder encoder = CodegenImplNative.NATIVE_ENCODERS.get(type); if (encoder != null) { return encoder; } encoder = reflectionEncoders.get(cacheKey); if (encoder != null) { return encoder; } synchronized (Codegen.class) { encoder = reflectionEncoders.get(cacheKey); if (encoder != null) { return encoder; } ClassInfo classInfo = new ClassInfo(type); encoder = ReflectionEncoderFactory.create(classInfo); HashMap<String, Encoder.ReflectionEncoder> copy = new HashMap<String, Encoder.ReflectionEncoder>( reflectionEncoders); copy.put(cacheKey, encoder); reflectionEncoders = copy; return encoder; } } public static Encoder getEncoder(String cacheKey, Type type) { Encoder encoder = JsoniterSpi.getEncoder(cacheKey); if (encoder != null) { return encoder; } return gen(cacheKey, type); } /** * primo metodo di supporto per errore "Follow the limit for number of * statements in a method" * * @param classInfo */ private static void primo(ClassInfo classInfo) { if (Map.class.isAssignableFrom(classInfo.clazz) && classInfo.typeArgs.length > 1) { DefaultMapKeyEncoder.registerOrGetExisting(classInfo.typeArgs[0]); } } /** * secondo metodo di supporto per errore "Follow the limit for number of * statements in a method" * * @param encoder * @param cacheKey * @return * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException */ private static Encoder secondo(Encoder encoder, final String cacheKey) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Encoder e = encoder; if (Class.forName(cacheKey).newInstance() instanceof Encoder) { e = (Encoder) Class.forName(cacheKey).newInstance(); } return e; } /** * terzo metodo di supporto per errore "Follow the limit for number of * statements in a method" * * @param encoder * @param cacheKey * @param classInfo * @param source * @return */ private static Encoder terzo(Encoder encoder, final String cacheKey, ClassInfo classInfo, CodegenResult source) { Encoder e = encoder; try { generatedSources.put(cacheKey, source); if (isDoingStaticCodegen.outputDir == "") { e = DynamicCodegen.gen(classInfo.clazz, cacheKey, source); } else { staticGen(classInfo.clazz, cacheKey, source); } } catch (Exception excpt) { System.out.print(""); } finally { System.out.print(""); } return e; } private static void quarto(EncodingMode mode) { if (mode == EncodingMode.STATIC_MODE) { throw new JsonException(); } } private static Encoder quinto(EncodingMode mode, ClassInfo classInfo, Encoder encoder, final String cacheKey) { Encoder e = encoder; primo(classInfo); if (mode == EncodingMode.REFLECTION_MODE) { return ReflectionEncoderFactory.create(classInfo); } if (isDoingStaticCodegen.outputDir == "") { try { return secondo(e, cacheKey); } catch (Exception exc) { quarto(mode); } } CodegenResult source = genSource(cacheKey, classInfo); try { return terzo(e, cacheKey, classInfo, source); } catch (Exception exc) { throw new JsonException(); } } private static Encoder gen(final String cacheKey, Type type) { synchronized (gen(cacheKey, type)) { Encoder encoder = (JsoniterSpi.getEncoder(cacheKey) != null) ? JsoniterSpi.getEncoder(cacheKey) : null; List<Extension> extensions = JsoniterSpi.getExtensions(); for (Extension extension : extensions) { if (extension.createEncoder(cacheKey, type) != null) { JsoniterSpi.addNewEncoder(cacheKey, extension.createEncoder(cacheKey, type)); encoder = extension.createEncoder(cacheKey, type); } } if (CodegenImplNative.NATIVE_ENCODERS.get(type) != null) { JsoniterSpi.addNewEncoder(cacheKey, CodegenImplNative.NATIVE_ENCODERS.get(type)); encoder = CodegenImplNative.NATIVE_ENCODERS.get(type); } addPlaceholderEncoderToSupportRecursiveStructure(cacheKey); if (JsoniterSpi.getCurrentConfig().encodingMode() != EncodingMode.REFLECTION_MODE) { if (Object.class == chooseAccessibleSuper(type)) { throw new JsonException("dynamic code can not serialize private class: " + type); } } encoder = quinto(JsoniterSpi.getCurrentConfig().encodingMode(), new ClassInfo(chooseAccessibleSuper(type)), encoder, cacheKey); JsoniterSpi.addNewEncoder(cacheKey, encoder); return encoder; } } private static void addPlaceholderEncoderToSupportRecursiveStructure(final String cacheKey) { JsoniterSpi.addNewEncoder(cacheKey, new Encoder() { @Override public void encode(Object obj, JsonStream stream) throws IOException { Encoder encoder = JsoniterSpi.getEncoder(cacheKey); try { if (this == encoder) { for (int i = 0; i < 30; i++) { encoder = JsoniterSpi.getEncoder(cacheKey); if (this == encoder) { int n = 1000; Thread.sleep(n); } else { break; } } if (this == encoder) { throw new JsonException("internal error: placeholder is not replaced with real encoder"); } } } catch (InterruptedException e) { throw new JsonException(); } encoder.encode(obj, stream); } }); } private static Type chooseAccessibleSuper(Type type) { Type[] typeArgs = new Type[0]; Class clazz = null; if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; clazz = (Class) pType.getRawType(); typeArgs = pType.getActualTypeArguments(); } else { if (type instanceof Class) { clazz = (Class) type; } } if (Modifier.isPublic(clazz.getModifiers())) { return type; } clazz = walkSuperUntilPublic(clazz.getSuperclass()); if (typeArgs.length == 0) { return clazz; } else { return GenericsHelper.createParameterizedType(typeArgs, null, clazz); } } private static Class walkSuperUntilPublic(Class clazz) { if (Modifier.isPublic(clazz.getModifiers())) { return clazz; } return walkSuperUntilPublic(clazz.getSuperclass()); } public static CodegenResult getGeneratedSource(String cacheKey) { return generatedSources.get(cacheKey); } private static void staticGen(Class clazz, String cacheKey, CodegenResult source) throws IOException { createDir(cacheKey); String fileName = cacheKey.replace('.', '/') + ".java"; FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(new File(isDoingStaticCodegen.outputDir, fileName)); OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream); try { staticGen(clazz, cacheKey, writer, source); } finally { writer.close(); } } finally { fileOutputStream.close(); } } private static void staticGen(Class clazz, String cacheKey, OutputStreamWriter writer, CodegenResult source) throws IOException { String className = cacheKey.substring(cacheKey.lastIndexOf('.') + 1); String packageName = cacheKey.substring(0, cacheKey.lastIndexOf('.')); writer.write("package " + packageName + ";\n"); writer.write("public class " + className + " implements com.jsoniter.spi.Encoder {\n"); writer.write(source.generateWrapperCode(clazz)); writer.write(source.toString()); writer.write("}\n"); } private static void createDir(String cacheKey) { String[] parts = cacheKey.split("\\."); File parent = new File(isDoingStaticCodegen.outputDir); File current = null; for (int i = 0; i < parts.length - 1; i++) { String part = parts[i]; current = new File(parent, part); current.mkdir(); parent = current; } } private static CodegenResult genSource(String cacheKey, ClassInfo classInfo) { Class clazz = classInfo.clazz; if (clazz.isArray()) { return CodegenImplArray.genArray(cacheKey, classInfo); } if (Map.class.isAssignableFrom(clazz)) { return CodegenImplMap.genMap(cacheKey, classInfo); } if (Collection.class.isAssignableFrom(clazz)) { return CodegenImplArray.genCollection(cacheKey, classInfo); } if (clazz.isEnum()) { return CodegenImplNative.genEnum(clazz); } return CodegenImplObject.genObject(classInfo); } public static void staticGenEncoders(TypeLiteral[] typeLiterals, CodegenAccess.StaticCodegenTarget staticCodegenTarget) { isDoingStaticCodegen = staticCodegenTarget; for (TypeLiteral typeLiteral : typeLiterals) { gen(typeLiteral.getEncoderCacheKey(), typeLiteral.getType()); } } }
3e158024f05c4662ddaaf80f40c98801e5859908
12,778
java
Java
activiti-core/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskVariablesTest.java
HurryUpWb/Activiti
a0cc6985d29695c8043b8e2413729348478b3828
[ "Apache-2.0" ]
8,599
2015-01-01T01:29:48.000Z
2022-03-30T03:23:40.000Z
activiti-core/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskVariablesTest.java
LoveMyOrange/Activiti
e39053d02c47cfebbece7a4978ab4dd1eaf2d620
[ "Apache-2.0" ]
2,988
2015-01-03T19:45:21.000Z
2022-03-31T04:08:38.000Z
activiti-core/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskVariablesTest.java
Harshit51435/Activiti
03a0e06921a9ff51c0e700a8c14770ca2c2eb49d
[ "Apache-2.0" ]
7,097
2015-01-02T06:32:21.000Z
2022-03-31T08:17:25.000Z
42.879195
121
0.737987
9,137
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.test.api.task; import static org.assertj.core.api.Assertions.assertThat; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.activiti.engine.impl.persistence.entity.VariableInstance; import org.activiti.engine.impl.test.PluggableActivitiTestCase; import org.activiti.engine.runtime.Execution; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.activiti.engine.test.Deployment; /** */ public class TaskVariablesTest extends PluggableActivitiTestCase { public void testStandaloneTaskVariables() { Task task = taskService.newTask(); task.setName("gonzoTask"); taskService.saveTask(task); String taskId = task.getId(); taskService.setVariable(taskId, "instrument", "trumpet"); assertThat(taskService.getVariable(taskId, "instrument")).isEqualTo("trumpet"); taskService.deleteTask(taskId, true); } @Deployment public void testTaskExecutionVariables() { String processInstanceId = runtimeService.startProcessInstanceByKey("oneTaskProcess").getId(); String taskId = taskService.createTaskQuery().singleResult().getId(); Map<String, Object> expectedVariables = new HashMap<String, Object>(); assertThat(runtimeService.getVariables(processInstanceId)).isEqualTo(expectedVariables); assertThat(taskService.getVariables(taskId)).isEqualTo(expectedVariables); assertThat(runtimeService.getVariablesLocal(processInstanceId)).isEqualTo(expectedVariables); assertThat(taskService.getVariablesLocal(taskId)).isEqualTo(expectedVariables); runtimeService.setVariable(processInstanceId, "instrument", "trumpet"); expectedVariables = new HashMap<String, Object>(); assertThat(taskService.getVariablesLocal(taskId)).isEqualTo(expectedVariables); expectedVariables.put("instrument", "trumpet"); assertThat(runtimeService.getVariables(processInstanceId)).isEqualTo(expectedVariables); assertThat(taskService.getVariables(taskId)).isEqualTo(expectedVariables); assertThat(runtimeService.getVariablesLocal(processInstanceId)).isEqualTo(expectedVariables); taskService.setVariable(taskId, "player", "gonzo"); assertThat(taskService.hasVariable(taskId, "player")).isTrue(); assertThat(taskService.hasVariableLocal(taskId, "budget")).isFalse(); expectedVariables = new HashMap<String, Object>(); assertThat(taskService.getVariablesLocal(taskId)).isEqualTo(expectedVariables); expectedVariables.put("player", "gonzo"); expectedVariables.put("instrument", "trumpet"); assertThat(runtimeService.getVariables(processInstanceId)).isEqualTo(expectedVariables); assertThat(taskService.getVariables(taskId)).isEqualTo(expectedVariables); assertThat(runtimeService.getVariablesLocal(processInstanceId)).isEqualTo(expectedVariables); taskService.setVariableLocal(taskId, "budget", "unlimited"); assertThat(taskService.hasVariableLocal(taskId, "budget")).isTrue(); assertThat(taskService.hasVariable(taskId, "budget")).isTrue(); expectedVariables = new HashMap<String, Object>(); expectedVariables.put("budget", "unlimited"); assertThat(taskService.getVariablesLocal(taskId)).isEqualTo(expectedVariables); expectedVariables.put("player", "gonzo"); expectedVariables.put("instrument", "trumpet"); assertThat(taskService.getVariables(taskId)).isEqualTo(expectedVariables); expectedVariables = new HashMap<String, Object>(); expectedVariables.put("player", "gonzo"); expectedVariables.put("instrument", "trumpet"); assertThat(runtimeService.getVariables(processInstanceId)).isEqualTo(expectedVariables); assertThat(runtimeService.getVariablesLocal(processInstanceId)).isEqualTo(expectedVariables); } public void testSerializableTaskVariable() { Task task = taskService.newTask(); task.setName("MyTask"); taskService.saveTask(task); // Set variable Map<String, Object> vars = new HashMap<String, Object>(); MyVariable myVariable = new MyVariable("Hello world"); vars.put("theVar", myVariable); taskService.setVariables(task.getId(), vars); // Fetch variable MyVariable variable = (MyVariable) taskService.getVariable(task.getId(), "theVar"); assertThat(variable.getValue()).isEqualTo("Hello world"); // Cleanup taskService.deleteTask(task.getId(), true); } @Deployment public void testGetVariablesLocalByTaskIds(){ ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("twoTaskProcess"); ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey("twoTaskProcess"); List<Task> taskList1 = taskService.createTaskQuery().processInstanceId(processInstance1.getId()).list(); List<Task> taskList2 = taskService.createTaskQuery().processInstanceId(processInstance2.getId()).list(); // Task local variables for(Task task : taskList1){ if ("usertask1".equals(task.getTaskDefinitionKey())){ taskService.setVariableLocal(task.getId(), "taskVar1", "sayHello1"); } else { taskService.setVariableLocal(task.getId(), "taskVar2", "sayHello2"); } // Execution variables taskService.setVariable(task.getId(), "executionVar1", "helloWorld1"); } // Task local variables for (Task task : taskList2){ if ("usertask1".equals(task.getTaskDefinitionKey())){ taskService.setVariableLocal(task.getId(), "taskVar3", "sayHello3"); } else { taskService.setVariableLocal(task.getId(), "taskVar4", "sayHello4"); } // Execution variables taskService.setVariable(task.getId(), "executionVar2", "helloWorld2"); } // only 1 process Set<String> taskIds = new HashSet<String>(); taskIds.add(taskList1.get(0).getId()); taskIds.add(taskList1.get(1).getId()); List<VariableInstance> variables = taskService.getVariableInstancesLocalByTaskIds(taskIds); assertThat(variables).hasSize(2); checkVariable(taskList1.get(0).getId(), "taskVar1" , "sayHello1", variables); checkVariable(taskList1.get(1).getId(), "taskVar2" , "sayHello2", variables); // 2 process taskIds = new HashSet<String>(); taskIds.add(taskList1.get(0).getId()); taskIds.add(taskList1.get(1).getId()); taskIds.add(taskList2.get(0).getId()); taskIds.add(taskList2.get(1).getId()); variables = taskService.getVariableInstancesLocalByTaskIds(taskIds); assertThat(variables).hasSize(4); checkVariable(taskList1.get(0).getId(), "taskVar1" , "sayHello1", variables); checkVariable(taskList1.get(1).getId(), "taskVar2" , "sayHello2", variables); checkVariable(taskList2.get(0).getId(), "taskVar3" , "sayHello3", variables); checkVariable(taskList2.get(1).getId(), "taskVar4" , "sayHello4", variables); // mixture 2 process taskIds = new HashSet<String>(); taskIds.add(taskList1.get(0).getId()); taskIds.add(taskList2.get(1).getId()); variables = taskService.getVariableInstancesLocalByTaskIds(taskIds); assertThat(variables).hasSize(2); checkVariable(taskList1.get(0).getId(), "taskVar1" , "sayHello1", variables); checkVariable(taskList2.get(1).getId(), "taskVar4" , "sayHello4", variables); } @Deployment public void testGetVariablesCopiedIntoTasks(){ //variables not automatically copied into tasks at engine level unless we turn this on processEngineConfiguration.setCopyVariablesToLocalForTasks(true); Map<String,Object> startVariables = new HashMap<>(); startVariables.put("start1","start1"); startVariables.put("start2","start2"); ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey("twoTaskProcess",startVariables); Task userTask1 = taskService.createTaskQuery().taskDefinitionKey("usertask1").singleResult(); Task userTask2 = taskService.createTaskQuery().taskDefinitionKey("usertask2").singleResult(); //both should have the process variables copied into their local assertThat(taskService.getVariablesLocal(userTask1.getId())).isEqualTo(startVariables); assertThat(taskService.getVariablesLocal(userTask2.getId())).isEqualTo(startVariables); //if one modifies, the other should not see the modification taskService.setVariableLocal(userTask1.getId(),"start1","modifiedstart1"); assertThat(startVariables).isEqualTo(taskService.getVariablesLocal(userTask2.getId())); taskService.complete(userTask1.getId()); //after completion the process variable should be updated but only that one and not task2's local variable assertThat(runtimeService.getVariable(processInstance1.getId(),"start1")).isEqualTo("modifiedstart1"); assertThat(runtimeService.getVariable(processInstance1.getId(),"start2")).isEqualTo("start2"); assertThat(taskService.getVariablesLocal(userTask2.getId())).isEqualTo(startVariables); processEngineConfiguration.setCopyVariablesToLocalForTasks(false); } private void checkVariable(String taskId, String name, String value, List<VariableInstance> variables) { assertThat(variables) .filteredOn(variable -> taskId.equals(variable.getTaskId())) .hasSize(1) .first() .satisfies(variable -> { assertThat(variable.getName()).isEqualTo(name); assertThat(variable.getValue()).isEqualTo(value); }); } @Deployment(resources={ "org/activiti/engine/test/api/task/TaskVariablesTest.testTaskExecutionVariables.bpmn20.xml" }) public void testGetVariablesLocalByTaskIdsForSerializableType(){ runtimeService.startProcessInstanceByKey("oneTaskProcess").getId(); String taskId = taskService.createTaskQuery().singleResult().getId(); StringBuilder sb = new StringBuilder("a"); for (int i = 0; i < 4001; i++) { sb.append("a"); } String serializableTypeVar = sb.toString(); taskService.setVariableLocal(taskId, "taskVar1", serializableTypeVar); // only 1 process Set<String> taskIds = new HashSet<String>(); taskIds.add(taskId); List<VariableInstance> variables = taskService.getVariableInstancesLocalByTaskIds(taskIds); assertThat(variables.get(0).getValue()).isEqualTo(serializableTypeVar); } @Deployment(resources={ "org/activiti/engine/test/api/runtime/variableScope.bpmn20.xml" }) public void testGetVariablesLocalByTaskIdsForScope(){ Map<String, Object> processVars = new HashMap<String, Object>(); processVars.put("processVar", "processVar"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("variableScopeProcess", processVars); Set<String> executionIds = new HashSet<String>(); List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); for (Execution execution : executions){ if (!processInstance.getId().equals(execution.getId())){ executionIds.add(execution.getId()); runtimeService.setVariableLocal(execution.getId(), "executionVar", "executionVar"); } } List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).list(); Set<String> taskIds = new HashSet<String>(); for (Task task : tasks){ taskService.setVariableLocal(task.getId(), "taskVar", "taskVar"); taskIds.add(task.getId()); } List<VariableInstance> variableInstances = taskService.getVariableInstancesLocalByTaskIds(taskIds); assertThat(2).isEqualTo(variableInstances.size()); assertThat("taskVar").isEqualTo(variableInstances.get(0).getName()); assertThat("taskVar").isEqualTo(variableInstances.get(0).getValue() ); assertThat("taskVar").isEqualTo(variableInstances.get(1).getName()); assertThat("taskVar").isEqualTo(variableInstances.get(1).getValue() ); } public static class MyVariable implements Serializable { private String value; public MyVariable(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }