blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8da45f826fe7ef740f7af1fef6fcde35d4116dad | a823bbe4b0840132e81bd469f1b66357ec50fcb2 | /src/test/java/com/huobi/client/impl/TestSyncRequestImpl.java | 5cc9dd72341b36c67f6e47799a0203a6c9232f7b | [
"Apache-2.0"
] | permissive | Snuby/huobi_Java | 065aa5fedf9cae79ee0b2336b9c866791458635d | 40214d1a94afa1ffdb383b9cc39b6f574472c207 | refs/heads/master | 2020-04-29T11:51:32.351119 | 2019-03-08T00:32:03 | 2019-03-08T00:32:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,284 | java | package com.huobi.client.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.same;
import static org.mockito.Mockito.when;
import com.huobi.client.model.BestQuote;
import com.huobi.client.model.Candlestick;
import com.huobi.client.model.LastTradeAndBestQuote;
import com.huobi.client.model.PriceDepth;
import com.huobi.client.model.Symbol;
import com.huobi.client.model.Trade;
import com.huobi.client.model.TradeStatistics;
import com.huobi.client.model.enums.CandlestickInterval;
import com.huobi.client.model.request.CandlestickRequest;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(RestApiInvoker.class)
@PowerMockIgnore({"okhttp3.*"})
public class TestSyncRequestImpl {
@Mock
RestApiRequestImpl restApiRequestImpl;
@Test
public void testGetLatestCandlestick() {
RestApiRequest<List<Candlestick>> restApiRequest = new RestApiRequest<>();
when(restApiRequestImpl.getCandlestick("btcusdt", CandlestickInterval.MIN1, null, null, 10))
.thenReturn(restApiRequest);
List<Candlestick> result = new LinkedList<>();
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest))).thenReturn(result);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertSame(result, impl.getLatestCandlestick("btcusdt", CandlestickInterval.MIN1, 10));
}
@Test
public void testGetCandlestick() {
RestApiRequest<List<Candlestick>> restApiRequest1 = new RestApiRequest<>();
RestApiRequest<List<Candlestick>> restApiRequest2 = new RestApiRequest<>();
CandlestickRequest request1 = new CandlestickRequest("abc", CandlestickInterval.DAY1, null,
null, 10);
CandlestickRequest request2 = new CandlestickRequest("def", CandlestickInterval.YEAR1);
when(restApiRequestImpl.getCandlestick(
request1.getSymbol(), request1.getInterval(), request1.getStartTime(),
request1.getEndTime(), request1.getSize())).thenReturn(restApiRequest1);
when(restApiRequestImpl.getCandlestick(
request2.getSymbol(), request2.getInterval(), request2.getStartTime(),
request2.getEndTime(), request2.getSize())).thenReturn(restApiRequest2);
List<Candlestick> result1 = new LinkedList<>();
List<Candlestick> result2 = new LinkedList<>();
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest1))).thenReturn(result1);
when(RestApiInvoker.callSync(same(restApiRequest2))).thenReturn(result2);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertSame(result1, impl.getCandlestick(request1));
assertSame(result2, impl.getCandlestick(request2));
}
@Test
public void testGetExchangeTimestamp() {
RestApiRequest<Long> restApiRequest = new RestApiRequest<>();
when(restApiRequestImpl.getExchangeTimestamp()).thenReturn(restApiRequest);
PowerMockito.mockStatic(RestApiInvoker.class);
long l = 1;
when(RestApiInvoker.callSync(same(restApiRequest))).thenReturn(l);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertSame(l, impl.getExchangeTimestamp());
}
@Test
public void testGetPriceDepth() {
RestApiRequest<PriceDepth> restApiRequest1 = new RestApiRequest<>();
RestApiRequest<PriceDepth> restApiRequest2 = new RestApiRequest<>();
when(restApiRequestImpl.getPriceDepth("abc", 11)).thenReturn(restApiRequest1);
when(restApiRequestImpl.getPriceDepth("abc", null)).thenReturn(restApiRequest2);
PriceDepth result1 = new PriceDepth();
PriceDepth result2 = new PriceDepth();
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest1))).thenReturn(result1);
when(RestApiInvoker.callSync(same(restApiRequest2))).thenReturn(result2);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertSame(result1, impl.getPriceDepth("abc", 11));
assertSame(result2, impl.getPriceDepth("abc"));
}
@Test
public void testGetLastTradeAndBestQuote() {
RestApiRequest<BestQuote> restApiRequest1 = new RestApiRequest<>();
RestApiRequest<List<Trade>> restApiRequest2 = new RestApiRequest<>();
when(restApiRequestImpl.getBestQuote("abc")).thenReturn(restApiRequest1);
when(restApiRequestImpl.getHistoricalTrade("abc", null, 1)).thenReturn(restApiRequest2);
BestQuote result1 = new BestQuote();
result1.setAskAmount(new BigDecimal("1.1"));
result1.setAskPrice(new BigDecimal("2.1"));
result1.setBidAmount(new BigDecimal("3.1"));
result1.setBidPrice(new BigDecimal("3.1"));
List<Trade> result2 = new LinkedList<>();
Trade testTrade1 = new Trade();
testTrade1.setPrice(new BigDecimal("4.1"));
testTrade1.setAmount(new BigDecimal("4.2"));
Trade testTrade2 = new Trade();
testTrade2.setPrice(new BigDecimal("5.1"));
testTrade2.setAmount(new BigDecimal("5.2"));
result2.add(testTrade1);
result2.add(testTrade2);
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest1))).thenReturn(result1);
when(RestApiInvoker.callSync(same(restApiRequest2))).thenReturn(result2);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
LastTradeAndBestQuote result = impl.getLastTradeAndBestQuote("abc");
assertEquals(result1.getAskAmount(), result.getAskAmount());
assertEquals(result1.getAskPrice(), result.getAskPrice());
assertEquals(result1.getBidAmount(), result.getBidAmount());
assertEquals(result1.getBidPrice(), result.getBidPrice());
assertEquals(testTrade2.getAmount(), result.getLastTradeAmount());
assertEquals(testTrade2.getPrice(), result.getLastTradePrice());
}
@Test
public void testGetLastTrade() {
RestApiRequest<List<Trade>> restApiRequest = new RestApiRequest<>();
when(restApiRequestImpl.getHistoricalTrade("abc", null, 1)).thenReturn(restApiRequest);
Trade trade = new Trade();
trade.setPrice(new BigDecimal("1.1"));
trade.setAmount(new BigDecimal("2.2"));
List<Trade> result = new LinkedList<>();
result.add(trade);
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest))).thenReturn(result);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertEquals(trade.getPrice(), impl.getLastTrade("abc").getPrice());
assertEquals(trade.getAmount(), impl.getLastTrade("abc").getAmount());
}
@Test
public void testGetHistoricalTrade() {
RestApiRequest<List<Trade>> restApiRequest = new RestApiRequest<>();
when(restApiRequestImpl.getHistoricalTrade("abc", null, 10)).thenReturn(restApiRequest);
List<Trade> result = new LinkedList<>();
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest))).thenReturn(result);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertSame(result, impl.getHistoricalTrade("abc", 10));
}
@Test
public void testGet24HTradeStatistics() {
RestApiRequest<TradeStatistics> restApiRequest = new RestApiRequest<>();
when(restApiRequestImpl.get24HTradeStatistics("abc")).thenReturn(restApiRequest);
TradeStatistics result = new TradeStatistics();
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest))).thenReturn(result);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertSame(result, impl.get24HTradeStatistics("abc"));
}
@Test
public void testGetExchangeInfo() {
RestApiRequest<List<Symbol>> restApiRequest1 = new RestApiRequest<>();
RestApiRequest<List<String>> restApiRequest2 = new RestApiRequest<>();
when(restApiRequestImpl.getSymbols()).thenReturn(restApiRequest1);
when(restApiRequestImpl.getCurrencies()).thenReturn(restApiRequest2);
List<Symbol> result1 = new LinkedList<>();
Symbol symbol = new Symbol();
symbol.setBaseCurrency("btc");
symbol.setQuoteCurrency("usdt");
result1.add(symbol);
List<String> result2 = new LinkedList<>();
result2.add("asd");
result2.add("qwe");
PowerMockito.mockStatic(RestApiInvoker.class);
when(RestApiInvoker.callSync(same(restApiRequest1))).thenReturn(result1);
when(RestApiInvoker.callSync(same(restApiRequest2))).thenReturn(result2);
SyncRequestImpl impl = new SyncRequestImpl(restApiRequestImpl);
assertEquals(1, impl.getExchangeInfo().getSymbolList().size());
assertEquals(2, impl.getExchangeInfo().getCurrencies().size());
assertEquals("btc", impl.getExchangeInfo().getSymbolList().get(0).getBaseCurrency());
assertEquals("usdt", impl.getExchangeInfo().getSymbolList().get(0).getQuoteCurrency());
assertEquals("asd", impl.getExchangeInfo().getCurrencies().get(0));
assertEquals("qwe", impl.getExchangeInfo().getCurrencies().get(1));
}
}
| [
"mawenrui@huobi.com"
] | mawenrui@huobi.com |
7e0df7e55f51d7bb7b638fd2e711e4710e5d8756 | ffc3560e8a157c0438933cee69e8ec314686ee90 | /src/RestaurantScene/Composite/MenuPart.java | 951b259c2cc718b01a02d2ced9bed664a682bece | [] | no_license | Freg-x/Design_Pattern2019 | 739b9d8afecc5dc4567b1d34b6095ae96839450f | b5130ab7e4acb784971eeab5e115642983191fdb | refs/heads/master | 2020-08-23T02:47:06.603028 | 2019-11-11T12:11:53 | 2019-11-11T12:11:53 | 216,526,052 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 698 | java | package Composite;
import Composite.Menu;
import Factory.Food;
import java.util.ArrayList;
import java.util.List;
public class MenuPart {
private String name;
private List<Food> foods = new ArrayList<Food>();
public MenuPart(String name){
System.out.println("MenuPart "+name+" was created.");
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addFoods(Food f){
foods.add(f);
}
public void display(){
System.out.println(this.getName());
for (Food f :foods
) {
f.display();
}
}
}
| [
"33998668+Tolebest1@users.noreply.github.com"
] | 33998668+Tolebest1@users.noreply.github.com |
c7eb3baf0ba89bf0a7f7033271960d6a99e249f7 | 4d8cc383e27ea897b76dc75b306db809575a75bc | /chalktalk/src/main/java/com/fairfield/chalktalk/daoImpl/CompanyStageDaoImpl.java | 26f1305e3c81ad74ad81f0844d77a43cf48006d7 | [] | no_license | ashwinisajjan/mentor-mentee-webapp | 99a239fa845498d4f486fcf12389c08b9eaccfe7 | 2944d2011a0d53004a0bd34f403a7ff20643c3d7 | refs/heads/master | 2020-04-21T03:54:34.735284 | 2020-01-22T15:56:15 | 2020-01-22T15:56:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 496 | java | package com.fairfield.chalktalk.daoImpl;
import org.springframework.stereotype.Repository;
import com.fairfield.chalktalk.dao.ICompanyStageDao;
import com.fairfield.chalktalk.dao.common.AbstractHibernateDao;
import com.fairfield.chalktalk.entities.CompanyStage;
@Repository
public class CompanyStageDaoImpl extends AbstractHibernateDao<CompanyStage> implements ICompanyStageDao {
public CompanyStageDaoImpl() {
super();
setClazz(CompanyStage.class);
}
// API
}
| [
"ashwini.sajjan@student.fairfield.edu"
] | ashwini.sajjan@student.fairfield.edu |
12a088aee1a62b30c0c360fb5ace7d43b6a6cf08 | c13ea0de802b3ff50e79e9e09c7240e7e251555e | /Java/src/main/java/JavaConcurrency/ThrottlingTaskSubmission/RejectedExecutionHandler/DemoExecutor.java | 361daf1833c3bfe3e4cb16b38c4efecdece14dde | [] | no_license | Nomiracle/springboot | a680bda5d3dc84c3f506e3ad8d90d8a551cff4d7 | 854648ded7bc143b92799b32dcbd1fac0d20d2d9 | refs/heads/master | 2022-12-21T00:19:52.261134 | 2021-02-12T03:30:06 | 2021-02-12T03:30:06 | 212,362,634 | 0 | 0 | null | 2022-12-15T23:46:26 | 2019-10-02T14:29:29 | Java | UTF-8 | Java | false | false | 1,392 | java | package JavaConcurrency.ThrottlingTaskSubmission.RejectedExecutionHandler;
import JavaConcurrency.ThrottlingTaskSubmission.DemoTask;
import java.util.concurrent.*;
public class DemoExecutor {
public static void main(String[] args) {
int threadCounter = 0;
BlockingQueue<Runnable>blockingQueue
= new ArrayBlockingQueue<>(10);
CustomThreadPoolExecutor executor
= new CustomThreadPoolExecutor(5,20,
5000, TimeUnit.MILLISECONDS,blockingQueue);
executor.setRejectedExecutionHandler(
(r, executor1) -> {
System.out.println("DemoTask Rejected : "+
((DemoTask)r).getName());
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(
"lets add another time : "+
(((DemoTask) r).getName())
);
executor1.execute(r);
}
);
executor.prestartAllCoreThreads();
while(true){
threadCounter++;
executor.execute(new DemoTask(threadCounter+""));
if(threadCounter == 300)
break;
}
}
}
| [
"308198861@qq.com"
] | 308198861@qq.com |
ef51d2ca9d0c9fbc06f0873d40511810ac9908fe | 7effb2f1faebc3c5d55afee3d15c859c5b28e67b | /lang/lang.test/src/test/java/mb/pie/lang/test/funcDef/params/twoBothAnonymous/twoBothAnonymousComponent.java | b295d00d0ebcb3027cfe22c328a160c692ec0098 | [
"Apache-2.0"
] | permissive | metaborg/pie | ac421ebf4e5265245137908b0c3c061848581db4 | ecf896f11a4fbc11b8aef8a8fb831663baa0d188 | refs/heads/develop | 2022-06-20T03:09:11.729080 | 2022-06-15T09:46:10 | 2022-06-15T09:46:10 | 102,454,792 | 8 | 4 | Apache-2.0 | 2022-06-15T09:46:11 | 2017-09-05T08:23:07 | Java | UTF-8 | Java | false | false | 475 | java | package mb.pie.lang.test.funcDef.params.twoBothAnonymous;
import dagger.Component;
import mb.pie.dagger.PieComponent;
import mb.pie.dagger.PieModule;
import javax.inject.Singleton;
@mb.pie.dagger.PieScope
@Component(modules = {PieModule.class, PieTestModule.class}, dependencies = {mb.log.dagger.LoggerComponent.class, mb.resource.dagger.ResourceServiceComponent.class})
public interface twoBothAnonymousComponent extends PieComponent {
main_twoBothAnonymous get();
}
| [
"noreply@github.com"
] | metaborg.noreply@github.com |
c7f93ab47ab7a773fe8e7395ccc4baaaa4b52ffd | a2da1d978b2051a5bff084f21b826a66bde05bb3 | /adv/src/main/java/com/mark/adv/AdvActivity.java | da8e81d52e448db028cf856f0916b3185d5673d0 | [] | no_license | Joinfeng/MakeBase | d22107384e4765946a20634eddd3844478c9c16f | b07399cc2130bc019011c3d924ba93f9042d23d3 | refs/heads/master | 2020-03-17T03:07:38.124833 | 2019-01-23T07:54:39 | 2019-01-23T07:54:39 | 133,221,158 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 552 | java | package com.mark.adv;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.mark.common.base.BaseActivity;
@Route(path = "/adv/advAct")
public class AdvActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected int getViewLayout() {
return R.layout.advact_layout;
}
}
| [
"mottoboy@126.com"
] | mottoboy@126.com |
0d0ad39b76cdfb00217609cdeaf0d0f271331b4b | d9fadce59ed908a56476827e387cef656cba4109 | /src/main/java/huntingrl/view/SceneChangeEvent.java | 3d1ac7ce0780ced004db1ab009bd0e2b018b1f40 | [
"Unlicense"
] | permissive | MattJTrueblood/HuntingRL | 129b04f1021b91859d8cd0370d04f25966847f42 | 66263900acbfd16a050eca0483a4ee2b2f1862d6 | refs/heads/develop | 2021-07-15T18:58:37.487952 | 2020-09-23T20:10:03 | 2020-09-23T20:10:03 | 210,669,450 | 0 | 0 | Unlicense | 2019-10-23T20:39:20 | 2019-09-24T18:17:45 | Java | UTF-8 | Java | false | false | 338 | java | package huntingrl.view;
import lombok.Builder;
@Builder
public class SceneChangeEvent {
@Builder.Default
public Scene scene = null;
@Builder.Default
public boolean saveOldScene = false;
@Builder.Default
public boolean goToSavedOldScene = false;
@Builder.Default
public boolean quitApplication = false;
}
| [
"mattjtrueblood@gmail.com"
] | mattjtrueblood@gmail.com |
22c2607cd9750a60f290c60291b7ffcb31beb63a | 39b7b0c2726d87f42275ffb834962ec33da7d553 | /xstampp-spring/xstampp-common/src/main/java/de/xstampp/common/errors/ErrorCondition.java | 8430fae5b3c46db80dfa8f1120c7be34bdbf9733 | [
"Apache-2.0"
] | permissive | duny31030/xstampp-4.0 | 90f1a253b95f2c8a4deecb3996ca1af443eefe09 | b31e952bf98fc88ec579f0cb11a029769ef0e745 | refs/heads/main | 2023-03-22T02:30:26.493074 | 2021-03-09T10:39:16 | 2021-03-09T10:39:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,453 | java | package de.xstampp.common.errors;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ErrorCondition implements Serializable {
private static final long serialVersionUID = 7725419417904368840L;
/*
* using @JsonProperty to set names that are similar to the Spring default error
* jsons
*/
@JsonProperty("error")
private final String errorCode;
@JsonProperty("status")
private final int httpStatusCode;
@JsonProperty("message")
private final String userVisibleMessage;
private boolean retriable = false;
@JsonIgnore
private boolean showNextMessage = false;
public ErrorCondition(String errorCode, int httpStatusCode, String userVisibleMessage) {
this.errorCode = errorCode;
this.httpStatusCode = httpStatusCode;
this.userVisibleMessage = userVisibleMessage;
}
private ErrorCondition(ErrorCondition other) {
this.errorCode = other.errorCode;
this.httpStatusCode = other.httpStatusCode;
this.userVisibleMessage = other.userVisibleMessage;
this.showNextMessage = other.showNextMessage;
this.retriable = other.retriable;
}
/* getters */
public String getErrorCode() {
return errorCode;
}
public int getHttpStatusCode() {
return httpStatusCode;
}
public String getUserVisibleMessage() {
return userVisibleMessage;
}
public boolean getRetriable() {
return retriable;
}
@JsonIgnore
public boolean isShowNextMesage() {
return showNextMessage;
}
/*
* "with" methods that return new ErrorConditions based on this one but with
* different settings
*/
public ErrorCondition withShowNextMessage() {
ErrorCondition cond = copy();
cond.showNextMessage = true;
return cond;
}
public ErrorCondition withRetriable() {
ErrorCondition cond = copy();
cond.retriable = true;
return cond;
}
/* exception building */
public GenericXSTAMPPException exc(Throwable cause, String internalMessage) {
return new GenericXSTAMPPException(this, cause, internalMessage);
}
public GenericXSTAMPPException exc(Throwable cause) {
return new GenericXSTAMPPException(this, cause);
}
public GenericXSTAMPPException exc(String internalMessage) {
return new GenericXSTAMPPException(this, internalMessage);
}
public GenericXSTAMPPException exc() {
return new GenericXSTAMPPException(this);
}
/* cloning */
private ErrorCondition copy() {
return new ErrorCondition(this);
}
}
| [
"stefan.wagner@iste.uni-stuttgart.de"
] | stefan.wagner@iste.uni-stuttgart.de |
9056aff03f3a416b45c7f9e2eec53de404f0ebdd | f0d25d83176909b18b9989e6fe34c414590c3599 | /app/src/main/java/com/tencent/smtt/sdk/ao.java | 5d99be1fb334a249104170eb7d60a3717f4d2f95 | [] | no_license | lycfr/lq | e8dd702263e6565486bea92f05cd93e45ef8defc | 123914e7c0d45956184dc908e87f63870e46aa2e | refs/heads/master | 2022-04-07T18:16:31.660038 | 2020-02-23T03:09:18 | 2020-02-23T03:09:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | package com.tencent.smtt.sdk;
import android.os.Build;
import com.tencent.component.plugin.server.PluginConstant;
import java.io.File;
import java.io.FileFilter;
final class ao implements FileFilter {
ao() {
}
public boolean accept(File file) {
String name = file.getName();
if (name != null && !name.endsWith(".jar_is_first_load_dex_flag_file")) {
return Build.VERSION.SDK_INT < 21 || !name.endsWith(PluginConstant.PLUGIN_INSTALL_DEX_OPT_SUFFIX);
}
return false;
}
}
| [
"quyenlm.vn@gmail.com"
] | quyenlm.vn@gmail.com |
181e7574be6593102867af5edf77fd7a6a2fd3b1 | edacfa5f2f4d0935967fc8da753c610c111605a6 | /robotappjpa/src/it/rpa/model/table/classes/RpBusinessOwner_.java | e68e81c13bee58737f5ef71aea9c7a6d4043ec6c | [] | no_license | dariostrazza/webapp_common_light | 7a9e7417da9e103ded0aac58d5ade25db4298c61 | d7661dfedb0921101c4ffdc79fccdd66b4503821 | refs/heads/master | 2020-04-28T16:56:28.789271 | 2019-03-13T11:01:42 | 2019-03-13T11:01:42 | 175,429,292 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 460 | java | package it.rpa.model.table.classes;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="Dali", date="2019-02-08T18:14:39.470+0100")
@StaticMetamodel(RpBusinessOwner.class)
public class RpBusinessOwner_ {
public static volatile SingularAttribute<RpBusinessOwner, String> id;
public static volatile SingularAttribute<RpBusinessOwner, Long> license;
}
| [
"ffarano@deloitte.it"
] | ffarano@deloitte.it |
9327a724fd2622adbfeba6d1f455b815cbc9e2d0 | ee69a5e831f7a5f76ef4507dec9f87a59199b582 | /src/main/java/com/ryz/sh/kafka/Message.java | efcdbef6608e4006c9109fecc952d108d3cbd0cc | [] | no_license | ryz-13997318136/SpringbootMvcKafkaAsync | 1eb4907e6fd6eab42e6e1837237f0aef5a8acd7a | 57067334e1034b2d75c3cb2fd8173c028400d352 | refs/heads/master | 2020-03-14T01:40:19.717703 | 2018-04-28T07:06:20 | 2018-04-28T07:06:20 | 131,382,423 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 508 | java | package com.ryz.sh.kafka;
import java.util.Date;
public class Message {
private Long id;
private String msg;
private Date date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
| [
"ryz@tzit.cn"
] | ryz@tzit.cn |
0f10bf9242079e51be1fb0c32153e444cc571b83 | a9f36e3184e38e00924869cc77c82b4bdf78ecc1 | /src/luceneExtend/org/apache/lucene/search/model/Hiemstra_LM.java | 782d1270f551d5f9122c39e4f69add6f8b83e450 | [] | no_license | jeffzhengye/lablucene | 8673815b35cc1b5be045d17a995b49bd98324c43 | 6586eede60ae9d9afd8b6fdd4d3b81c554ac0ab2 | refs/heads/master | 2020-04-21T11:22:16.143685 | 2014-01-24T21:13:25 | 2014-01-24T21:13:25 | 13,627,966 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,340 | java |
package org.apache.lucene.search.model;
import org.dutir.lucene.util.ApplicationSetup;
/**
*
*According to Zhai
*/
public class Hiemstra_LM extends WeightingModel {
/**
* A default constructor. Uses the default value of lambda=0.15.
*/
public Hiemstra_LM() {
super();
this.c = Float.parseFloat(ApplicationSetup.getProperty("wm.c", "0.15"));
}
/**
* Constructs an instance of this class with the specified value for the
* parameter lambda.
*
* @param lambda
* the smoothing parameter.
*/
public Hiemstra_LM(float lambda) {
this();
this.c = lambda;
}
/**
* Returns the name of the model.
*
* @return the name of the model
*/
public final String getInfo() {
return "Hiemstra_LM" + c;
}
/**
* Uses Hiemestra_LM to compute a weight for a term in a document.
*
* @param tf
* The term frequency in the document
* @param docLength
* the document's length
* @return the score assigned to a document with the given tf and docLength,
* and other preset parameters
*/
public final float score(float tf, float docLength) {
return keyFrequency * Idf.log(1 + ((1-c) * tf * numberOfTokens)
/ (c * termFrequency * docLength))
+ keyFrequency * Idf.log(c * termFrequency / numberOfTokens);
}
/**
* Uses Hiemstra_LM to compute a weight for a term in a document.
*
* @param tf
* The term frequency in the document
* @param docLength
* the document's length
* @param n_t
* The document frequency of the term
* @param F_t
* the term frequency in the collection
* @param keyFrequency
* the term frequency in the query
* @return the score assigned by the weighting model Hiemstra_LM.
*/
public final float score(float tf, float docLength, float n_t, float F_t,
float keyFrequency) {
return
keyFrequency * Idf.log(1 + (1- c) * tf * numberOfTokens / (c * F_t * docLength))
+keyFrequency * Idf.log(c * termFrequency / numberOfTokens);
/**
* Idf.log(((1 - c) * (tf / docLength)) / (c * (F_t / numberOfTokens)) +
* 1 ) + Idf.log(c* (F_t / numberOfTokens));
*/
}
public float unseeScore(int dl){
return score(0, dl);
}
}
| [
"jeff.zheng.ye@gmail.com"
] | jeff.zheng.ye@gmail.com |
7450c7e5f33247ad51e53baff7f49a059ec241c9 | d7e913aa36299ab2a596042177030c8576b46f91 | /GeneticProgramming/src/main/java/com/Genetic/gp/symbolic/SymbolicRegressionIterationListener.java | 1537b6cb3b5ee1a82df0b55ac7001ff4591a9cd7 | [] | no_license | AnnaDina/Tugas_GP_annadina | b83d9f2648a2a7cf64f7efd232e628c3623e7393 | 7e2276c497ac8fbfe88fbae837821380a55be736 | refs/heads/master | 2021-01-01T05:23:47.206780 | 2016-04-20T02:19:29 | 2016-04-20T02:19:29 | 56,647,640 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 290 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.Genetic.gp.symbolic;
/**
*
* @author Anna Dina
*/
public interface SymbolicRegressionIterationListener {
void update(SymbolicRegressionEngine symbolicRegressionEngine);
}
| [
"ad.kalifia@gmail.com"
] | ad.kalifia@gmail.com |
e893810f50d751558876587cb630303ce9d5463d | 798e58716ba48c75d4b68893a535af46113f2b19 | /src/main/java/edu/clemson/cs/rsrg/typeandpopulate/query/BaseMultimatchSymbolQuery.java | 52647f786da5d8b2a7ec3953ff389a4865d9d1a4 | [
"BSD-3-Clause"
] | permissive | M-Sitaraman/RESOLVE | 89bd2ea32e32f2c54e707b93747c2cd3311d717f | fdd6857ad841d8478f8cad09fd867756dad7bfaa | refs/heads/master | 2020-12-27T12:01:05.101459 | 2017-05-17T22:37:53 | 2017-05-17T22:37:53 | 23,886,951 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,954 | java | /*
* BaseMultimatchSymbolQuery.java
* ---------------------------------
* Copyright (c) 2017
* RESOLVE Software Research Group
* School of Computing
* Clemson University
* All rights reserved.
* ---------------------------------
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package edu.clemson.cs.rsrg.typeandpopulate.query;
import edu.clemson.cs.rsrg.typeandpopulate.entry.SymbolTableEntry;
import edu.clemson.cs.rsrg.typeandpopulate.exception.DuplicateSymbolException;
import edu.clemson.cs.rsrg.typeandpopulate.query.searcher.MultimatchTableSearcher;
import edu.clemson.cs.rsrg.typeandpopulate.query.searchpath.ScopeSearchPath;
import edu.clemson.cs.rsrg.typeandpopulate.symboltables.Scope;
import edu.clemson.cs.rsrg.typeandpopulate.symboltables.ScopeRepository;
import java.util.List;
/**
* <p>The most basic implementation of {@link MultimatchSymbolQuery}, which
* pairs a {@link ScopeSearchPath} with a {@link MultimatchTableSearcher} to
* define a fully parameterized strategy for searching a set of scopes.</p>
*
* @param <E> The return type of the base <code>MultimatchSymbolQuery</code>.
*
* @version 2.0
*/
abstract class BaseMultimatchSymbolQuery<E extends SymbolTableEntry>
implements
MultimatchSymbolQuery<E> {
// ===========================================================
// Member Fields
// ===========================================================
/** <p>Search path.</p> */
private final ScopeSearchPath mySearchPath;
/** <p>Symbol table searcher.</p> */
private final MultimatchTableSearcher<E> mySearcher;
// ===========================================================
// Constructors
// ===========================================================
/**
* <p>This is an helper constructor for storing the search path
* and a multimatch symbol table search strategy.</p>
*
* @param path Search path.
* @param searcher Multimatch symbol table searcher.
*/
protected BaseMultimatchSymbolQuery(ScopeSearchPath path,
MultimatchTableSearcher<E> searcher) {
mySearchPath = path;
mySearcher = searcher;
}
// ===========================================================
// Public Methods
// ===========================================================
/**
* <p>Behaves just as {@link SymbolQuery#searchFromContext(Scope, ScopeRepository)},
* except that it cannot throw a {@link DuplicateSymbolException}.</p>
*
* @param source The source scope from which the search was spawned.
* @param repo A repository of any referenced modules.
*
* @return A list of matches.
*/
@Override
public final List<E> searchFromContext(Scope source, ScopeRepository repo) {
return mySearchPath.searchFromContext(mySearcher, source, repo);
}
} | [
"yushans@g.clemson.edu"
] | yushans@g.clemson.edu |
7945ddde78667290589ea1574872e89afcf67c8c | 7e3e67b0e94d6b137df60738bf6b3f5f732b25d0 | /corejavaweek/src/Sortingdatainlistemployee/Namecamparator.java | 6ebf432b02c06cc3285eb4945df680c43ef971fc | [] | no_license | gvenkatesh4/corejavaprograms | 428f8d1f884e708c5b964e9f967743e1942d825f | 91aca8c8485e68e3a0dda3dc39021caf4f501e79 | refs/heads/master | 2022-10-15T22:23:52.280300 | 2020-06-13T05:20:52 | 2020-06-13T05:20:52 | 271,946,197 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 307 | java | package Sortingdatainlistemployee;
import java.util.Collections;
import java.util.Comparator;
public class Namecamparator implements Comparator<Employee> {
public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
return o1.getName().compareTo(o2.getName());
}
}
| [
"Venkatesh@LAPTOP-4OKHSCA5"
] | Venkatesh@LAPTOP-4OKHSCA5 |
6bbbd28032f7754df28c79e2aabfd9ad4821dd04 | 3d0740cc093b2ba462743390832415b9c1e44481 | /src/realtimeinterfaceexamplepackage/RealinterfaceExampleCaller.java | 48fccda0d832bc69e154e2d72702ec0cd36b8177 | [] | no_license | siddiswar/training-batch1 | 107c708fd523341f2d52388b8ca34e177e93ed77 | 6d6cae4b23d9f5f8aa1eaf26292bdaae9a8a198c | refs/heads/master | 2021-01-17T08:37:28.186171 | 2016-08-06T06:27:13 | 2016-08-06T06:27:13 | 65,066,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 342 | java | package realtimeinterfaceexamplepackage;
public class RealinterfaceExampleCaller {
public static void main(String[] args) {
BajajaPlatina platinaObject = new BajajaPlatina();
platinaObject.startBike();
platinaObject.accelerateBike();
platinaObject.stopBike();
platinaObject.getDimensions();
}
}
| [
"sidda005ait@gmail.com"
] | sidda005ait@gmail.com |
844d387c64d12dcbd3b2481e844e0411c02ded54 | 43939e894d56c54b1f2994475c0ab0c97f425f28 | /animation/src/main/java/com/example/animation/view/ProvinceView.java | ea8a042f62e5d098e9144858f9b2d2a043de40d8 | [] | no_license | xiaocui723/CustomViewLearn | 64b82afc0a3c58ec00f2ee05be060b0bfc963198 | d84e5088043874731808803047da53c8ca7f22cd | refs/heads/main | 2023-06-25T06:43:41.591484 | 2021-07-18T03:52:13 | 2021-07-18T03:52:13 | 333,454,384 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,482 | java | package com.example.animation.view;
import android.animation.TypeEvaluator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
import com.example.animation.Utils;
import java.util.Arrays;
import java.util.List;
public class ProvinceView extends View {
private static final List<String> provinces = Arrays.asList(
"北京市",
"天津市",
"上海市",
"重庆市",
"河北省",
"山西省",
"辽宁省",
"吉林省",
"黑龙江省",
"江苏省",
"浙江省",
"安徽省",
"福建省",
"江西省",
"山东省",
"河南省",
"湖北省",
"湖南省",
"广东省",
"海南省",
"四川省",
"贵州省",
"云南省",
"陕西省",
"甘肃省",
"青海省",
"台湾省",
"内蒙古自治区",
"广西壮族自治区",
"西藏自治区",
"宁夏回族自治区",
"新疆维吾尔自治区",
"香港特别行政区",
"澳门特别行政区"
);
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private String province = "北京市";
public ProvinceView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
paint.setTextSize(Utils.dp2px(50f));
paint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawText(province, getWidth() / 2f, getHeight() / 2f, paint);
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
invalidate();
}
public static class ProvinceEvaluator implements TypeEvaluator<String> {
@Override
public String evaluate(float fraction, String startValue, String endValue) {
int startIndex = provinces.indexOf(startValue);
int endIndex = provinces.indexOf(endValue);
int currentIndex = (int) (startIndex + (endIndex - startIndex) * fraction);
return provinces.get(currentIndex);
}
}
}
| [
"xiaocui723@163.com"
] | xiaocui723@163.com |
9432e63e65324a19580dff6f568c97facedb0c28 | b6cc4385389d792190518ba3673cf566c37b23a4 | /app/src/main/java/com/example/mycattonapplication/model/Remark.java | d938bf9fcb51955d63dab7b9cb0a55a7d56c4721 | [] | no_license | jacobeYang/cartoon | 5d6e9db04df2538b803b10cfc4b16b8f4ed648ac | a22149279ffcbf8b58d86aed8f92aae7bb65063f | refs/heads/master | 2020-07-05T18:35:52.608793 | 2019-08-16T13:15:20 | 2019-08-16T13:15:20 | 202,726,502 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,246 | java | package com.example.mycattonapplication.model;
import java.util.Date;
public class Remark {
private String id;
private String userId;
private User user;
private String cartoonId;
private Date time;
private String remarkContent;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
public String getCartoonId() {
return cartoonId;
}
public void setCartoonId(String cartoonId) {
this.cartoonId = cartoonId == null ? null : cartoonId.trim();
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getRemarkContent() {
return remarkContent;
}
public void setRemarkContent(String remarkContent) {
this.remarkContent = remarkContent == null ? null : remarkContent.trim();
}
} | [
"33113080+jacobeYang@users.noreply.github.com"
] | 33113080+jacobeYang@users.noreply.github.com |
29ad5f0747bac6de34df068909ae1b1fe9842399 | 7d0cce235c1d175f1785dd2b01d3a1b65d8e3b2d | /src/main/java/org/sid/controller/StorageController.java | 11eb1442a77501e50e0397051be86cc376f857fe | [] | no_license | ledemka/stock | 3a641cea84b4314041ea617b9256cfce08758179 | 9e13bf418f48bfb1bd5e32f84dc6090d65b6db4c | refs/heads/master | 2022-12-10T23:56:01.866006 | 2020-08-27T08:36:41 | 2020-08-27T08:36:41 | 287,254,196 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,887 | java | package org.sid.controller;
import java.util.List;
import java.util.stream.Collectors;
import org.sid.entities.InfoFichier;
import org.sid.services.impl.FilesStorageServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class StorageController {
private static final String URL ="http://localhost:8085/files/";
/*
* @Autowired FileStrorageService fileStorageService;
*/
FilesStorageServiceImpl fileStorageService = new FilesStorageServiceImpl();
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
String message = "";
fileStorageService.save(file);
try {
message = "upload avec succes:" + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(message);
} catch (Exception e) {
message = "Erreur lors de l'upload" + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
}
}
@GetMapping("/files")
public ResponseEntity<List<InfoFichier>> getListFiles() {
List<InfoFichier> fileInfos = fileStorageService.loadAll().map(path -> {
String filename = path.getFileName().toString();
/*
* String url = MvcUriComponentsBuilder
* .fromMethodName(StorageController.class,"getListFiles" ,
* path.getFileName().toString()).build().toString();
*/
String url = URL + filename;
return new InfoFichier(filename, url);
}).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.OK).body(fileInfos);
}
}
| [
"ledemka1@gmail.com"
] | ledemka1@gmail.com |
5a74770243ad8ecddafecd39629178a6d99e39ef | 8bdba494cfb40f883ebd1f069b7a7bc1a48ffe06 | /Android_QQ/QQ/src/com/qq/wifi/foregin/ProxyConnector.java | 32d6286dc30e0bc097efabbfdbc2903a705f7ab8 | [
"Apache-2.0"
] | permissive | XiGuangKai/MyStudyDemoProject | cd27208e343d0a146ff4b49e3e16b4de36f6e1db | 10e54ff2248282054a77c17d78e01610c39f5168 | refs/heads/master | 2021-07-24T14:04:37.689178 | 2017-11-24T09:54:25 | 2017-11-24T09:54:25 | 96,064,128 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 25,397 | java | /*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SwiFTP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.qq.wifi.foregin;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import org.json.JSONException;
import org.json.JSONObject;
import com.qq.util.RemoteUtil;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
public class ProxyConnector extends Thread {
public static final int IN_BUF_SIZE = 2048;
public static final String ENCODING = "UTF-8";
public static final int RESPONSE_WAIT_MS = 10000;
public static final int QUEUE_WAIT_MS = 20000;
public static final long UPDATE_USAGE_BYTES = 5000000;
public static final String PREFERRED_SERVER = "preferred_server"; //preferences
public static final int CONNECT_TIMEOUT = 5000;
private FTPServerService ftpServerService;
private JSONObject response = null;
private Thread responseWaiter = null;
private Queue<Thread> queuedRequestThreads = new LinkedList<Thread>();
private Socket commandSocket = null;
private OutputStream out = null;
private String hostname = null;
private InputStream inputStream = null;
private long proxyUsage = 0;
private State proxyState = State.DISCONNECTED;
private String prefix;
private String proxyMessage = null;
public enum State {CONNECTING, CONNECTED, FAILED, UNREACHABLE, DISCONNECTED};
//QuotaStats cachedQuotaStats = null; // quotas have been canceled for now
static final String USAGE_PREFS_NAME = "proxy_usage_data";
/* We establish a so-called "command session" to the proxy. New connections
* will be handled by creating addition control and data connections to the
* proxy. See proxy_protocol.txt and proxy_architecture.pdf for an
* explanation of how proxying works. Hint: it's complicated.
*/
public ProxyConnector(FTPServerService ftpServerService) {
this.ftpServerService = ftpServerService;
this.proxyUsage = getPersistedProxyUsage();
setProxyState(State.DISCONNECTED);
Globals.setProxyConnector(this);
}
public void run() {
setProxyState(State.CONNECTING);
try {
String candidateProxies[] = getProxyList();
for(String candidateHostname : candidateProxies) {
hostname = candidateHostname;
commandSocket = newAuthedSocket(hostname, Defaults.REMOTE_PROXY_PORT);
if(commandSocket == null) {
continue;
}
commandSocket.setSoTimeout(0); // 0 == forever
//commandSocket.setKeepAlive(true);
// Now that we have authenticated, we want to start the command session so we can
// be notified of pending control sessions.
JSONObject request = makeJsonRequest("start_command_session");
response = sendRequest(commandSocket, request);
if(response == null) {
continue; // try next server
}
if(!response.has("prefix")) {
continue; // try next server
}
prefix = response.getString("prefix");
response = null; // Indicate that response is free for other use
break; // breaking with commandSocket != null indicates success
}
if(commandSocket == null) {
setProxyState(State.UNREACHABLE);
return;
}
setProxyState(State.CONNECTED);
preferServer(hostname);
inputStream = commandSocket.getInputStream();
out = commandSocket.getOutputStream();
int numBytes;
byte[] bytes = new byte[IN_BUF_SIZE];
//spawnQuotaRequester().start();
while(true) {
numBytes = inputStream.read(bytes);
incrementProxyUsage(numBytes);
JSONObject incomingJson = null;
if(numBytes > 0) {
String responseString = new String(bytes, ENCODING);
incomingJson = new JSONObject(responseString);
if(incomingJson.has("action")) {
// If the incoming JSON object has an "action" field, then it is a
// request, and not a response
incomingCommand(incomingJson);
} else {
// If the incoming JSON object does not have an "action" field, then
// it is a response to a request we sent earlier.
// If there's an object waiting for a response, then that object
// will be referenced by responseWaiter.
if(responseWaiter != null) {
if(response != null) {
}
response = incomingJson;
responseWaiter.interrupt();
} else {
}
}
} else if(numBytes == 0) {
} else { // numBytes < 0
if(proxyState != State.DISCONNECTED) {
// Set state to FAILED unless this was an intentional
// socket closure.
setProxyState(State.FAILED);
}
break;
}
}
} catch (IOException e) {
setProxyState(State.FAILED);
} catch (JSONException e) {
setProxyState(State.FAILED);
} catch (Exception e) {
setProxyState(State.FAILED);
} finally {
Globals.setProxyConnector(null);
hostname = null;
persistProxyUsage();
}
}
// This function is used to spawn a new Thread that will make a request over the
// command thread. Since the main ProxyConnector thread handles the input
// request/response de-multiplexing, it cannot also make a request using the
// sendCmdSocketRequest, since sendCmdSocketRequest will block waiting for
// a response, but the same thread is expected to deliver the response.
// The short story is, if the main ProxyConnector command session thread wants to
// make a request, the easiest way is to spawn a new thread and have it call
// sendCmdSocketRequest in the same way as any other thread.
//private Thread spawnQuotaRequester() {
// return new Thread() {
// public void run() {
// getQuotaStats(false);
// }
// };
//}
/**
* Since we want devices to generally stick with the same proxy server,
* and we may want to explicitly redirect some devices to other servers,
* we have this mechanism to store a "preferred server" on the device.
*/
private void preferServer(String hostname) {
SharedPreferences prefs = Globals.getContext()
.getSharedPreferences(PREFERRED_SERVER, 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PREFERRED_SERVER, hostname);
editor.commit();
}
private String[] getProxyList() {
SharedPreferences prefs = Globals.getContext()
.getSharedPreferences(PREFERRED_SERVER, 0);
String preferred = prefs.getString(PREFERRED_SERVER, null);
String[] allProxies;
if(Defaults.release) {
allProxies = new String[] {
"c1.swiftp.org",
"c2.swiftp.org",
"c3.swiftp.org",
"c4.swiftp.org",
"c5.swiftp.org",
"c6.swiftp.org",
"c7.swiftp.org",
"c8.swiftp.org",
"c9.swiftp.org"};
} else {
//allProxies = new String[] {
// "cdev.swiftp.org"
//};
allProxies = new String[] {
"c1.swiftp.org",
"c2.swiftp.org",
"c3.swiftp.org",
"c4.swiftp.org",
"c5.swiftp.org",
"c6.swiftp.org",
"c7.swiftp.org",
"c8.swiftp.org",
"c9.swiftp.org"};
}
// We should randomly permute the server list in order to spread
// load between servers. Collections offers a shuffle() function
// that does this, so we'll convert to List and back to String[].
List<String> proxyList = Arrays.asList(allProxies);
Collections.shuffle(proxyList);
allProxies = proxyList.toArray(new String[] {}); // arg used for type
// Return preferred server first, followed by all others
if(preferred == null) {
return allProxies;
} else {
return RemoteUtil.concatStrArrays(
new String[] {preferred}, allProxies);
}
}
private boolean checkAndPrintJsonError(JSONObject json) throws JSONException {
if(json.has("error_code")) {
// The returned JSON object will have a field called "errorCode"
// if there was a problem executing our request.
StringBuilder s = new StringBuilder(
"Error in JSON response, code: ");
s.append(json.getString("error_code"));
if(json.has("error_string")) {
s.append(", string: ");
s.append(json.getString("error_string"));
}
// Obsolete: there's no authentication anymore
// Dev code to enable frequent database wipes. If we fail to login,
// remove our stored account info, causing a create_account action
// next time.
//if(!Defaults.release) {
// if(json.getInt("error_code") == 11) {
// myLog.l(Log.DEBUG, "Dev: removing secret due to login failure");
// removeSecret();
// }
//}
return true;
}
return false;
}
/**
* Reads our persistent storage, looking for a stored proxy authentication secret.
* @return The secret, if present, or null.
*/
//Obsolete, there's no authentication anymore
/*private String retrieveSecret() {
SharedPreferences settings = Globals.getContext().
getSharedPreferences(Defaults.getSettingsName(),
Defaults.getSettingsMode());
return settings.getString("proxySecret", null);
}*/
//Obsolete, there's no authentication anymore
/*private void storeSecret(String secret) {
SharedPreferences settings = Globals.getContext().
getSharedPreferences(Defaults.getSettingsName(),
Defaults.getSettingsMode());
Editor editor = settings.edit();
editor.putString("proxySecret", secret);
editor.commit();
}*/
//Obsolete, there's no authentication anymore
/*private void removeSecret() {
SharedPreferences settings = Globals.getContext().
getSharedPreferences(Defaults.getSettingsName(),
Defaults.getSettingsMode());
Editor editor = settings.edit();
editor.remove("proxySecret");
editor.commit();
}*/
private void incomingCommand(JSONObject json) {
try {
String action = json.getString("action");
if(action.equals("control_connection_waiting")) {
startControlSession(json.getInt("port"));
} else if(action.equals("prefer_server")) {
String host = json.getString("host"); // throws JSONException, fine
preferServer(host);
} else if(action.equals("message")) {
proxyMessage = json.getString("text");
//myLog.i("Got news from proxy server: \"" + proxyMessage + "\"");
FTPServerService.updateClients(); // UI update to show message
} else if(action.equals("noop")) {
//myLog.d("Proxy noop");
} else {
//myLog.l(Log.INFO, "Unsupported incoming action: " + action);
}
// If we're starting a control session register with ftpServerService
} catch (JSONException e){
//myLog.l(Log.INFO, "JSONException in proxy incomingCommand");
}
}
private void startControlSession(int port) {
Socket socket;
//myLog.d("Starting new proxy FTP control session");
socket = newAuthedSocket(hostname, port);
if(socket == null) {
//myLog.i("startControlSession got null authed socket");
return;
}
ProxyDataSocketFactory dataSocketFactory = new ProxyDataSocketFactory();
SessionThread thread = new SessionThread(socket, dataSocketFactory,
SessionThread.Source.PROXY);
thread.start();
ftpServerService.registerSessionThread(thread);
}
/**
* Connects an outgoing socket to the proxy and authenticates, creating an account
* if necessary.
*/
private Socket newAuthedSocket(String hostname, int port) {
if(hostname == null) {
//myLog.i("newAuthedSocket can't connect to null host");
return null;
}
JSONObject json = new JSONObject();
//String secret = retrieveSecret();
Socket socket;
OutputStream out = null;
InputStream in = null;
try {
//myLog.d("Opening proxy connection to " + hostname + ":" + port);
socket = new Socket();
socket.connect(new InetSocketAddress(hostname, port), CONNECT_TIMEOUT);
json.put("android_id", RemoteUtil.getAndroidId());
json.put("swiftp_version", RemoteUtil.getVersion());
json.put("action", "login");
out = socket.getOutputStream();
in = socket.getInputStream();
int numBytes;
out.write(json.toString().getBytes(ENCODING));
//myLog.l(Log.DEBUG, "Sent login request");
// Read and parse the server's response
byte[] bytes = new byte[IN_BUF_SIZE];
// Here we assume that the server's response will all be contained in
// a single read, which may be unsafe for large responses
numBytes = in.read(bytes);
if(numBytes == -1) {
//myLog.l(Log.INFO, "Proxy socket closed while waiting for auth response");
return null;
} else if (numBytes == 0) {
//myLog.l(Log.INFO, "Short network read waiting for auth, quitting");
return null;
}
json = new JSONObject(new String(bytes, 0, numBytes, ENCODING));
if(checkAndPrintJsonError(json)) {
return null;
}
//myLog.d("newAuthedSocket successful");
return socket;
} catch(Exception e) {
//myLog.i("Exception during proxy connection or authentication: " + e);
return null;
}
}
public void quit() {
setProxyState(State.DISCONNECTED);
try {
sendRequest(commandSocket, makeJsonRequest("finished")); // ignore reply
if(inputStream != null) {
//myLog.d("quit() closing proxy inputStream");
inputStream.close();
} else {
//myLog.d("quit() won't close null inputStream");
}
if(commandSocket != null) {
//myLog.d("quit() closing proxy socket");
commandSocket.close();
} else {
//myLog.d("quit() won't close null socket");
}
}
catch (IOException e) {}
catch(JSONException e) {}
persistProxyUsage();
Globals.setProxyConnector(null);
}
private JSONObject sendCmdSocketRequest(JSONObject json) {
try {
boolean queued;
synchronized(this) {
if(responseWaiter == null) {
responseWaiter = Thread.currentThread();
queued = false;
//myLog.d("sendCmdSocketRequest proceeding without queue");
} else if (!responseWaiter.isAlive()) {
// This code should never run. It is meant to recover from a situation
// where there is a thread that sent a proxy request but died before
// starting the subsequent request. If this is the case, the correct
// behavior is to run the next queued thread in the queue, or if the
// queue is empty, to perform our own request.
//myLog.l(Log.INFO, "Won't wait on dead responseWaiter");
if(queuedRequestThreads.size() == 0) {
responseWaiter = Thread.currentThread();
queued = false;
} else {
queuedRequestThreads.add(Thread.currentThread());
queuedRequestThreads.remove().interrupt(); // start queued thread
queued = true;
}
} else {
//myLog.d("sendCmdSocketRequest queueing thread");
queuedRequestThreads.add(Thread.currentThread());
queued = true;
}
}
// If a different thread has sent a request and is waiting for a response,
// then the current thread will be in a queue waiting for an interrupt
if(queued) {
// The current thread must wait until we are popped off the waiting queue
// and receive an interrupt()
boolean interrupted = false;
try {
//myLog.d("Queued cmd session request thread sleeping...");
Thread.sleep(QUEUE_WAIT_MS);
} catch (InterruptedException e) {
//myLog.l(Log.DEBUG, "Proxy request popped and ready");
interrupted = true;
}
if(!interrupted) {
//myLog.l(Log.INFO, "Timed out waiting on proxy queue");
return null;
}
}
// We have been popped from the wait queue if necessary, and now it's time
// to send the request.
try {
responseWaiter = Thread.currentThread();
byte[] outboundData = RemoteUtil.jsonToByteArray(json);
try {
out.write(outboundData);
} catch(IOException e) {
//myLog.l(Log.INFO, "IOException sending proxy request");
return null;
}
// Wait RESPONSE_WAIT_MS for a response from the proxy
boolean interrupted = false;
try {
// Wait for the main ProxyConnector thread to interrupt us, meaning
// that a response has been received.
//myLog.d("Cmd session request sleeping until response");
Thread.sleep(RESPONSE_WAIT_MS);
} catch (InterruptedException e) {
//myLog.d("Cmd session response received");
interrupted = true;
}
if(!interrupted) {
//myLog.l(Log.INFO, "Proxy request timed out");
return null;
}
// At this point, the main ProxyConnector thread will have stored
// our response in "JSONObject response".
//myLog.d("Cmd session response was: " + response);
return response;
}
finally {
// Make sure that when this request finishes, the next thread on the
// queue gets started.
synchronized(this) {
if(queuedRequestThreads.size() != 0) {
queuedRequestThreads.remove().interrupt();
}
}
}
} catch (JSONException e) {
//myLog.l(Log.INFO, "JSONException in sendRequest: " + e);
return null;
}
}
public JSONObject sendRequest(InputStream in, OutputStream out, JSONObject request)
throws JSONException {
try {
out.write(RemoteUtil.jsonToByteArray(request));
byte[] bytes = new byte[IN_BUF_SIZE];
int numBytes = in.read(bytes);
if(numBytes < 1) {
//myLog.i("Proxy sendRequest short read on response");
return null;
}
JSONObject response = RemoteUtil.byteArrayToJson(bytes);
if(response == null) {
//myLog.i("Null response to sendRequest");
}
if(checkAndPrintJsonError(response)) {
//myLog.i("Error response to sendRequest");
return null;
}
return response;
} catch (IOException e) {
//myLog.i("IOException in proxy sendRequest: " + e);
return null;
}
}
public JSONObject sendRequest(Socket socket, JSONObject request)
throws JSONException {
try {
if(socket == null) {
// The server is probably shutting down
// myLog.i("null socket in ProxyConnector.sendRequest()");
return null;
} else {
return sendRequest(socket.getInputStream(),
socket.getOutputStream(),
request);
}
} catch (IOException e) {
// myLog.i("IOException in proxy sendRequest wrapper: " + e);
return null;
}
}
public ProxyDataSocketInfo pasvListen() {
try {
// connect to proxy and authenticate
//myLog.d("Sending data_pasv_listen to proxy");
Socket socket = newAuthedSocket(this.hostname, Defaults.REMOTE_PROXY_PORT);
if(socket == null) {
//myLog.i("pasvListen got null socket");
return null;
}
JSONObject request = makeJsonRequest("data_pasv_listen");
JSONObject response = sendRequest(socket, request);
if(response == null) {
return null;
}
int port = response.getInt("port");
return new ProxyDataSocketInfo(socket, port);
} catch(JSONException e) {
//myLog.l(Log.INFO, "JSONException in pasvListen");
return null;
}
}
public Socket dataPortConnect(InetAddress clientAddr, int clientPort) {
/**
* This function is called by a ProxyDataSocketFactory when it's time to
* transfer some data in PORT mode (not PASV mode). We send a
* data_port_connect request to the proxy, containing the IP and port
* of the FTP client to which a connection should be made.
*/
try {
//myLog.d("Sending data_port_connect to proxy");
Socket socket = newAuthedSocket(this.hostname, Defaults.REMOTE_PROXY_PORT);
if(socket == null) {
//myLog.i("dataPortConnect got null socket");
return null;
}
JSONObject request = makeJsonRequest("data_port_connect");
request.put("address", clientAddr.getHostAddress());
request.put("port", clientPort);
JSONObject response = sendRequest(socket, request);
if(response == null) {
return null; // logged elsewhere
}
return socket;
} catch (JSONException e) {
//myLog.i("JSONException in dataPortConnect");
return null;
}
}
/**
* Given a socket returned from pasvListen(), send a data_pasv_accept request
* over the socket to the proxy, which should result in a socket that is ready
* for data transfer with the FTP client. Of course, this will only work if the
* FTP client connects to the proxy like it's supposed to. The client will have
* already been told to connect by the response to its PASV command.
*
* This should only be called from the onTransfer method of ProxyDataSocketFactory.
*
* @param socket A socket previously returned from ProxyConnector.pasvListen()
* @return true if the accept operation completed OK, otherwise false
*/
public boolean pasvAccept(Socket socket) {
try {
JSONObject request = makeJsonRequest("data_pasv_accept");
JSONObject response = sendRequest(socket, request);
if(response == null) {
return false; // error is logged elsewhere
}
if(checkAndPrintJsonError(response)) {
//myLog.i("Error response to data_pasv_accept");
return false;
}
// The proxy's response will be an empty JSON object on success
//myLog.d("Proxy data_pasv_accept successful");
return true;
} catch (JSONException e) {
//myLog.i("JSONException in pasvAccept: " + e);
return false;
}
}
public InetAddress getProxyIp() {
if(this.isAlive()) {
if(commandSocket.isConnected()) {
return commandSocket.getInetAddress();
}
}
return null;
}
private JSONObject makeJsonRequest(String action) throws JSONException {
JSONObject json = new JSONObject();
json.put("action", action);
return json;
}
/* Quotas have been canceled for now
public QuotaStats getQuotaStats(boolean canUseCached) {
if(canUseCached) {
if(cachedQuotaStats != null) {
myLog.d("Returning cachedQuotaStats");
return cachedQuotaStats;
} else {
myLog.d("Would return cached quota stats but none retrieved");
}
}
// If there's no cached quota stats, or if the called wants fresh stats,
// make a JSON request to the proxy, assuming the command session is open.
try {
JSONObject response = sendCmdSocketRequest(makeJsonRequest("check_quota"));
int used, quota;
if(response == null) {
myLog.w("check_quota got null response");
return null;
}
used = response.getInt("used");
quota = response.getInt("quota");
myLog.d("Got quota response of " + used + "/" + quota);
cachedQuotaStats = new QuotaStats(used, quota) ;
return cachedQuotaStats;
} catch (JSONException e) {
myLog.w("JSONException in getQuota: " + e);
return null;
}
}*/
// We want to track the total amount of data sent via the proxy server, to
// show it to the user and encourage them to donate.
void persistProxyUsage() {
if(proxyUsage == 0) {
return; // This shouldn't happen, but just for safety
}
SharedPreferences prefs = Globals.getContext().
getSharedPreferences(USAGE_PREFS_NAME, 0); // 0 == private
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(USAGE_PREFS_NAME, proxyUsage);
editor.commit();
//myLog.d("Persisted proxy usage to preferences");
}
long getPersistedProxyUsage() {
// This gets the last persisted value for bytes transferred through
// the proxy. It can be out of date since it doesn't include data
// transferred during the current session.
SharedPreferences prefs = Globals.getContext().
getSharedPreferences(USAGE_PREFS_NAME, 0); // 0 == private
return prefs.getLong(USAGE_PREFS_NAME, 0); // Default count of 0
}
public long getProxyUsage() {
// This gets the running total of all proxy usage, which may not have
// been persisted yet.
return proxyUsage;
}
public void incrementProxyUsage(long num) {
long oldProxyUsage = proxyUsage;
proxyUsage += num;
if(proxyUsage % UPDATE_USAGE_BYTES < oldProxyUsage % UPDATE_USAGE_BYTES) {
FTPServerService.updateClients();
persistProxyUsage();
}
}
public State getProxyState() {
return proxyState;
}
private void setProxyState(State state) {
proxyState = state;
//myLog.l(Log.DEBUG, "Proxy state changed to " + state, true);
FTPServerService.updateClients(); // UI update
}
static public String stateToString(State s) {
// Context ctx = Globals.getContext();
// switch(s) {
// case DISCONNECTED:
// return ctx.getString(R.string.pst_disconnected);
// case CONNECTING:
// return ctx.getString(R.string.pst_connecting);
// case CONNECTED:
// return ctx.getString(R.string.pst_connected);
// case FAILED:
// return ctx.getString(R.string.pst_failed);
// case UNREACHABLE:
// return ctx.getString(R.string.pst_unreachable);
// default:
// return ctx.getString(R.string.unknown);
// }
return "";
}
/**
* The URL to which users should point their FTP client.
*/
public String getURL() {
if(proxyState == State.CONNECTED) {
String username = Globals.getUsername();
if(username != null) {
return "ftp://" + prefix + "_" + username + "@" + hostname;
}
}
return "";
}
/** If the proxy sends a human-readable message, it can be retrieved by
* calling this function. Returns null if no message has been received.
*/
public String getProxyMessage() {
return proxyMessage;
}
}
| [
"wangdy11@WANGDY11XAM00G2.lenovo.com"
] | wangdy11@WANGDY11XAM00G2.lenovo.com |
6e81192769c34cd8b3367b9a854b87de4ae2dbe8 | abae510a63039e2eb1a636ec4bdbe6cfc27cd88d | /src/main/java/jp/xet/uncommons/mirage/valuetype/enumerated/AnnotationUtils.java | 031d29acc1e2fc182a2683d88e2d19630f0ec49d | [] | no_license | dai0304/uncommons-mirage | 976711c3b161fde3b96b9bd83103fb311e22d383 | 888194bc3bb747a0b2928adc8685468c50407472 | refs/heads/master | 2021-01-22T13:47:26.765371 | 2013-08-06T15:44:13 | 2013-08-06T15:44:13 | 2,621,342 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,849 | java | /*
* Copyright 2011 Daisuke Miyamoto.
* Created on 2013/08/07
*
* 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 jp.xet.uncommons.mirage.valuetype.enumerated;
import java.lang.annotation.Annotation;
/**
* TODO for daisuke
*
* @since TODO for daisuke
* @version $Id$
* @author daisuke
*/
public class AnnotationUtils {
/**
* Find a single {@link Annotation} of {@code annotationType} from the supplied {@link Class},
* traversing its interfaces and superclasses if no annotation can be found on the given class itself.
* <p>This method explicitly handles class-level annotations which are not declared as
* {@link java.lang.annotation.Inherited inherited} <i>as well as annotations on interfaces</i>.
* <p>The algorithm operates as follows: Searches for an annotation on the given class and returns
* it if found. Else searches all interfaces that the given class declares, returning the annotation
* from the first matching candidate, if any. Else proceeds with introspection of the superclass
* of the given class, checking the superclass itself; if no annotation found there, proceeds
* with the interfaces that the superclass declares. Recursing up through the entire superclass
* hierarchy if no match is found.
* @param clazz the class to look for annotations on
* @param annotationType the annotation class to look for
* @return the annotation found, or {@code null} if none found
*/
public static <A extends Annotation>A findAnnotation(Class<?> clazz, Class<A> annotationType) {
if (clazz == null) {
throw new NullPointerException("Class must not be null"); //$NON-NLS-1$
}
A annotation = clazz.getAnnotation(annotationType);
if (annotation != null) {
return annotation;
}
for (Class<?> ifc : clazz.getInterfaces()) {
annotation = findAnnotation(ifc, annotationType);
if (annotation != null) {
return annotation;
}
}
if (!Annotation.class.isAssignableFrom(clazz)) {
for (Annotation ann : clazz.getAnnotations()) {
annotation = findAnnotation(ann.annotationType(), annotationType);
if (annotation != null) {
return annotation;
}
}
}
Class<?> superClass = clazz.getSuperclass();
if (superClass == null || superClass.equals(Object.class)) {
return null;
}
return findAnnotation(superClass, annotationType);
}
}
| [
"dai.0304@gmail.com"
] | dai.0304@gmail.com |
8ccc77e6d01184f8642a3178b74f71e6ad51a95e | c3445da9eff3501684f1e22dd8709d01ff414a15 | /LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/bq/PEdorBLBackConfirmBL.java | c06b4ce42f5a294029a6a8b21b1f09d142ca2885 | [] | no_license | zhanght86/HSBC20171018 | 954403d25d24854dd426fa9224dfb578567ac212 | c1095c58c0bdfa9d79668db9be4a250dd3f418c5 | refs/heads/master | 2021-05-07T03:30:31.905582 | 2017-11-08T08:54:46 | 2017-11-08T08:54:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,493 | java | package com.sinosoft.lis.bq;
import org.apache.log4j.Logger;
import com.sinosoft.lis.db.LCContStateDB;
import com.sinosoft.lis.pubfun.GlobalInput;
import com.sinosoft.lis.pubfun.MMap;
import com.sinosoft.lis.pubfun.PubFun;
import com.sinosoft.lis.schema.LCContStateSchema;
import com.sinosoft.lis.schema.LPContStateSchema;
import com.sinosoft.lis.schema.LPEdorItemSchema;
import com.sinosoft.lis.vschema.LCContStateSet;
import com.sinosoft.lis.vschema.LPContStateSet;
import com.sinosoft.utility.CError;
import com.sinosoft.utility.CErrors;
import com.sinosoft.utility.Reflections;
import com.sinosoft.utility.SQLwithBindVariables;
import com.sinosoft.utility.VData;
/**
* <p>
* Title: Web业务系统
* </p>
* <p>
* Description: 保全- 保单质押银行贷款回退确认生效处理类
* </p>
* <p>
* Copyright: Copyright (c) 2005
* </p>
* <p>
* Company: Sinosoft
* </p>
*
* @author:liurx
* @version:1.0
* @CreateDate:2005-10-13
*/
public class PEdorBLBackConfirmBL implements EdorBack {
private static Logger logger = Logger.getLogger(PEdorBLBackConfirmBL.class);
/** 传入数据的容器 */
private VData mInputData = new VData();
/** 传出数据的容器 */
private VData mResult = new VData();
/** 数据操作字符串 */
private String mOperate;
/** 错误处理类 */
//public CErrors mErrors = new CErrors();
private MMap map = new MMap();
/** 全局基础数据 */
private GlobalInput mGlobalInput = new GlobalInput();
// 需要回退的保全项目
private LPEdorItemSchema mLPEdorItemSchema = new LPEdorItemSchema();
private String mCurrentDate = PubFun.getCurrentDate();
private String mCurrentTime = PubFun.getCurrentTime();
private String mContNo = "";
public PEdorBLBackConfirmBL() {
}
/**
* 数据提交的公共方法
*
* @param cInputData
* 传入的数据对象
* @param cOperate
* 数据操作字符串
* @return boolean
*/
public boolean submitData(VData cInputData, String cOperate) {
mInputData = (VData) cInputData.clone();
mOperate = cOperate;
if (!getInputData()) {
return false;
}
// 进行业务处理
if (!dealData()) {
return false;
}
// 准备往后台的数据
if (!prepareData()) {
return false;
}
return true;
}
/**
* 将外部传入的数据分解到本类的属性中
*
* @return boolean
*/
private boolean getInputData() {
try {
mGlobalInput = (GlobalInput) mInputData.getObjectByObjectName(
"GlobalInput", 0);
mLPEdorItemSchema = // 需要回退的保全项目
(LPEdorItemSchema) mInputData.getObjectByObjectName(
"LPEdorItemSchema", 0);
} catch (Exception e) {
e.printStackTrace();
CError.buildErr(this, "接收前台数据失败!");
return false;
}
if (mGlobalInput == null || mLPEdorItemSchema == null) {
CError.buildErr(this, "传入数据有误!");
return false;
}
return true;
}
/**
* 根据前面的输入数据,进行逻辑处理
*
* @return boolean
*/
private boolean dealData() {
logger.debug("=== 保单质押银行贷款回退确认生效 ===");
String tEndDate = PubFun.calDate(mLPEdorItemSchema.getEdorValiDate(),
-1, "D", null);
mContNo = mLPEdorItemSchema.getContNo();
if (mContNo == null || mContNo.trim().equals("")) {
CError.buildErr(this, "保单号为空!");
return false;
}
Reflections tRef = null;
// 查询贷款状态记录
LCContStateDB tLCContStateDB = new LCContStateDB();
LCContStateSet tLCContStateSet = new LCContStateSet();
String strsql = "select * from lccontstate where contno = '"
+ "?mContNo?"
+ "' "
+ " and statetype = 'BankLoan' and state = '1' and enddate is null "
+ " and startdate = '" + "?startdate?"
+ "'";
SQLwithBindVariables sbv1=new SQLwithBindVariables();
sbv1.sql(strsql);
sbv1.put("mContNo", mContNo);
sbv1.put("startdate", mLPEdorItemSchema.getEdorValiDate());
tLCContStateSet = tLCContStateDB.executeQuery(sbv1);
// 如果存在,则删除此记录,并备份到p表中
if (tLCContStateSet != null && tLCContStateSet.size() > 0) {
tRef = new Reflections();
LPContStateSet tLPContStateSet = new LPContStateSet();
for (int i = 1; i <= tLCContStateSet.size(); i++) {
LPContStateSchema tLPContStateSchema = new LPContStateSchema();
tRef.transFields(tLPContStateSchema, tLCContStateSet.get(i));
tLPContStateSchema.setEdorNo(mLPEdorItemSchema.getEdorNo());
tLPContStateSchema.setEdorType(mLPEdorItemSchema.getEdorType());
tLPContStateSet.add(tLPContStateSchema);
}
map.put(tLPContStateSet, "DELETE&INSERT");
map.put(tLCContStateSet, "DELETE");
}
// 查找旧状态数据,如果存在,则置其enddate为空,并将其备份到p表中
LCContStateDB oldLCContStateDB = new LCContStateDB();
LCContStateSet oldLCContStateSet = new LCContStateSet();
strsql = "select * from lccontstate where contno = '" + "?mContNo?" + "' "
+ " and statetype = 'BankLoan' and state = '0' "
+ " and enddate = '" + "?tEndDate?" + "'";
sbv1=new SQLwithBindVariables();
sbv1.sql(strsql);
sbv1.put("mContNo", mContNo);
sbv1.put("tEndDate", tEndDate);
oldLCContStateSet = oldLCContStateDB.executeQuery(sbv1);
if (oldLCContStateSet != null && oldLCContStateSet.size() > 0) {
tRef = new Reflections();
LPContStateSet oldLPContStateSet = new LPContStateSet();
LCContStateSet uptLCContStateSet = new LCContStateSet();
for (int i = 1; i <= oldLCContStateSet.size(); i++) {
LPContStateSchema tLPContStateSchema = new LPContStateSchema();
LCContStateSchema tLCContStateSchema = new LCContStateSchema();
tLCContStateSchema.setSchema(oldLCContStateSet.get(i));
tRef.transFields(tLPContStateSchema, oldLCContStateSet.get(i));
tLPContStateSchema.setEdorNo(mLPEdorItemSchema.getEdorNo());
tLPContStateSchema.setEdorType(mLPEdorItemSchema.getEdorType());
oldLPContStateSet.add(tLPContStateSchema);
tLCContStateSchema.setEndDate("");
uptLCContStateSet.add(tLCContStateSchema);
}
map.put(oldLPContStateSet, "DELETE&INSERT");
map.put(uptLCContStateSet, "UPDATE");
}
return true;
}
/**
* 准备往后层输出所需要的数据
*
* @return boolean
*/
private boolean prepareData() {
mResult.clear();
mResult.add(map);
return true;
}
/**
* 数据输出方法,供外界获取数据处理结果
*
* @return VData
*/
public VData getResult() {
return mResult;
}
public CErrors getErrors() {
return null;
}
}
| [
"dingzansh@sinosoft.com.cn"
] | dingzansh@sinosoft.com.cn |
b8e1f844ab5ea833a10cb03d4adbf4b3dea8765d | 9d065e356d9f73471b2cfb15992ecc12602a10cd | /src/com/ob/action/LoginClientAction.java | b6b6272855ad1665f4151fc0625983b443cad318 | [] | no_license | NEUCompiler/OnlineBanking | c69d617662a1c7266d0a7bf5ecdefb1a5dd743ae | dca76230a0230f5f507f19217c0019e2a3f44218 | refs/heads/master | 2021-01-19T05:34:44.241594 | 2016-07-23T14:14:18 | 2016-07-23T14:14:18 | 63,911,999 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,594 | java | package com.ob.action;
import java.util.Iterator;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ob.dao.ClientDAO;
import com.ob.dao.impl.ClientDaoImpl;
import com.ob.model.Client;
public class LoginClientAction extends SuperAction {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String login(){
//ClientDAO dao = new ClientDaoImpl();
//java.util.List user = dao.findByUserName(username);
//Iterator iter = user.iterator();
ApplicationContext c = new ClassPathXmlApplicationContext("applicationContext.xml");
SessionFactory sf = (SessionFactory) c.getBean("sessionFactory");
Session session = sf.openSession();
Query query = session.createQuery("from Client WHERE userName = ?");
query.setString(0, username+"");
java.util.List user = query.list();
Iterator iter = user.iterator();
if(user.isEmpty()){
return "FAIL";
} else {
Client client = (Client)iter.next();
if(client.getUserName().equals(username) && client.getUserPassword().equals(password)){
return "SUCCESS";
} else {
return "FAIL";
}
}
}
}
| [
"肖贺军@202.118.19.159"
] | 肖贺军@202.118.19.159 |
ddd0b31b0907e1500f291bf003f81116989f4add | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_7991115514e96e9ee354dbb722e4dbeed3efe5d4/SWF9Writer/28_7991115514e96e9ee354dbb722e4dbeed3efe5d4_SWF9Writer_s.java | 5dbd11166b37d8072a92320d9e0d7708b2207f48 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 39,949 | java | /*****************************************************************************
* SWF9Writer.java
* ****************************************************************************/
/* J_LZ_COPYRIGHT_BEGIN *******************************************************
* Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. *
* Use is subject to license terms. *
* J_LZ_COPYRIGHT_END *********************************************************/
package org.openlaszlo.compiler;
import org.openlaszlo.sc.ScriptCompiler;
import org.openlaszlo.server.LPS;
import org.openlaszlo.utils.ChainedException;
import org.openlaszlo.utils.FileUtils;
import org.openlaszlo.utils.ListFormat;
import org.openlaszlo.compiler.CompilationEnvironment;
import org.openlaszlo.compiler.ObjectWriter.ImportResourceError;
import org.openlaszlo.compiler.ObjectWriter.Resource;
import org.openlaszlo.iv.flash.api.text.*;
import org.openlaszlo.iv.flash.api.FlashDef;
import org.openlaszlo.media.*;
import java.io.*;
import java.util.*;
import java.lang.Math;
import java.lang.Character;
import org.jdom.Element;
// jgen 1.4
import java.awt.geom.Rectangle2D;
import org.apache.log4j.*;
/** Accumulates code, XML, and assets to a SWF9 object file.
*
* Properties documented in Compiler.getProperties.
*/
class SWF9Writer extends ObjectWriter {
// Accumulate script here, to pass to script compiler
protected PrintWriter scriptWriter = null;
protected StringWriter scriptBuffer = null;
private FontManager mFontManager = new FontManager();
private Map mDeviceFontTable = new HashMap();
/** Default font */
private Font mDefaultFont = null;
private String mDefaultFontName = null;
private String mDefaultFontFileName = null;
private String mDefaultBoldFontFileName = null;
private String mDefaultItalicFontFileName = null;
private String mDefaultBoldItalicFontFileName = null;
// TODO: [2003-12-08 bloch] need logic to set this to true
private boolean mDefaultFontUsedForMeasurement = false;
/** Height for generated advance (width) table */
public static final int DEFAULT_SIZE = 11;
/** Leading for text and input text */
private int mTextLeading = 2;
/** Logger */
protected static Logger mLogger = org.apache.log4j.Logger.getLogger(SWF9Writer.class);
SWF9Writer(Properties props, OutputStream stream,
CompilerMediaCache cache,
boolean importLibrary,
CompilationEnvironment env) {
super(props, stream, cache, importLibrary, env);
scriptBuffer = new StringWriter();
scriptWriter= new PrintWriter(scriptBuffer);
}
/**
* Sets the canvas for the app
*
* @param canvas
*
*/
void setCanvas(Canvas canvas, String canvasConstructor) {
scriptWriter.println(canvasConstructor);
// Pass canvas dimensions through the script compiler to the Flex compiler
mProperties.put("canvasWidth", Integer.toString(canvas.getWidth()));
mProperties.put("canvasHeight", Integer.toString(canvas.getHeight()));
}
void setCanvasDefaults(Canvas canvas, CompilerMediaCache mc) { };
public int addScript(String script) {
scriptWriter.println(script);
return script.length();
}
public void importPreloadResource(File fileName, String name)
throws ImportResourceError
{
}
public void importPreloadResource(String fileName, String name)
throws ImportResourceError
{
}
/** Import a multiframe resource into the current movie. Using a
* name that already exists clobbers the old resource (for now).
*/
public void importPreloadResource(List sources, String name, File parent)
throws ImportResourceError
{
}
/** Import a resource file into the current movie.
* Using a name that already exists clobbers the
* old resource (for now).
*
* @param fileName file name of the resource
* @param name name of the MovieClip/Sprite
* @throws CompilationError
*/
public void importResource(String fileName, String name)
throws ImportResourceError
{
importResource(new File(fileName), name);
}
public void importResource(File inputFile, String name)
throws ImportResourceError
{
// Moved this conversion from below.
try {
inputFile = inputFile.getCanonicalFile(); //better be ok if this does not yet exist. changed from getcanonicalPath to getCanonicalFile
} catch (java.io.IOException e) {
throw new ImportResourceError(inputFile.toString(), e, mEnv);
}
File[] sources;
List outsources = new ArrayList();
mLogger.debug("SWF9Writer: Importing resource: " + name);
if (inputFile.isDirectory()) {
//mLogger.debug("SWF9Writer Is directory: " + inputFile.toString());
sources = inputFile.listFiles();
//mLogger.debug("SWF9Writer: "+inputFile.toString()+" is a directory containing "+ sources.length +" files.");
for (int i = 0; i < sources.length; i++) {
// Construct path from directory and file names.
/* TODO: In theory, file resolution might get files that come from somewhere on the file system that doesn't match where
things will be on the server. Part of the root path may differ, and this File doesn't actually have to correspond
to a file on the server disk. Thus the path is reconstructed here.
That said, the current code isn't actually abstracting the path here.
This will actually come into play when the '2 phase' file resolution currently occuring is
compacted to a single phase. To do this, more resource and file descriptor information will have
to be maintained, either in a global table or using a more abstract path structure, or both.
For now I'll leave this as it is. [pga]
*/
String sFname = inputFile.toString() + File.separator + sources[i].getName();
File f = new File(sFname);
//mLogger.debug("SWF9Writer file: " + sFname + " is a file? " + f.isFile());
if (f.isFile()) {
outsources.add(sFname);
}
}
importResource(outsources, name, null);
return;
} else if (!inputFile.exists()) {
// This case is supposed to handle multiframe resources, as is the one above.
sources = FileUtils.matchPlusSuffix(inputFile);
for (int i = 0; i < sources.length; i++) {
// Construct path from directory and file names. (see comment above [pga])
File fDir = inputFile.getParentFile();
String sFname = fDir.toString() + File.separator + sources[i].getName();
File f = new File(sFname); //sources[i];
//mLogger.debug("SWF9Writer file: " + f.toString() + " is a file? " + f.isFile());
if (f.isFile()) {
outsources.add(f.toString());
}
}
importResource(outsources, name, null);
return;
}
// Conversion to canonical path was here.
org.openlaszlo.iv.flash.api.FlashDef def = null;
File dirfile = mEnv.getApplicationFile().getParentFile();
File appdir = dirfile != null ? dirfile : new File(".");
mLogger.debug("appdir is: " + appdir + ", LPS.HOME() is: "+ LPS.HOME());
//File appHomeParent = new File(LPS.getHomeParent());
String sHome=LPS.HOME();
// relativePath will perform canonicalization if needed, placing
// the current dir in front of a path fragment.
String arPath = FileUtils.relativePath(inputFile, appdir);
String srPath = FileUtils.relativePath(inputFile, sHome);
String relPath;
String pType;
if (arPath.length() <= srPath.length()) {
pType="ar";
relPath = arPath;
} else {
pType ="sr";
relPath = srPath;
}
// make it relative and watch out, it comes back canonicalized with forward slashes.
// Comparing to file.separator is wrong on the pc.
if (relPath.charAt(0) == '/') {
relPath = relPath.substring(1);
}
mLogger.debug("relPath is: "+relPath);
StringBuffer sbuf = new StringBuffer();
// [Embed(source="logo.swf")]
// public var logoClass:Class;
sbuf.append("#passthrough {\n");
String rpath;
try {
rpath = inputFile.getCanonicalPath();
// Fix Winblows pathname backslash lossage
rpath = rpath.replaceAll("\\\\", "/");
} catch (IOException e) {
throw new ImportResourceError(inputFile.toString(), e, mEnv);
}
sbuf.append("[Embed(source=\""+rpath+"\")]\n");
String assetClassname = "__embed_lzasset_" + name;
sbuf.append("var "+assetClassname+":Class;\n");
sbuf.append("}#\n");
sbuf.append("LzResourceLibrary." +
name + "={ptype: \"" + pType + "\", assetclass: "+assetClassname +", frames:[");
sbuf.append("'"+relPath+"'");
Resource res = (Resource)mResourceMap.get(inputFile.toString());
boolean oldRes = (res != null);
if (!oldRes) {
// Get the resource and put in the map
res = getResource(inputFile.toString(), name);
mLogger.debug("Building resource map; res: "+ res + ", relPath: "+ relPath +", fileName: "+inputFile.toString());
mResourceMap.put(relPath, res); //[pga] was fileName
def = res.getFlashDef();
def.setName(name);
} else {
def = res.getFlashDef();
// Add an element with 0 size, since it's already there.
Element elt = new Element("resource");
elt.setAttribute("name", name);
// elt.setAttribute("mime-type", MimeType.MP3);
elt.setAttribute("source", relPath); //[pga] was fileName
elt.setAttribute("filesize", "0");
mInfo.addContent(elt);
}
Rectangle2D b = def.getBounds();
if (b != null) {
sbuf.append("],width:" + (b.getWidth() / 20));
sbuf.append(",height:" + (b.getHeight() / 20));
} else {
// could be an mp3 resource
sbuf.append("]");
}
sbuf.append("};");
addScript(sbuf.toString());
}
public void importResource(List sources, String sResourceName, File parent)
{
writeResourceLibraryDescriptor(sources, sResourceName, parent);
}
/* Write resource descriptor library */
public void writeResourceLibraryDescriptor(List sources, String sResourceName, File parent)
{
mLogger.debug("Constructing resource library: " + sResourceName);
int width = 0;
int height = 0;
int fNum = 0;
File dirfile = mEnv.getApplicationFile().getParentFile();
String appdir = dirfile != null ? dirfile.getPath() : ".";
mLogger.debug("appdir is: " + appdir + ", LPS.HOME() is: "+ LPS.HOME());
//File appHomeParent = new File(LPS.getHomeParent());
String sHome=LPS.HOME();
boolean first = true;
// Initialize the temporary buffer.
StringBuffer sbuf= new StringBuffer("");
if (sources.isEmpty()) {
return;
}
ArrayList frameClassList = new ArrayList();
String pType;
String relPath;
String arPath;
String srPath;
sbuf.append("#passthrough {\n");
for (Iterator e = sources.iterator() ; e.hasNext() ;) {
File fFile = new File((String)e.next());
String rpath;
try {
rpath = fFile.getCanonicalPath();
// Fix Winblows pathname backslash lossage
rpath = rpath.replaceAll("\\\\", "/");
} catch (IOException err) {
throw new ImportResourceError(fFile.toString(), err, mEnv);
}
sbuf.append("[Embed(source=\""+rpath+"\")]\n");
String assetClassname = "__embed_lzasset_" + sResourceName+"_"+fNum;
sbuf.append("var "+assetClassname+":Class;\n");
frameClassList.add(assetClassname);
// Definition to add to the library (without stop)
Resource res = getMultiFrameResource(fFile.toString(), sResourceName, fNum);
int rw = res.getWidth();
int rh = res.getHeight();
if (rw > width) {
width = rw;
}
if (rh > height) {
height = rh;
}
fNum++;
}
sbuf.append("}#\n");
sbuf.append("LzResourceLibrary." + sResourceName + "={frames: ");
// enumerate the asset classes for each frame
sbuf.append("[");
String sep = "";
for (Iterator e = frameClassList.iterator() ; e.hasNext() ;) {
String assetclass = (String)e.next();
sbuf.append(sep+assetclass);
sep = ",";
}
sbuf.append("]");
mMultiFrameResourceSet.add(new Resource(sResourceName, width, height));
sbuf.append(",width:" + width);
sbuf.append(",height:" + height);
sbuf.append("};");
addScript(sbuf.toString());
}
public void close() throws IOException {
//Should we emit javascript or SWF?
//boolean emitScript = mEnv.isSWF9();
if (mCloseCalled) {
throw new IllegalStateException("SWF9Writer.close() called twice");
}
boolean debug = mProperties.getProperty("debug", "false").equals("true");
// This indicates whether the user's source code already manually invoked
// <debug> to create a debug window. If they didn't explicitly call for
// a debugger window, instantiate one now by passing 'true' to __LzDebug.startDebugWindow()
boolean makedebugwindow = !mEnv.getBooleanProperty(mEnv.USER_DEBUG_WINDOW);
// Bring up a debug window if needed.
if (debug && makedebugwindow) {
//addScript("__LzDebug.makeDebugWindow()");
}
// Put the canvas sprite on the 'stage'.
addScript("addChild(canvas.sprite)");
// Tell the canvas we're done loading.
addScript("canvas.initDone()");
try {
Properties props = (Properties)mProperties.clone();
scriptWriter.close();
byte[] objcode = ScriptCompiler.compileToByteArray(scriptBuffer.toString(), props);
InputStream input = new ByteArrayInputStream(objcode);
FileUtils.send(input, mStream);
} catch (org.openlaszlo.sc.CompilerException e) {
throw new CompilationError(e);
} catch (Exception e) {
throw new ChainedException(e);
}
mCloseCalled = true;
}
public void openSnippet(String url) throws IOException {
this.liburl = url;
}
public void closeSnippet() throws IOException {
// Callback to let library know we're done loading
addScript("LzLibrary.__LZsnippetLoaded('"+this.liburl+"')");
if (mCloseCalled) {
throw new IllegalStateException("SWF9Writer.close() called twice");
}
try {
Properties props = (Properties)mProperties.clone();
scriptWriter.close();
byte[] objcode = ScriptCompiler.compileToByteArray(scriptBuffer.toString(), props);
InputStream input = new ByteArrayInputStream(objcode);
mLogger.debug("compiled SWF9 code is "+new String(objcode));
FileUtils.send(input, mStream);
} catch (org.openlaszlo.sc.CompilerException e) {
throw new CompilationError(e);
} catch (Exception e) {
throw new ChainedException(e);
}
mCloseCalled = true;
}
FontManager getFontManager() {
return mFontManager;
}
public boolean isDeviceFont(String face) {
return (mDeviceFontTable.get(face) != null);
}
public void setDeviceFont(String face) {
mDeviceFontTable.put(face,"true");
}
public void setFontManager(FontManager fm) {
this.mFontManager = fm;
}
/**
* Import a font of a given style into the SWF we are writing.
*
* @param fileName filename for font in LZX
* @param face face name of font
* @param style style of font
*/
void importFontStyle(String fileName, String face, String style,
CompilationEnvironment env)
throws FileNotFoundException, CompilationError {
int styleBits = FontInfo.styleBitsFromString(style);
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="importing " + p[0] + " of style " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-1225", new Object[] {face, style})
);
FontInfo fontInfo = mEnv.getCanvas().getFontInfo();
boolean isDefault = false;
Font font = importFont(fileName, face, styleBits, false);
if (fontInfo.getName().equals(face)) {
if (styleBits == FontInfo.PLAIN) {
isDefault = true;
}
}
FontFamily family = mFontManager.getFontFamily(face, true);
switch (styleBits) {
case FontInfo.PLAIN:
if (family.plain != null) {
if (!isDefault) {
warn(env,
/* (non-Javadoc)
* @i18n.test
* @org-mes="Redefined plain style of font: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-1252", new Object[] {face})
);
}
}
family.plain = font; break;
case FontInfo.BOLD:
if (family.bold != null) {
warn(env,
/* (non-Javadoc)
* @i18n.test
* @org-mes="Redefined bold style of font: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-1265", new Object[] {face})
);
}
family.bold = font; break;
case FontInfo.ITALIC:
if (family.italic != null) {
warn(env,
/* (non-Javadoc)
* @i18n.test
* @org-mes="Redefined italic style of font: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-1277", new Object[] {face})
);
}
family.italic = font; break;
case FontInfo.BOLDITALIC:
if (family.bitalic != null) {
warn(env,
/* (non-Javadoc)
* @i18n.test
* @org-mes="Redefined bold italic style of font: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-1289", new Object[] {face})
);
}
family.bitalic = font; break;
default:
throw new ChainedException(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Unexpected style"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-1300")
);
}
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Adding font family: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-1502", new Object[] {face})
);
// TODO [ hqm 2008-01 ]
// Add entry to LFC font manager table. Do we actually need to add font metrics ?
// Does anybody use them?
StringBuffer sbuf = new StringBuffer();
sbuf.append("LzFontManager.addFont('" + face + "', " );
appendFont(sbuf, family.plain, family.getBounds(FontInfo.PLAIN));
sbuf.append(",");
appendFont(sbuf, family.bold, family.getBounds(FontInfo.BOLD));
sbuf.append(",");
appendFont(sbuf, family.italic, family.getBounds(FontInfo.ITALIC));
sbuf.append(",");
appendFont(sbuf, family.bitalic, family.getBounds(FontInfo.BOLDITALIC));
sbuf.append("\n)\n");
addScript(sbuf.toString());
}
/**
* Import a font into the SWF we are writing
*
* @param fileName name of font file
* @param face font name of font in LZX
*/
private Font importFont(String fileName, String face, int styleBits,
boolean replace)
throws FileNotFoundException, CompilationError {
if (isDeviceFont(face)) {
return Font.createDummyFont(face);
}
File fontFile = new File(fileName);
String fromType = FontType.fromName(fileName);
Font font = Font.createDummyFont(face);
long fileSize = FileUtils.getSize(fontFile);
// TODO [hqm 2008-01] Do we need to parse out the font metrics
// here? Code is in SWFWriter, I haven't copied it over here yet.
// That requires the JGenerator transcoder, which only does the first
// 256 chars in the font, kind of useless.
Element elt = new Element("font");
elt.setAttribute("face", face);
elt.setAttribute("style", FontInfo.styleBitsToString(styleBits, true));
elt.setAttribute("location", fontFile.getAbsolutePath());
elt.setAttribute("source", fileName);
elt.setAttribute("filesize", "" + fileSize);
mInfo.addContent(elt);
// Put in our face name
font.fontName = face;
// Clean out existing styles.
font.flags &= ~(Font.BOLD | Font.ITALIC);
// Write in ours.
if ((styleBits & FontInfo.BOLD) != 0) {
font.flags |= Font.BOLD;
}
if ((styleBits & FontInfo.ITALIC) != 0) {
font.flags |= Font.ITALIC;
}
/*
[Embed(mimeType='application/x-font', source='../assets/BELLB.TTF',
fontName='myBellFont', fontWeight='bold')]
// This variable is not used. It exists so that the compiler will link
// in the font.
private var myFontClass:Class;
*/
StringBuffer sbuf = new StringBuffer();
sbuf.append("#passthrough {\n");
String rpath;
File inputFile = fontFile;
try {
rpath = inputFile.getCanonicalPath();
// Fix Winblows pathname backslash lossage
rpath = rpath.replaceAll("\\\\", "/");
} catch (IOException e) {
throw new ImportResourceError(inputFile.toString(), e, mEnv);
}
String weight = FontInfo.styleBitsToString(styleBits, true);
sbuf.append("[Embed(mimeType='application/x-font', source='"+rpath+"', fontName='"+
face+"', fontWeight='"+weight+"')]\n");
String assetClassname = "__embed_lzfont_" + face;
sbuf.append("var "+assetClassname+":Class;\n");
sbuf.append("}#\n");
addScript(sbuf.toString());
return font;
}
/**
* @return height of fontinfo in pixels
* @param fontInfo
*/
double getFontHeight (FontInfo fontInfo) {
return fontHeight(getFontFromInfo(fontInfo));
}
/**
* @return lineheight which lfc LzInputText expects for a given fontsize
*/
double getLFCLineHeight (FontInfo fontInfo, int fontsize) {
return lfcLineHeight(getFontFromInfo(fontInfo), fontsize);
}
/**
* Convert em units to pixels, truncated to 2 decimal places.
* Slow float math... but simple code to read.
*
* @param units number of 1024 em units
* @return pixels
*/
private static double emUnitsToPixels(int units) {
int x = (100 * units * DEFAULT_SIZE) / 1024;
return (double)(x / 100.0);
}
/**
* Compute font bounding box
*
* @param font
*/
static double fontHeight(Font font) {
if (font == null) { return 0; }
double ascent = emUnitsToPixels(font.ascent);
double descent = emUnitsToPixels(font.descent);
double leading = emUnitsToPixels(font.leading);
double lineheight = ascent+descent+leading;
return lineheight;
}
/**
* Compute font bounding box
*
* @param font
*/
double lfcLineHeight(Font font, int fontsize) {
double ascent = emUnitsToPixels(font.ascent);
double descent = emUnitsToPixels(font.descent);
//double leading = emUnitsToPixels(font.leading);
double lineheight = mTextLeading + ((ascent+descent) * ((double)fontsize) / DEFAULT_SIZE);
return lineheight;
}
/**
* Appends font to actionscript string buffer
* @param actions string
* @param font font
*/
private static void appendFont(StringBuffer actions, Font font,
Rectangle2D[] bounds) {
final String newline = "\n ";
actions.append(newline);
if (font == null) {
actions.append("null");
return;
}
double ascent = emUnitsToPixels(font.ascent);
double descent = emUnitsToPixels(font.descent);
double leading = emUnitsToPixels(font.leading);
final String comma = ", ";
actions.append("{");
actions.append("ascent:");
actions.append(ascent);
actions.append(comma);
actions.append("descent:");
actions.append(descent);
actions.append(comma);
actions.append("leading:");
actions.append(leading);
actions.append(comma);
actions.append("advancetable:");
int idx, adv;
actions.append(newline);
actions.append("[");
// FIXME: [2003-03-19 bloch] We only support ANSI 8bit (up to
// 255) char encodings. We lose the higher characters is
// UNICODE and we don't support anything else.
for(int i = 0; i < 256; i++) {
idx = font.getIndex(i);
adv = font.getAdvanceValue(idx);
// Convert to pixels rounded to nearest 100th
double advance = emUnitsToPixels(adv);
actions.append(advance);
if (i != 255) {
actions.append(comma);
}
if (i%10 == 9) {
actions.append(newline);
}
}
actions.append("],");
actions.append(newline);
actions.append("lsbtable:");
actions.append(newline);
actions.append("[");
int m;
int max;
int adj;
for(int i = 0; i < 256; i++) {
idx = font.getIndex(i);
try {
m = (int)bounds[idx].getMinX();
//max = (int)bounds[idx].getMaxX();
} catch (Exception e) {
m = 0;
//max = 0;
}
adv = font.getAdvanceValue(idx);
adj = m;
if (adj < 0) adj = 0;
/* The following makes the lsb bigger
but is strictly wrong */
/*max = max - adv;
if (max < 0) max = 0;
if (max > adj) {
adj = max;
}*/
// Convert to pixels rounded to nearest 100th
double lsb = emUnitsToPixels(adj);
actions.append(lsb);
if (i != 255) {
actions.append(comma);
}
if (i%10 == 9) {
actions.append(newline);
}
}
actions.append("],");
actions.append(newline);
actions.append("rsbtable:");
actions.append(newline);
actions.append("[");
for(int i = 0; i < 256; i++) {
idx = font.getIndex(i);
try {
m = (int)bounds[idx].getMaxX();
} catch (Exception e) {
m = 0;
}
adv = font.getAdvanceValue(idx);
adj = m - adv;
if (adj < 0) adj = 0;
// Convert to pixels rounded to nearest 100th
double rsb = emUnitsToPixels(adj);
actions.append(rsb);
if (i != 255) {
actions.append(comma);
}
if (i%10 == 9) {
actions.append(newline);
}
}
actions.append("]}");
}
/**
* @return font given a font info
*/
private Font getFontFromInfo(FontInfo fontInfo) {
// This will bring in the default bold ofnt if it's not here yet
checkFontExists(fontInfo);
String fontName = fontInfo.getName();
FontFamily family = mFontManager.getFontFamily(fontName);
String style = fontInfo.getStyle();
if (family == null) {
return null;
/*
throw new CompilationError("Font '" + fontName +
"' used but not defined");
*/
}
Font font = family.getStyle(fontInfo.styleBits);
if (font == null) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Font '" + p[0] + "' style ('" + p[1] + "') used but not defined"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-2089", new Object[] {fontName, style})
);
}
return font;
}
/**
* @return true if the font exists
*
* If this is the default bold font and it hasn't been
* declared, import it.
*/
boolean checkFontExists(FontInfo fontInfo) {
// Bulletproofing...
if (fontInfo.getName() == null) {
return false;
}
boolean a = mFontManager.checkFontExists(fontInfo);
if (a) {
return a;
}
if (fontInfo.getName().equals(mDefaultFontName) &&
fontInfo.styleBits == FontInfo.PLAIN) {
try {
File f = mEnv.resolve(mDefaultFontFileName, null);
importFontStyle(f.getAbsolutePath(), mDefaultFontName, "plain", mEnv);
} catch (FileNotFoundException fnfe) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="default font " + p[0] + " missing " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-2125", new Object[] {mDefaultFontFileName, fnfe})
);
}
return true;
}
if (fontInfo.getName().equals(mDefaultFontName) &&
fontInfo.styleBits == FontInfo.BOLD) {
try {
File f = mEnv.resolve(mDefaultBoldFontFileName, null);
importFontStyle(f.getAbsolutePath(), mDefaultFontName, "bold", mEnv);
} catch (FileNotFoundException fnfe) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="default bold font " + p[0] + " missing " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-2143", new Object[] {mDefaultBoldFontFileName, fnfe})
);
}
return true;
}
if (fontInfo.getName().equals(mDefaultFontName) &&
fontInfo.styleBits == FontInfo.ITALIC) {
try {
File f = mEnv.resolve(mDefaultItalicFontFileName, null);
importFontStyle(f.getAbsolutePath(), mDefaultFontName, "italic", mEnv);
} catch (FileNotFoundException fnfe) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="default italic font " + p[0] + " missing " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-2161", new Object[] {mDefaultItalicFontFileName, fnfe})
);
}
return true;
}
if (fontInfo.getName().equals(mDefaultFontName) &&
fontInfo.styleBits == FontInfo.BOLDITALIC) {
try {
File f = mEnv.resolve(mDefaultBoldItalicFontFileName, null);
importFontStyle(f.getAbsolutePath(), mDefaultFontName, "bold italic", mEnv);
} catch (FileNotFoundException fnfe) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="default bold italic font " + p[0] + " missing " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
SWFWriter.class.getName(),"051018-2179", new Object[] {mDefaultBoldItalicFontFileName, fnfe})
);
}
return true;
}
return false;
}
void addPreloaderScript(String script) { } ;
void addPreloader(CompilationEnvironment env) { } ;
public void importBaseLibrary(String library, CompilationEnvironment env) {
env.warn("SWF9Writer does not implement importBaseLibrary");
}
public String importClickResource(File file) throws ImportResourceError {
mEnv.warn( "clickregion not implemented by SWF9Writer");
return("SWF9Writer clickregions not implemented");
}
/** Get a resource descriptor without resource content.
*
* @param name name of the resource
* @param fileName file name of the resource
* @param stop include stop action if true
*
*/
// TODO: Required for performance improvement. So far not differentiated from ObjectWriter version.
protected Resource getResource(String fileName, String name, boolean stop)
throws ImportResourceError
{
try {
String inputMimeType = MimeType.fromExtension(fileName);
if (!Transcoder.canTranscode(inputMimeType, MimeType.SWF)
&& !inputMimeType.equals(MimeType.SWF)) {
inputMimeType = Transcoder.guessSupportedMimeTypeFromContent(fileName);
if (inputMimeType == null || inputMimeType.equals("")) {
throw new ImportResourceError(fileName, new Exception(
/* (non-Javadoc)
* @i18n.test
* @org-mes="bad mime type"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
ObjectWriter.class.getName(),"051018-549")
), mEnv);
}
}
// No need to get these from the cache since they don't need to be
// transcoded and we usually keep the cmcache on disk.
if (inputMimeType.equals(MimeType.SWF)) {
long fileSize = FileUtils.getSize(new File(fileName));
Element elt = new Element("resource");
elt.setAttribute("name", name);
elt.setAttribute("mime-type", inputMimeType);
elt.setAttribute("source", fileName);
elt.setAttribute("filesize", "" + fileSize);
mInfo.addContent(elt);
return importSWF(fileName, name, false);
}
// TODO: [2002-12-3 bloch] use cache for mp3s; for now we're skipping it
// arguably, this is a fixme
if (inputMimeType.equals(MimeType.MP3) ||
inputMimeType.equals(MimeType.XMP3)) {
return importMP3(fileName, name);
}
File inputFile = new File(fileName);
File outputFile = mCache.transcode(inputFile, inputMimeType, MimeType.SWF);
mLogger.debug(
/* (non-Javadoc)
* @i18n.test
* @org-mes="importing: " + p[0] + " as " + p[1] + " from cache; size: " + p[2]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
ObjectWriter.class.getName(),"051018-584", new Object[] {fileName, name, new Long(outputFile.length())})
);
long fileSize = FileUtils.getSize(outputFile);
Element elt = new Element("resource");
elt.setAttribute("name", name);
elt.setAttribute("mime-type", inputMimeType);
elt.setAttribute("source", fileName);
elt.setAttribute("filesize", "" + fileSize);
mInfo.addContent(elt);
return importSWF(outputFile.getPath(), name, stop);
} catch (Exception e) {
mLogger.error(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Can't get resource " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
ObjectWriter.class.getName(),"051018-604", new Object[] {fileName})
);
throw new ImportResourceError(fileName, e, mEnv);
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
00b3c26ba8f6d8b20c625eec3e7a2e09e6d94fce | 78ca5f9f9006dbe8aeec8edddef266d7471c6d1c | /src/main/java/com/sharingplatform/datagovernance/query/TaskResult.java | 9bbd8ee97a6dd452fd29280f083984753b584325 | [] | no_license | kingqueenly/sharing-platform-backend | 14d3854760305eafc4d6254181732bfd6684a8ae | a348fa94280d58fe2ea2019670511c573b216664 | refs/heads/master | 2020-07-14T23:40:29.160122 | 2017-08-31T15:31:46 | 2017-08-31T15:31:46 | 94,300,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,071 | java | package com.sharingplatform.datagovernance.query;
import java.util.Date;
/**
* Created by AMC on 2017/8/18.
*/
public class TaskResult {
private Long id;
private Long flowInstanceId;
private String taskKey;
private String stepKey;
private String applicationName;
private String userId;
private Date createTime;
private Date updateTime;
private Long applicationFormId;
private String status;
private String comments;
private String buttonName;
private Date applicationSubmitTime;
private String applicant;
private Long prevFormId;
public Long getPrevFormId() {
return prevFormId;
}
public void setPrevFormId(Long prevFormId) {
this.prevFormId = prevFormId;
}
public Date getApplicationSubmitTime() {
return applicationSubmitTime;
}
public void setApplicationSubmitTime(Date applicationSubmitTime) {
this.applicationSubmitTime = applicationSubmitTime;
}
public String getApplicant() {
return applicant;
}
public void setApplicant(String applicant) {
this.applicant = applicant;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getFlowInstanceId() {
return flowInstanceId;
}
public void setFlowInstanceId(Long flowInstanceId) {
this.flowInstanceId = flowInstanceId;
}
public String getTaskKey() {
return taskKey;
}
public void setTaskKey(String taskKey) {
this.taskKey = taskKey;
}
public String getStepKey() {
return stepKey;
}
public void setStepKey(String stepKey) {
this.stepKey = stepKey;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Long getApplicationFormId() {
return applicationFormId;
}
public void setApplicationFormId(Long applicationFormId) {
this.applicationFormId = applicationFormId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getButtonName() {
return buttonName;
}
public void setButtonName(String buttonName) {
this.buttonName = buttonName;
}
}
| [
"kui.li@accenture.com"
] | kui.li@accenture.com |
8584ab95b95c27722c424254b6ccc78e4de7f540 | f222dbc0c70f2372179c01ca9e6f7310ab624d63 | /store/src/java/com/zimbra/cs/util/SpamExtract.java | 42372c5698171723c27f0e7d8bce04762616e16b | [] | no_license | Prashantsurana/zm-mailbox | 916480997851f55d4b2de1bc8034c2187ed34dda | 2fb9a0de108df9c2cd530fe3cb2da678328b819d | refs/heads/develop | 2021-01-23T01:07:59.215154 | 2017-05-26T09:18:30 | 2017-05-26T10:36:04 | 85,877,552 | 1 | 0 | null | 2017-03-22T21:23:04 | 2017-03-22T21:23:04 | null | UTF-8 | Java | false | false | 26,555 | java | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Synacor, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.util;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Charsets;
import com.google.common.io.Closeables;
import com.zimbra.common.account.Key.AccountBy;
import com.zimbra.common.httpclient.HttpClientUtil;
import com.zimbra.common.localconfig.LC;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.AccountConstants;
import com.zimbra.common.soap.AdminConstants;
import com.zimbra.common.soap.Element;
import com.zimbra.common.soap.MailConstants;
import com.zimbra.common.soap.SoapFaultException;
import com.zimbra.common.soap.SoapHttpTransport;
import com.zimbra.common.util.BufferStream;
import com.zimbra.common.util.ByteUtil;
import com.zimbra.common.util.CliUtil;
import com.zimbra.common.util.Log;
import com.zimbra.common.util.LogFactory;
import com.zimbra.common.util.ZimbraCookie;
import com.zimbra.common.zmime.ZMimeMessage;
import com.zimbra.common.zmime.ZSharedFileInputStream;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.mailbox.MailItem;
import com.zimbra.cs.mailbox.MailItem.UnderlyingData;
import com.zimbra.cs.service.formatter.ArchiveFormatter.ArchiveInputEntry;
import com.zimbra.cs.service.formatter.ArchiveFormatter.ArchiveInputStream;
import com.zimbra.cs.service.formatter.TarArchiveInputStream;
import com.zimbra.cs.service.mail.ItemAction;
import com.zimbra.cs.service.util.ItemData;
public class SpamExtract {
private static Log LOG = LogFactory.getLog(SpamExtract.class);
private static Options options = new Options();
private static boolean verbose = false;
private static int BATCH_SIZE = 25;
private static int SLEEP_TIME = 100;
static {
options.addOption("s", "spam", false, "extract messages from configured spam mailbox");
options.addOption("n", "notspam", false, "extract messages from configured notspam mailbox");
options.addOption("m", "mailbox", true, "extract messages from specified mailbox");
options.addOption("d", "delete", false, "delete extracted messages (default is to keep)");
options.addOption("o", "outdir", true, "directory to store extracted messages");
options.addOption("a", "admin", true, "admin user name for auth (default is zimbra_ldap_userdn)");
options.addOption("p", "password", true, "admin password for auth (default is zimbra_ldap_password)");
options.addOption("u", "url", true, "admin SOAP service url (default is target mailbox's server's admin service port)");
options.addOption("q", "query", true, "search query whose results should be extracted (default is in:inbox)");
options.addOption("r", "raw", false, "extract raw message (default: gets message/rfc822 attachments)");
options.addOption("h", "help", false, "show this usage text");
options.addOption("D", "debug", false, "enable debug level logging");
options.addOption("v", "verbose", false, "be verbose while running");
}
private static void usage(String errmsg) {
if (errmsg != null) {
LOG.error(errmsg);
}
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("zmspamextract [options] ",
"where [options] are one of:", options,
"SpamExtract retrieve messages that may have been marked as spam or not spam in the Zimbra Web Client.");
System.exit((errmsg == null) ? 0 : 1);
}
private static CommandLine parseArgs(String args[]) {
CommandLineParser parser = new GnuParser();
CommandLine cl = null;
try {
cl = parser.parse(options, args);
} catch (ParseException pe) {
usage(pe.getMessage());
}
if (cl.hasOption("h")) {
usage(null);
}
return cl;
}
public static void main(String[] args) throws ServiceException, HttpException, SoapFaultException, IOException {
CommandLine cl = parseArgs(args);
if (cl.hasOption('D')) {
CliUtil.toolSetup("DEBUG");
} else {
CliUtil.toolSetup("INFO");
}
if (cl.hasOption('v')) {
verbose = true;
}
boolean optDelete = cl.hasOption('d');
if (!cl.hasOption('o')) {
usage("must specify directory to extract messages to");
}
String optDirectory = cl.getOptionValue('o');
File outputDirectory = new File(optDirectory);
if (!outputDirectory.exists()) {
LOG.info("Creating directory: " + optDirectory);
outputDirectory.mkdirs();
if (!outputDirectory.exists()) {
LOG.error("could not create directory " + optDirectory);
System.exit(2);
}
}
String optAdminUser;
if (cl.hasOption('a')) {
optAdminUser = cl.getOptionValue('a');
} else {
optAdminUser = LC.zimbra_ldap_user.value();
}
String optAdminPassword;
if (cl.hasOption('p')) {
optAdminPassword = cl.getOptionValue('p');
} else {
optAdminPassword = LC.zimbra_ldap_password.value();
}
String optQuery = "in:inbox";
if (cl.hasOption('q')) {
optQuery = cl.getOptionValue('q');
}
Account account = getAccount(cl);
if (account == null) {
System.exit(1);
}
boolean optRaw = cl.hasOption('r');
if (verbose) {
LOG.info("Extracting from account " + account.getName());
}
Server server = Provisioning.getInstance().getServer(account);
String optAdminURL;
if (cl.hasOption('u')) {
optAdminURL = cl.getOptionValue('u');
} else {
optAdminURL = getSoapURL(server, true);
}
String adminAuthToken = getAdminAuthToken(optAdminURL, optAdminUser, optAdminPassword);
String authToken = getDelegateAuthToken(optAdminURL, account, adminAuthToken);
BATCH_SIZE = Provisioning.getInstance().getLocalServer().getAntispamExtractionBatchSize();
SLEEP_TIME = Provisioning.getInstance().getLocalServer().getAntispamExtractionBatchDelay();
extract(authToken, account, server, optQuery, outputDirectory, optDelete, optRaw);
}
private static void extract(String authToken, Account account, Server server, String query, File outdir, boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException {
String soapURL = getSoapURL(server, false);
URL restURL = getServerURL(server, false);
HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr
HttpState state = new HttpState();
GetMethod gm = new GetMethod();
gm.setFollowRedirects(true);
Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1, false);
state.addCookie(authCookie);
hc.setState(state);
hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(), Protocol.getProtocol(restURL.getProtocol()));
gm.getParams().setSoTimeout(60000);
if (verbose) {
LOG.info("Mailbox requests to: " + restURL);
}
SoapHttpTransport transport = new SoapHttpTransport(soapURL);
transport.setRetryCount(1);
transport.setTimeout(0);
transport.setAuthToken(authToken);
int totalProcessed = 0;
boolean haveMore = true;
int offset = 0;
while (haveMore) {
Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST);
searchReq.addElement(MailConstants.A_QUERY).setText(query);
searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, MailItem.Type.MESSAGE.toString());
searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset);
searchReq.addAttribute(MailConstants.A_LIMIT, BATCH_SIZE);
try {
if (LOG.isDebugEnabled()) {
LOG.debug(searchReq.prettyPrint());
}
Element searchResp = transport.invoke(searchReq, false, true, account.getId());
if (LOG.isDebugEnabled()) {
LOG.debug(searchResp.prettyPrint());
}
StringBuilder deleteList = new StringBuilder();
List<String> ids = new ArrayList<String>();
for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) {
offset++;
Element e = iter.next();
String mid = e.getAttribute(MailConstants.A_ID);
if (mid == null) {
LOG.warn("null message id SOAP response");
continue;
}
LOG.debug("adding id %s", mid);
ids.add(mid);
if (ids.size() >= BATCH_SIZE || !iter.hasNext()) {
StringBuilder path = new StringBuilder("/service/user/" + account.getName() + "/?fmt=tgz&list=" + StringUtils.join(ids, ","));
LOG.debug("sending request for path %s", path.toString());
List<String> extractedIds = extractMessages(hc, gm, path.toString(), outdir, raw);
if (ids.size() > extractedIds.size()) {
ids.removeAll(extractedIds);
LOG.warn("failed to extract %s", ids);
}
for (String id : extractedIds) {
deleteList.append(id).append(',');
}
ids.clear();
}
totalProcessed++;
}
haveMore = false;
String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE);
if (more != null && more.length() > 0) {
try {
int m = Integer.parseInt(more);
if (m > 0) {
haveMore = true;
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
}
}
} catch (NumberFormatException nfe) {
LOG.warn("more flag from server not a number: " + more, nfe);
}
}
if (delete && deleteList.length() > 0) {
deleteList.deleteCharAt(deleteList.length()-1); // -1 removes trailing comma
Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST);
Element action = msgActionReq.addElement(MailConstants.E_ACTION);
action.addAttribute(MailConstants.A_ID, deleteList.toString());
action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE);
if (LOG.isDebugEnabled()) {
LOG.debug(msgActionReq.prettyPrint());
}
Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId());
if (LOG.isDebugEnabled()) {
LOG.debug(msgActionResp.prettyPrint());
}
offset = 0; //put offset back to 0 so we always get top N messages even after delete
}
} finally {
gm.releaseConnection();
}
}
LOG.info("Total messages processed: " + totalProcessed);
}
private static Session mJMSession;
private static String mOutputPrefix;
static {
Properties props = new Properties();
props.setProperty("mail.mime.address.strict", "false");
mJMSession = Session.getInstance(props);
mOutputPrefix = Long.toHexString(System.currentTimeMillis());
}
private static int mExtractIndex;
private static final int MAX_BUFFER_SIZE = 10 * 1024 * 1024;
private static List<String> extractMessages(HttpClient hc, GetMethod gm, String path, File outdir, boolean raw) throws HttpException, IOException {
List<String> extractedIds = new ArrayList<String>();
gm.setPath(path);
if (LOG.isDebugEnabled()) {
LOG.debug("Fetching " + path);
}
HttpClientUtil.executeMethod(hc, gm);
if (gm.getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("HTTP GET failed: " + gm.getPath() + ": " + gm.getStatusCode() + ": " + gm.getStatusText());
}
ArchiveInputStream tgzStream = null;
try {
tgzStream = new TarArchiveInputStream(new GZIPInputStream(gm.getResponseBodyAsStream()), Charsets.UTF_8.name());
ArchiveInputEntry entry = null;
while ((entry = tgzStream.getNextEntry()) != null) {
LOG.debug("got entry name %s", entry.getName());
if (entry.getName().endsWith(".meta")) {
ItemData itemData = new ItemData(readArchiveEntry(tgzStream, entry));
UnderlyingData ud = itemData.ud;
entry = tgzStream.getNextEntry(); //.meta always followed by .eml
if (raw) {
// Write the message as-is.
File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++);
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
byte[] data = readArchiveEntry(tgzStream, entry);
ByteUtil.copy(new ByteArrayInputStream(data), true, os, false);
if (verbose) {
LOG.info("Wrote: " + file);
}
extractedIds.add(ud.id + "");
} catch (java.io.IOException e) {
String fileName = outdir + "/" + mOutputPrefix + "-" + mExtractIndex;
LOG.error("Cannot write to " + fileName, e);
} finally {
if (os != null) {
os.close();
}
}
} else {
// Write the attached message to the output directory.
BufferStream buffer = new BufferStream(entry.getSize(), MAX_BUFFER_SIZE);
buffer.setSequenced(false);
MimeMessage mm = null;
InputStream fis = null;
try {
byte[] data = readArchiveEntry(tgzStream, entry);
ByteUtil.copy(new ByteArrayInputStream(data), true, buffer, false);
if (buffer.isSpooled()) {
fis = new ZSharedFileInputStream(buffer.getFile());
mm = new ZMimeMessage(mJMSession, fis);
} else {
mm = new ZMimeMessage(mJMSession, buffer.getInputStream());
}
writeAttachedMessages(mm, outdir, entry.getName());
extractedIds.add(ud.id + "");
} catch (MessagingException me) {
LOG.warn("exception occurred fetching message", me);
} finally {
ByteUtil.closeStream(fis);
}
}
}
}
} finally {
Closeables.closeQuietly(tgzStream);
}
return extractedIds;
}
private static byte[] readArchiveEntry(ArchiveInputStream ais, ArchiveInputEntry aie)
throws IOException {
if (aie == null) {
return null;
}
int dsz = (int) aie.getSize();
byte[] data;
if (dsz == 0) {
return null;
} else if (dsz == -1) {
data = ByteUtil.getContent(ais.getInputStream(), -1, false);
} else {
data = new byte[dsz];
if (ais.read(data, 0, dsz) != dsz) {
throw new IOException("archive read err");
}
}
return data;
}
private static void writeAttachedMessages(MimeMessage mm, File outdir, String msgUri)
throws IOException, MessagingException {
// Not raw - ignore the spam report and extract messages that are in attachments...
if (!(mm.getContent() instanceof MimeMultipart)) {
LOG.warn("Spam/notspam messages must have attachments (skipping " + msgUri + ")");
return;
}
MimeMultipart mmp = (MimeMultipart)mm.getContent();
int nAttachments = mmp.getCount();
boolean foundAtleastOneAttachedMessage = false;
for (int i = 0; i < nAttachments; i++) {
BodyPart bp = mmp.getBodyPart(i);
if (!bp.isMimeType("message/rfc822")) {
// Let's ignore all parts that are not messages.
continue;
}
foundAtleastOneAttachedMessage = true;
Part msg = (Part) bp.getContent(); // the actual message
File file = new File(outdir, mOutputPrefix + "-" + mExtractIndex++);
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
if (msg instanceof MimeMessage) {
//bug 74435 clone into newMsg so our parser has a chance to handle headers which choke javamail
ZMimeMessage newMsg = new ZMimeMessage((MimeMessage) msg);
newMsg.writeTo(os);
} else {
msg.writeTo(os);
}
} finally {
os.close();
}
if (verbose) LOG.info("Wrote: " + file);
}
if (!foundAtleastOneAttachedMessage) {
String msgid = mm.getHeader("Message-ID", " ");
LOG.warn("message uri=" + msgUri + " message-id=" + msgid + " had no attachments");
}
}
public static URL getServerURL(Server server, boolean admin) throws ServiceException {
String host = server.getAttr(Provisioning.A_zimbraServiceHostname);
if (host == null) {
throw ServiceException.FAILURE("invalid " + Provisioning.A_zimbraServiceHostname + " in server " + server.getName(), null);
}
String protocol = "http";
String portAttr = Provisioning.A_zimbraMailPort;
if (admin) {
protocol = "https";
portAttr = Provisioning.A_zimbraAdminPort;
} else {
String mode = server.getAttr(Provisioning.A_zimbraMailMode);
if (mode == null) {
throw ServiceException.FAILURE("null " + Provisioning.A_zimbraMailMode + " in server " + server.getName(), null);
}
if (mode.equalsIgnoreCase("https")) {
protocol = "https";
portAttr = Provisioning.A_zimbraMailSSLPort;
}
if (mode.equalsIgnoreCase("redirect")) {
protocol = "https";
portAttr = Provisioning.A_zimbraMailSSLPort;
}
}
int port = server.getIntAttr(portAttr, -1);
if (port < 1) {
throw ServiceException.FAILURE("invalid " + portAttr + " in server " + server.getName(), null);
}
try {
return new URL(protocol, host, port, "");
} catch (MalformedURLException mue) {
throw ServiceException.FAILURE("exception creating url (protocol=" + protocol + " host=" + host + " port=" + port + ")", mue);
}
}
public static String getSoapURL(Server server, boolean admin) throws ServiceException {
String url = getServerURL(server, admin).toString();
String file = admin ? AdminConstants.ADMIN_SERVICE_URI : AccountConstants.USER_SERVICE_URI;
return url + file;
}
public static String getAdminAuthToken(String adminURL, String adminUser, String adminPassword) throws ServiceException {
SoapHttpTransport transport = new SoapHttpTransport(adminURL);
transport.setRetryCount(1);
transport.setTimeout(0);
Element authReq = new Element.XMLElement(AdminConstants.AUTH_REQUEST);
authReq.addAttribute(AdminConstants.E_NAME, adminUser, Element.Disposition.CONTENT);
authReq.addAttribute(AdminConstants.E_PASSWORD, adminPassword, Element.Disposition.CONTENT);
try {
if (verbose) LOG.info("Auth request to: " + adminURL);
if (LOG.isDebugEnabled()) LOG.debug(authReq.prettyPrint());
Element authResp = transport.invokeWithoutSession(authReq);
if (LOG.isDebugEnabled()) LOG.debug(authResp.prettyPrint());
String authToken = authResp.getAttribute(AdminConstants.E_AUTH_TOKEN);
return authToken;
} catch (Exception e) {
throw ServiceException.FAILURE("admin auth failed url=" + adminURL, e);
}
}
public static String getDelegateAuthToken(String adminURL, Account account, String adminAuthToken) throws ServiceException {
SoapHttpTransport transport = new SoapHttpTransport(adminURL);
transport.setRetryCount(1);
transport.setTimeout(0);
transport.setAuthToken(adminAuthToken);
Element daReq = new Element.XMLElement(AdminConstants.DELEGATE_AUTH_REQUEST);
Element acctElem = daReq.addElement(AdminConstants.E_ACCOUNT);
acctElem.addAttribute(AdminConstants.A_BY, AdminConstants.BY_ID);
acctElem.setText(account.getId());
try {
if (verbose) LOG.info("Delegate auth request to: " + adminURL);
if (LOG.isDebugEnabled()) LOG.debug(daReq.prettyPrint());
Element daResp = transport.invokeWithoutSession(daReq);
if (LOG.isDebugEnabled()) LOG.debug(daResp.prettyPrint());
String authToken = daResp.getAttribute(AdminConstants.E_AUTH_TOKEN);
return authToken;
} catch (Exception e) {
throw ServiceException.FAILURE("Delegate auth failed url=" + adminURL, e);
}
}
private static Account getAccount(CommandLine cl) throws ServiceException {
Provisioning prov = Provisioning.getInstance();
Config conf;
try {
conf = prov.getConfig();
} catch (ServiceException e) {
throw ServiceException.FAILURE("Unable to connect to LDAP directory", e);
}
String name = null;
if (cl.hasOption('s')) {
if (cl.hasOption('n') || cl.hasOption('m')) {
LOG.error("only one of s, n or m options can be specified");
return null;
}
name = conf.getAttr(Provisioning.A_zimbraSpamIsSpamAccount);
if (name == null || name.length() == 0) {
LOG.error("no account configured for spam");
return null;
}
} else if (cl.hasOption('n')) {
if (cl.hasOption('m')) {
LOG.error("only one of s, n, or m options can be specified");
return null;
}
name = conf.getAttr(Provisioning.A_zimbraSpamIsNotSpamAccount);
if (name == null || name.length() == 0) {
LOG.error("no account configured for ham");
return null;
}
} else if (cl.hasOption('m')) {
name = cl.getOptionValue('m');
if (name.length() == 0) {
LOG.error("illegal argument to m option");
return null;
}
} else {
LOG.error("one of s, n or m options must be specified");
return null;
}
Account account = prov.get(AccountBy.name, name);
if (account == null) {
LOG.error("can not find account " + name);
return null;
}
return account;
}
}
| [
"shriram.vishwanathan@synacor.com"
] | shriram.vishwanathan@synacor.com |
def3ebf71992dbde598921f3d5eb63887a9d14c6 | d416939f17e5482c407920d4fa8a134fef4dc514 | /es_demo/src/main/java/es_demo/JestAnalyze.java | 21fca731feee3ea47430a19a8c26afde4735a8df | [] | no_license | hlpping/java_learning | eec0ce23a7315fc3a1fb811945242578198bb571 | da361ddc107eefaf0a16730ef40e01f464f1f5c8 | refs/heads/master | 2022-07-22T06:04:09.739792 | 2016-08-28T09:34:53 | 2016-08-28T09:34:53 | 265,539,505 | 0 | 0 | null | 2020-05-20T11:08:40 | 2020-05-20T11:08:40 | null | UTF-8 | Java | false | false | 3,570 | java | package es_demo;
import java.io.IOException;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.Get;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
public class JestAnalyze {
private JestClient client = ESFactory.getClient();
/**
* 批量插入
* @param indexName
* @throws IOException
*/
public void indexBulk(String indexName) throws IOException {
Bulk.Builder bulkBuilder = new Bulk.Builder();
QueryLog log1 = new QueryLog();
log1.setDocId(1);
log1.setUserId(1001);
log1.setAge(26);
log1.setQueryWord("iphone");
Index index1 = new Index.Builder(log1).index(indexName).type(indexName).build();
bulkBuilder.addAction(index1);
QueryLog log2 = new QueryLog();
log2.setDocId(2);
log2.setUserId(1002);
log2.setAge(28);
log2.setQueryWord("elasticsearch");
Index index2 = new Index.Builder(log2).index(indexName).type(indexName).build();
bulkBuilder.addAction(index2);
QueryLog log3 = new QueryLog();
log3.setDocId(3);
log3.setUserId(1003);
log3.setAge(26);
log3.setQueryWord("movie");
Index index3 = new Index.Builder(log3).index(indexName).type(indexName).build();
bulkBuilder.addAction(index3);
QueryLog log4 = new QueryLog();
log4.setDocId(4);
log4.setUserId(1004);
log4.setAge(27);
log4.setQueryWord("elasticsearch");
Index index4 = new Index.Builder(log4).index(indexName).type(indexName).build();
bulkBuilder.addAction(index4);
JestResult rs = client.execute(bulkBuilder.build());
System.out.println(rs.getJsonString());
}
public void get(String indexName, String query) throws IOException {
Get get = new Get.Builder(indexName, query).build();
JestResult rs = client.execute(get);
System.out.println(rs.getJsonString());
client.shutdownClient();
}
/**
* search
* @param query
* @throws IOException
*/
public void search(String query) throws IOException {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.queryStringQuery(query));
searchSourceBuilder.field("name");
Search search = new Search.Builder(searchSourceBuilder.toString()).build();
JestResult rs = client.execute(search);
System.out.println(rs.getJsonString());
client.shutdownClient();
}
/**
* 聚合查询
* @param indexName
* @param term1
* @param term2
*/
public void aggs(String indexName, String term1, String term2) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.aggregation(
AggregationBuilders.terms(term1).field(term1).
subAggregation(AggregationBuilders.terms(term2).field(term2))).size(0);
Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(indexName).build();
try {
JestResult rs = client.execute(search);
System.out.println(rs.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testbulk() throws IOException {
JestAnalyze jestInstance = new JestAnalyze();
String indexName = "querylog";
jestInstance.indexBulk(indexName);
}
@Test
public void testAgg() {
JestAnalyze jestInstance = new JestAnalyze();
String indexName = "querylog";
String term1 = "queryWord";
String term2 = "age";
jestInstance.aggs(indexName, term1, term2);
}
}
| [
"wolfs_2004@aliyun.com"
] | wolfs_2004@aliyun.com |
3039f603526cb0677d7adbd1c8769979d29c2d5d | c7f6dd8fb3f0212c66ae37c9de15386a74885f3c | /calendar/src/main/java/com/fenda/calendar/model/QueryZodiacBean.java | 93f9894c373f25d6cad571e9e66b0531eb94f5fd | [] | no_license | David-lvfujiang/launcher | f22c9b30720be55503d97bd98ce2037d31f0e5c5 | bcdf18ba4d70964ccf71f116c3e4db3d8db74779 | refs/heads/master | 2022-04-01T01:12:34.129601 | 2019-12-18T01:52:58 | 2019-12-18T01:52:58 | 233,329,099 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,049 | java | package com.fenda.calendar.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* @Author: david.lvfujiang
* @Date: 2019/10/10
* @Describe: 查询生肖实体
*/
public class QueryZodiacBean {
/**
* recordId : edf8b43cc4b6439a9b358c7bed07c3b3
* skillId : 2019031800001161
* requestId : edf8b43cc4b6439a9b358c7bed07c3b3
* nlu : {"skillId":"2019031800001161","res":"5d8ae7040d32eb000d70f883","input":"今年出生的人属什么","inittime":45.2041015625,"loadtime":63.13818359375,"skill":"日历","skillVersion":"38","source":"dui","systime":234.875,"semantics":{"request":{"slots":[{"pos":[0,1],"rawvalue":"今年","name":"年","rawpinyin":"jin nian","value":"2019"},{"name":"查询对象","value":"生肖"},{"name":"intent","value":"查询生肖"}],"task":"日历","confidence":1,"slotcount":3,"rules":{"5d8ae7040d32eb000d70f8f2":{"年":["2019",0,1],"查询对象":["生肖",-1,-1],"intent":["查询生肖",-1,-1]}}}},"version":"2019.1.15.20:40:58","timestamp":1570691987}
* dm : {"input":"今年出生的人属什么,","shouldEndSession":true,"task":"日历","widget":{"widgetName":"default","duiWidget":"text","extra":{"nlyear":"己亥","year":2019,"zodiac":"猪"},"name":"default","text":"猪","type":"text"},"intentName":"查询生肖","runSequence":"nlgFirst","nlg":"今年是猪年,农历己亥年","intentId":"5d8ae7040d32eb000d70f898","speak":{"text":"今年是猪年,农历己亥年","type":"text"},"command":{"api":""},"taskId":"5d8ae7040d32eb000d70f883","status":1}
* contextId : b484b5579a164edbb0b30ee5b7a3fca9
* sessionId : b484b5579a164edbb0b30ee5b7a3fca9
*/
private String recordId;
private String skillId;
private String requestId;
private NluBean nlu;
private DmBean dm;
private String contextId;
private String sessionId;
public String getRecordId() {
return recordId;
}
public void setRecordId(String recordId) {
this.recordId = recordId;
}
public String getSkillId() {
return skillId;
}
public void setSkillId(String skillId) {
this.skillId = skillId;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public NluBean getNlu() {
return nlu;
}
public void setNlu(NluBean nlu) {
this.nlu = nlu;
}
public DmBean getDm() {
return dm;
}
public void setDm(DmBean dm) {
this.dm = dm;
}
public String getContextId() {
return contextId;
}
public void setContextId(String contextId) {
this.contextId = contextId;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public static class NluBean {
/**
* skillId : 2019031800001161
* res : 5d8ae7040d32eb000d70f883
* input : 今年出生的人属什么
* inittime : 45.2041015625
* loadtime : 63.13818359375
* skill : 日历
* skillVersion : 38
* source : dui
* systime : 234.875
* semantics : {"request":{"slots":[{"pos":[0,1],"rawvalue":"今年","name":"年","rawpinyin":"jin nian","value":"2019"},{"name":"查询对象","value":"生肖"},{"name":"intent","value":"查询生肖"}],"task":"日历","confidence":1,"slotcount":3,"rules":{"5d8ae7040d32eb000d70f8f2":{"年":["2019",0,1],"查询对象":["生肖",-1,-1],"intent":["查询生肖",-1,-1]}}}}
* version : 2019.1.15.20:40:58
* timestamp : 1570691987
*/
private String skillId;
private String res;
private String input;
private double inittime;
private double loadtime;
private String skill;
private String skillVersion;
private String source;
private double systime;
private SemanticsBean semantics;
private String version;
private int timestamp;
public String getSkillId() {
return skillId;
}
public void setSkillId(String skillId) {
this.skillId = skillId;
}
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public double getInittime() {
return inittime;
}
public void setInittime(double inittime) {
this.inittime = inittime;
}
public double getLoadtime() {
return loadtime;
}
public void setLoadtime(double loadtime) {
this.loadtime = loadtime;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
public String getSkillVersion() {
return skillVersion;
}
public void setSkillVersion(String skillVersion) {
this.skillVersion = skillVersion;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public double getSystime() {
return systime;
}
public void setSystime(double systime) {
this.systime = systime;
}
public SemanticsBean getSemantics() {
return semantics;
}
public void setSemantics(SemanticsBean semantics) {
this.semantics = semantics;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getTimestamp() {
return timestamp;
}
public void setTimestamp(int timestamp) {
this.timestamp = timestamp;
}
public static class SemanticsBean {
/**
* request : {"slots":[{"pos":[0,1],"rawvalue":"今年","name":"年","rawpinyin":"jin nian","value":"2019"},{"name":"查询对象","value":"生肖"},{"name":"intent","value":"查询生肖"}],"task":"日历","confidence":1,"slotcount":3,"rules":{"5d8ae7040d32eb000d70f8f2":{"年":["2019",0,1],"查询对象":["生肖",-1,-1],"intent":["查询生肖",-1,-1]}}}
*/
private RequestBean request;
public RequestBean getRequest() {
return request;
}
public void setRequest(RequestBean request) {
this.request = request;
}
public static class RequestBean {
/**
* slots : [{"pos":[0,1],"rawvalue":"今年","name":"年","rawpinyin":"jin nian","value":"2019"},{"name":"查询对象","value":"生肖"},{"name":"intent","value":"查询生肖"}]
* task : 日历
* confidence : 1
* slotcount : 3
* rules : {"5d8ae7040d32eb000d70f8f2":{"年":["2019",0,1],"查询对象":["生肖",-1,-1],"intent":["查询生肖",-1,-1]}}
*/
private String task;
private int confidence;
private int slotcount;
private RulesBean rules;
private List<SlotsBean> slots;
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public int getConfidence() {
return confidence;
}
public void setConfidence(int confidence) {
this.confidence = confidence;
}
public int getSlotcount() {
return slotcount;
}
public void setSlotcount(int slotcount) {
this.slotcount = slotcount;
}
public RulesBean getRules() {
return rules;
}
public void setRules(RulesBean rules) {
this.rules = rules;
}
public List<SlotsBean> getSlots() {
return slots;
}
public void setSlots(List<SlotsBean> slots) {
this.slots = slots;
}
public static class RulesBean {
/**
* 5d8ae7040d32eb000d70f8f2 : {"年":["2019",0,1],"查询对象":["生肖",-1,-1],"intent":["查询生肖",-1,-1]}
*/
@SerializedName("5d8ae7040d32eb000d70f8f2")
private _$5d8ae7040d32eb000d70f8f2Bean _$5d8ae7040d32eb000d70f8f2;
public _$5d8ae7040d32eb000d70f8f2Bean get_$5d8ae7040d32eb000d70f8f2() {
return _$5d8ae7040d32eb000d70f8f2;
}
public void set_$5d8ae7040d32eb000d70f8f2(_$5d8ae7040d32eb000d70f8f2Bean _$5d8ae7040d32eb000d70f8f2) {
this._$5d8ae7040d32eb000d70f8f2 = _$5d8ae7040d32eb000d70f8f2;
}
public static class _$5d8ae7040d32eb000d70f8f2Bean {
private List<String> 年;
private List<String> 查询对象;
private List<String> intent;
public List<String> get年() {
return 年;
}
public void set年(List<String> 年) {
this.年 = 年;
}
public List<String> get查询对象() {
return 查询对象;
}
public void set查询对象(List<String> 查询对象) {
this.查询对象 = 查询对象;
}
public List<String> getIntent() {
return intent;
}
public void setIntent(List<String> intent) {
this.intent = intent;
}
}
}
public static class SlotsBean {
/**
* pos : [0,1]
* rawvalue : 今年
* name : 年
* rawpinyin : jin nian
* value : 2019
*/
private String rawvalue;
private String name;
private String rawpinyin;
private String value;
private List<Integer> pos;
public String getRawvalue() {
return rawvalue;
}
public void setRawvalue(String rawvalue) {
this.rawvalue = rawvalue;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRawpinyin() {
return rawpinyin;
}
public void setRawpinyin(String rawpinyin) {
this.rawpinyin = rawpinyin;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<Integer> getPos() {
return pos;
}
public void setPos(List<Integer> pos) {
this.pos = pos;
}
}
}
}
}
public static class DmBean {
/**
* input : 今年出生的人属什么,
* shouldEndSession : true
* task : 日历
* widget : {"widgetName":"default","duiWidget":"text","extra":{"nlyear":"己亥","year":2019,"zodiac":"猪"},"name":"default","text":"猪","type":"text"}
* intentName : 查询生肖
* runSequence : nlgFirst
* nlg : 今年是猪年,农历己亥年
* intentId : 5d8ae7040d32eb000d70f898
* speak : {"text":"今年是猪年,农历己亥年","type":"text"}
* command : {"api":""}
* taskId : 5d8ae7040d32eb000d70f883
* status : 1
*/
private String input;
private boolean shouldEndSession;
private String task;
private WidgetBean widget;
private String intentName;
private String runSequence;
private String nlg;
private String intentId;
private SpeakBean speak;
private CommandBean command;
private String taskId;
private int status;
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public boolean isShouldEndSession() {
return shouldEndSession;
}
public void setShouldEndSession(boolean shouldEndSession) {
this.shouldEndSession = shouldEndSession;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public WidgetBean getWidget() {
return widget;
}
public void setWidget(WidgetBean widget) {
this.widget = widget;
}
public String getIntentName() {
return intentName;
}
public void setIntentName(String intentName) {
this.intentName = intentName;
}
public String getRunSequence() {
return runSequence;
}
public void setRunSequence(String runSequence) {
this.runSequence = runSequence;
}
public String getNlg() {
return nlg;
}
public void setNlg(String nlg) {
this.nlg = nlg;
}
public String getIntentId() {
return intentId;
}
public void setIntentId(String intentId) {
this.intentId = intentId;
}
public SpeakBean getSpeak() {
return speak;
}
public void setSpeak(SpeakBean speak) {
this.speak = speak;
}
public CommandBean getCommand() {
return command;
}
public void setCommand(CommandBean command) {
this.command = command;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static class WidgetBean {
/**
* widgetName : default
* duiWidget : text
* extra : {"nlyear":"己亥","year":2019,"zodiac":"猪"}
* name : default
* text : 猪
* type : text
*/
private String widgetName;
private String duiWidget;
private ExtraBean extra;
private String name;
private String text;
private String type;
public String getWidgetName() {
return widgetName;
}
public void setWidgetName(String widgetName) {
this.widgetName = widgetName;
}
public String getDuiWidget() {
return duiWidget;
}
public void setDuiWidget(String duiWidget) {
this.duiWidget = duiWidget;
}
public ExtraBean getExtra() {
return extra;
}
public void setExtra(ExtraBean extra) {
this.extra = extra;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public static class ExtraBean {
/**
* nlyear : 己亥
* year : 2019
* zodiac : 猪
*/
private String nlyear;
private int year;
private String zodiac;
public String getNlyear() {
return nlyear;
}
public void setNlyear(String nlyear) {
this.nlyear = nlyear;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getZodiac() {
return zodiac;
}
public void setZodiac(String zodiac) {
this.zodiac = zodiac;
}
}
}
public static class SpeakBean {
/**
* text : 今年是猪年,农历己亥年
* type : text
*/
private String text;
private String type;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public static class CommandBean {
/**
* api :
*/
private String api;
public String getApi() {
return api;
}
public void setApi(String api) {
this.api = api;
}
}
}
}
| [
"2411795294@qq.com"
] | 2411795294@qq.com |
e1ddd19d3e15b9d72fee3630d922aefe7782c4f0 | f5b17e409525c8031a9a8612132afa122422a799 | /source-code/QuanLyNhaXe/src/main/java/com/datvexe/repository/ViTriGheNgoiRepository.java | 87e69d80aff7a1d3455c31c444449640bd154737 | [] | no_license | nguyenhuuhoa1702/Project_HeThongQuanLyDatVeOnline | a18f5ee7361a30e2e876cf19e984f0063569a5b7 | ad22b84c6e435e82a763d6a882b68e599c41cbaa | refs/heads/master | 2022-12-20T21:26:00.086388 | 2020-01-10T10:04:55 | 2020-01-10T10:04:55 | 218,690,720 | 0 | 1 | null | 2022-12-16T09:30:57 | 2019-10-31T05:26:46 | CSS | UTF-8 | Java | false | false | 469 | java | package com.datvexe.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.datvexe.entity.LichTrinh;
import com.datvexe.entity.ViTriGheNgoi;
public interface ViTriGheNgoiRepository extends JpaRepository<ViTriGheNgoi, Long> {
@Query("select u from ViTriGheNgoi u where u.idLichTrinh = ?1")
List<ViTriGheNgoi> findAllByIdLichTrinh(LichTrinh idLichTrinh);
}
| [
"nhh01629421608@gmail.com"
] | nhh01629421608@gmail.com |
d9c2e801d19351be3f008299529deed15dd68fa8 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_9e0c56878cdbc13e984d0d46a3ca2bf64afecfbb/DefaultNexusSecurityConfiguration/2_9e0c56878cdbc13e984d0d46a3ca2bf64afecfbb_DefaultNexusSecurityConfiguration_t.java | d1bd011983890c2bab45c5f9bb16310ff5133da2 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 29,510 | java | /*
* Nexus: Maven Repository Manager
* Copyright (C) 2008 Sonatype Inc.
*
* This file is part of Nexus.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package org.sonatype.nexus.configuration.security;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException;
import org.codehaus.plexus.util.StringUtils;
import org.sonatype.nexus.configuration.ConfigurationChangeEvent;
import org.sonatype.nexus.configuration.ConfigurationChangeListener;
import org.sonatype.nexus.configuration.ConfigurationException;
import org.sonatype.nexus.configuration.application.NexusConfiguration;
import org.sonatype.nexus.configuration.model.CRepository;
import org.sonatype.nexus.configuration.model.CRepositoryTarget;
import org.sonatype.nexus.configuration.security.model.CApplicationPrivilege;
import org.sonatype.nexus.configuration.security.model.CPrivilege;
import org.sonatype.nexus.configuration.security.model.CRepoTargetPrivilege;
import org.sonatype.nexus.configuration.security.model.CRole;
import org.sonatype.nexus.configuration.security.model.CUser;
import org.sonatype.nexus.configuration.security.model.Configuration;
import org.sonatype.nexus.configuration.security.runtime.SecurityRuntimeConfigurationBuilder;
import org.sonatype.nexus.configuration.security.source.FileConfigurationSource;
import org.sonatype.nexus.configuration.security.source.SecurityConfigurationSource;
import org.sonatype.nexus.configuration.security.validator.SecurityConfigurationValidator;
import org.sonatype.nexus.configuration.security.validator.SecurityValidationContext;
import org.sonatype.nexus.configuration.security.validator.SecurityValidationResponse;
import org.sonatype.nexus.configuration.validator.InvalidConfigurationException;
import org.sonatype.nexus.configuration.validator.ValidationMessage;
import org.sonatype.nexus.configuration.validator.ValidationResponse;
import org.sonatype.nexus.proxy.NoSuchRepositoryException;
import org.sonatype.nexus.proxy.NoSuchRepositoryGroupException;
import org.sonatype.nexus.proxy.registry.ContentClass;
import org.sonatype.nexus.proxy.registry.RepositoryRegistry;
import org.sonatype.nexus.smtp.SmtpClient;
import org.sonatype.nexus.smtp.SmtpClientException;
/**
* The class DefaultNexusSecurityConfiguration is responsible for config management. It actually keeps in sync Nexus internal
* state with persisted user configuration. All changes incoming thru its iface is reflect/maintained in Nexus current
* state and Nexus user config.
*
* @author cstamas
* @plexus.component
*/
public class DefaultNexusSecurityConfiguration
extends AbstractLogEnabled
implements
NexusSecurityConfiguration,
ConfigurationChangeListener
{
/**
* The nexus configuration. Used to initialize the list of repo targets
*
* @plexus.requirement
*/
private NexusConfiguration nexusConfiguration;
/**
* The repository registry.
*
* @plexus.requirement
*/
private RepositoryRegistry repositoryRegistry;
/**
* The configuration source.
*
* @plexus.requirement role-hint="file"
*/
private SecurityConfigurationSource configurationSource;
/**
* The smtp client for sending mails.
*
* @plexus.requirement
*/
private SmtpClient smtpClient;
/**
* The config validator.
*
* @plexus.requirement
*/
private SecurityConfigurationValidator configurationValidator;
/**
* @plexus.requirement
*/
private PasswordGenerator pwGenerator;
/**
* The runtime configuration builder.
*
* @plexus.requirement
*/
private SecurityRuntimeConfigurationBuilder runtimeConfigurationBuilder;
/** The config event listeners. */
private CopyOnWriteArrayList<ConfigurationChangeListener> configurationChangeListeners =
new CopyOnWriteArrayList<ConfigurationChangeListener>();
public void onConfigurationChange( ConfigurationChangeEvent evt )
{
getLogger().debug( "Nexus Configuration Loaded, now loading Security Configuration" );
try
{
if ( FileConfigurationSource.class.isAssignableFrom( configurationSource.getClass() ) )
{
( ( FileConfigurationSource ) configurationSource ).setConfigurationFile( new File( nexusConfiguration.readSecurityConfigurationFile() ) );
}
loadConfiguration( true );
notifyConfigurationChangeListeners();
}
catch ( ConfigurationException e )
{
getLogger().error( "Could not start Nexus Security, user configuration exception!", e );
}
catch ( IOException e )
{
getLogger().error( "Could not start Nexus Security, bad IO exception!", e );
}
}
public void startService()
throws StartingException
{
nexusConfiguration.addConfigurationChangeListener( this );
getLogger().info( "Started Nexus Security" );
}
public void stopService()
throws StoppingException
{
getLogger().info( "Stopped Nexus Security" );
}
public void loadConfiguration()
throws ConfigurationException,
IOException
{
loadConfiguration( false );
}
public void loadConfiguration( boolean force )
throws ConfigurationException,
IOException
{
if ( force || configurationSource.getConfiguration() == null )
{
getLogger().debug( "Loading Nexus Security Configuration..." );
configurationSource.loadConfiguration();
// and register things
runtimeConfigurationBuilder.initialize( this );
notifyConfigurationChangeListeners();
}
}
public void applyConfiguration()
throws IOException
{
getLogger().debug( "Applying Nexus Security Configuration..." );
notifyConfigurationChangeListeners();
}
public void saveConfiguration()
throws IOException
{
configurationSource.storeConfiguration();
}
protected void applyAndSaveConfiguration()
throws IOException
{
applyConfiguration();
saveConfiguration();
}
public void addConfigurationChangeListener( ConfigurationChangeListener listener )
{
configurationChangeListeners.add( listener );
}
public void removeConfigurationChangeListener( ConfigurationChangeListener listener )
{
configurationChangeListeners.remove( listener );
}
public void notifyConfigurationChangeListeners()
{
notifyConfigurationChangeListeners( new ConfigurationChangeEvent( this ) );
}
public void notifyConfigurationChangeListeners( ConfigurationChangeEvent evt )
{
for ( ConfigurationChangeListener l : configurationChangeListeners )
{
try
{
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "Notifying component about config change: " + l.getClass().getName() );
}
l.onConfigurationChange( evt );
}
catch ( Exception e )
{
getLogger().info( "Unexpected exception in listener", e );
}
}
}
public Configuration getConfiguration()
{
return configurationSource.getConfiguration();
}
public SecurityConfigurationSource getConfigurationSource()
{
return configurationSource;
}
public InputStream getConfigurationAsStream()
throws IOException
{
return configurationSource.getConfigurationAsStream();
}
public boolean isInstanceUpgraded()
{
// TODO: this is not quite true: we might keep model ver but upgrade JARs of Nexus only in a release
// we should store the nexus version somewhere in working storage and trigger some household stuff
// if version changes.
return configurationSource.isConfigurationUpgraded();
}
public boolean isConfigurationUpgraded()
{
return configurationSource.isConfigurationUpgraded();
}
public boolean isConfigurationDefaulted()
{
return configurationSource.isConfigurationDefaulted();
}
/**
* User CRUD
*/
public Collection<CUser> listUsers()
{
return new ArrayList<CUser>( getConfiguration().getUsers() );
}
private String generateNewPassword( CUser settings )
{
String password = pwGenerator.generatePassword( 10, 10 );
settings.setPassword( pwGenerator.hashPassword( password ) );
settings.setStatus( CUser.STATUS_EXPIRED );
return password;
}
public void createUser( CUser settings )
throws ConfigurationException,
IOException
{
//On create we need to generate a new password, and email the user their new password
String password = generateNewPassword( settings );
ValidationResponse vr = configurationValidator.validateUser( initializeContext(), settings, false );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getUsers().add( settings );
applyAndSaveConfiguration();
try
{
smtpClient.sendEmail( settings.getEmail(), null, "Nexus: New user account created.", "User Account " + settings.getUserId() + " has been created. Another email will be sent shortly containing your password." );
smtpClient.sendEmail( settings.getEmail(), null, "Nexus: New user account created.", "Your new password is " + password );
}
catch ( SmtpClientException e )
{
getLogger().error( "Unable to notify user by email for new user creation", e );
}
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CUser readUser( String id )
throws NoSuchUserException
{
List<CUser> users = getConfiguration().getUsers();
for ( CUser user : users )
{
if ( user.getUserId().equals( id ) )
{
return user;
}
}
throw new NoSuchUserException( id );
}
public void updateUser( CUser settings )
throws NoSuchUserException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateUser( initializeContext(), settings, true );
if ( vr.isValid() )
{
List<CUser> users = getConfiguration().getUsers();
for ( int i = 0; i < users.size(); i++ )
{
CUser user = users.get( i );
if ( user.getUserId().equals( settings.getUserId() ) )
{
users.remove( i );
users.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchUserException( settings.getUserId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteUser( String id )
throws NoSuchUserException,
IOException
{
List<CUser> users = getConfiguration().getUsers();
for ( Iterator<CUser> i = users.iterator(); i.hasNext(); )
{
CUser user = i.next();
if ( user.getUserId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchUserException( id );
}
public void resetPassword( String id )
throws IOException,
NoSuchUserException
{
CUser user = readUser( id );
String password = generateNewPassword( user );
applyAndSaveConfiguration();
try
{
smtpClient.sendEmail( user.getEmail(), null, "Nexus: User account notification.", "Your password has been reset. Your new password is: " + password );
}
catch ( SmtpClientException e )
{
getLogger().error( "Unable to notify user by email password reset", e );
}
}
public void forgotPassword( String userId, String email )
throws IOException,
NoSuchUserException
{
CUser user = readUser( userId );
if ( user.getEmail().equals( email ) )
{
resetPassword( userId );
}
}
public void forgotUserId( String email )
throws IOException,
NoSuchUserException
{
List<CUser> users = getConfiguration().getUsers();
for ( Iterator<CUser> i = users.iterator(); i.hasNext(); )
{
CUser user = i.next();
if ( user.getEmail().equals( email ) )
{
try
{
smtpClient.sendEmail( user.getEmail(), null, "Nexus: User account notification.", " Your User ID is: " + user.getUserId() );
}
catch ( SmtpClientException e )
{
getLogger().error( "Unable to notify user by email for username reminder", e );
}
return;
}
}
throw new NoSuchUserException();
}
/**
* Role CRUD
*/
public Collection<CRole> listRoles()
{
return new ArrayList<CRole>( getConfiguration().getRoles() );
}
public void createRole( CRole settings )
throws ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRole( initializeContext(), settings, false );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getRoles().add( settings );
applyAndSaveConfiguration();
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CRole readRole( String id )
throws NoSuchRoleException
{
List<CRole> roles = getConfiguration().getRoles();
for ( CRole role : roles )
{
if ( role.getId().equals( id ) )
{
return role;
}
}
throw new NoSuchRoleException( id );
}
public void updateRole( CRole settings )
throws NoSuchRoleException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRole( initializeContext(), settings, true );
if ( vr.isValid() )
{
List<CRole> roles = getConfiguration().getRoles();
for ( int i = 0; i < roles.size(); i++ )
{
CRole role = roles.get( i );
if ( role.getId().equals( settings.getId() ) )
{
roles.remove( i );
roles.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchRoleException( settings.getId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteRole( String id )
throws NoSuchRoleException,
IOException
{
List<CRole> roles = getConfiguration().getRoles();
for ( Iterator<CRole> i = roles.iterator(); i.hasNext(); )
{
CRole role = i.next();
if ( role.getId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchRoleException( id );
}
/**
* Application Privilege CRUD
*/
public Collection<CApplicationPrivilege> listApplicationPrivileges()
{
return new ArrayList<CApplicationPrivilege>( getConfiguration().getApplicationPrivileges() );
}
public void createApplicationPrivilege( CApplicationPrivilege settings )
throws ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateApplicationPrivilege( initializeContext(), settings, false );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getApplicationPrivileges().add( settings );
applyAndSaveConfiguration();
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CApplicationPrivilege readApplicationPrivilege( String id )
throws NoSuchPrivilegeException
{
List<CApplicationPrivilege> privs = getConfiguration().getApplicationPrivileges();
for ( CApplicationPrivilege priv : privs )
{
if ( priv.getId().equals( id ) )
{
return priv;
}
}
throw new NoSuchPrivilegeException( id );
}
public void updateApplicationPrivilege( CApplicationPrivilege settings )
throws NoSuchPrivilegeException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateApplicationPrivilege( initializeContext(), settings, true );
if ( vr.isValid() )
{
List<CApplicationPrivilege> privs = getConfiguration().getApplicationPrivileges();
for ( int i = 0; i < privs.size(); i++ )
{
CApplicationPrivilege priv = privs.get( i );
if ( priv.getId().equals( settings.getId() ) )
{
privs.remove( i );
privs.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( settings.getId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteApplicationPrivilege( String id )
throws NoSuchPrivilegeException,
IOException
{
List<CApplicationPrivilege> privs = getConfiguration().getApplicationPrivileges();
for ( Iterator<CApplicationPrivilege> i = privs.iterator(); i.hasNext(); )
{
CApplicationPrivilege priv = i.next();
if ( priv.getId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( id );
}
/**
* Repository Target Privilege CRUD
*/
public Collection<CRepoTargetPrivilege> listRepoTargetPrivileges()
{
return new ArrayList<CRepoTargetPrivilege>( getConfiguration().getRepositoryTargetPrivileges() );
}
private ValidationResponse crossValidateRepoTargetPrivilege( CRepoTargetPrivilege settings )
{
ValidationResponse vr = new SecurityValidationResponse();
CRepositoryTarget target = nexusConfiguration.readRepositoryTarget( settings.getRepositoryTargetId() );
// Invalid target ID
if ( target == null )
{
ValidationMessage error = new ValidationMessage( "repositoryTargetId", "Privilege ID '" + settings.getId()
+ "' has invalid repository target ID '" + settings.getRepositoryTargetId() + "'",
"Repository Target doesn't exist" );
vr.addValidationError( error );
}
else
{
if ( !StringUtils.isEmpty( settings.getRepositoryId() ) )
{
try
{
CRepository repo = nexusConfiguration.readRepository( settings.getRepositoryId() );
// Invalid Repo/Target content types
if ( !repo.getType().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has repository and repository target of different types",
"Content type differs between repository and target.");
vr.addValidationError( error );
}
}
// Invalid repo selection
catch ( NoSuchRepositoryException e )
{
ValidationMessage error = new ValidationMessage( "repositoryId", "Privilege ID '" + settings.getId()
+ "' has invalid repository ID '" + settings.getRepositoryId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else if ( !StringUtils.isEmpty( settings.getGroupId() ) )
{
try
{
ContentClass content = repositoryRegistry.getRepositoryGroupContentClass( settings.getGroupId() );
// Invalid group/target content types
if ( !content.getId().equals( target.getContentClass() ) )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has repository group and repository target of different types",
"Content type differs between repository group and target.");
vr.addValidationError( error );
}
}
// Invalid group selection
catch ( NoSuchRepositoryGroupException e )
{
ValidationMessage error = new ValidationMessage( "repositoryGroupId", "Privilege ID '" + settings.getId()
+ "' has invalid repository group ID '" + settings.getGroupId() + "'",
e.getMessage() );
vr.addValidationError( error );
}
}
else
{
//All is well
}
}
return vr;
}
public void createRepoTargetPrivilege( CRepoTargetPrivilege settings )
throws ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRepoTargetPrivilege( initializeContext(), settings, false );
vr.append( crossValidateRepoTargetPrivilege( settings ) );
if ( vr.isValid() )
{
//TODO: anything needs to be done for the runtime configuration?
getConfiguration().getRepositoryTargetPrivileges().add( settings );
applyAndSaveConfiguration();
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public CRepoTargetPrivilege readRepoTargetPrivilege( String id )
throws NoSuchPrivilegeException
{
List<CRepoTargetPrivilege> privs = getConfiguration().getRepositoryTargetPrivileges();
for ( CRepoTargetPrivilege priv : privs )
{
if ( priv.getId().equals( id ) )
{
return priv;
}
}
throw new NoSuchPrivilegeException( id );
}
public void updateRepoTargetPrivilege( CRepoTargetPrivilege settings )
throws NoSuchPrivilegeException,
ConfigurationException,
IOException
{
ValidationResponse vr = configurationValidator.validateRepoTargetPrivilege( initializeContext(), settings, true );
vr.append( crossValidateRepoTargetPrivilege( settings ) );
if ( vr.isValid() )
{
List<CRepoTargetPrivilege> privs = getConfiguration().getRepositoryTargetPrivileges();
for ( int i = 0; i < privs.size(); i++ )
{
CRepoTargetPrivilege priv = privs.get( i );
if ( priv.getId().equals( settings.getId() ) )
{
privs.remove( i );
privs.add( i, settings );
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( settings.getId() );
}
else
{
throw new InvalidConfigurationException( vr );
}
}
public void deleteRepoTargetPrivilege( String id )
throws NoSuchPrivilegeException,
IOException
{
List<CRepoTargetPrivilege> privs = getConfiguration().getRepositoryTargetPrivileges();
for ( Iterator<CRepoTargetPrivilege> i = privs.iterator(); i.hasNext(); )
{
CRepoTargetPrivilege priv = i.next();
if ( priv.getId().equals( id ) )
{
i.remove();
applyAndSaveConfiguration();
return;
}
}
throw new NoSuchPrivilegeException( id );
}
private SecurityValidationContext initializeContext()
{
SecurityValidationContext context = new SecurityValidationContext();
context.addExistingUserIds();
context.addExistingRoleIds();
context.addExistingPrivilegeIds();
for ( CUser user : listUsers() )
{
context.getExistingUserIds().add( user.getUserId() );
context.getExistingEmailMap().put( user.getUserId(), user.getEmail() );
}
for ( CRole role : listRoles() )
{
context.getExistingRoleIds().add( role.getId() );
ArrayList<String> containedRoles = new ArrayList<String>();
containedRoles.addAll( role.getRoles() );
context.getRoleContainmentMap().put( role.getId(), containedRoles );
}
for ( CPrivilege priv : listApplicationPrivileges() )
{
context.getExistingPrivilegeIds().add( priv.getId() );
}
for ( CPrivilege priv : listRepoTargetPrivileges() )
{
context.getExistingPrivilegeIds().add( priv.getId() );
}
return context;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
6608343a012311045da8cdf6168215aae80f18c9 | 650a3f521f9c0d1835a24d0f012a25284c9e53e5 | /Bradycardia_app/app/src/main/java/com/example/bradycardia/MainActivity.java | 16848305de17a97301dda86f289ac8ad6ab1a7b2 | [] | no_license | utkagarwal/mcProject | 2cff9255b101e745f498e112b71c6c48c3b55860 | 4e8b5660183b628f646abf8afa30703171adb7f5 | refs/heads/master | 2020-05-17T04:10:58.810691 | 2019-05-04T06:03:57 | 2019-05-04T06:03:57 | 183,500,780 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 15,396 | java | package com.example.bradycardia;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Spinner;
import android.widget.Button;
import android.widget.AdapterView;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;
import butterknife.internal.Utils;
import java.util.Collections;
import java.util.Comparator;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.patient_spinner)
Spinner patient_spinner;
@BindView(R.id.model_spinner)
Spinner model_spinner;
@BindView(R.id.detect_button)
Button detect_button;
@BindView(R.id.predict_button)
Button predict_button;
String patient;
String model;
TextView textView;
TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//Button classify_button = (Button)findViewById(R.id.classify_button);
//Button predict_button = (Button)findViewById(R.id.predict_button);
patient_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String text = patient_spinner.getSelectedItem().toString();
Log.d("PatientSpinner:", text);
patient = text;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
model_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String text = model_spinner.getSelectedItem().toString();
Log.d("ModelSpinner:", text);
model = text;
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
detect_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Detect:", "Button clicked");
textView = (TextView) findViewById(R.id.simpleTextView);
textView.setText(""); //set text for text view
textView2 = (TextView) findViewById(R.id.simpleTextView);
textView2.setText(""); //set text for text view
Detect(patient, model);
}
});
predict_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Predict:", "Button clicked");
textView = (TextView) findViewById(R.id.simpleTextView);
textView.setText(""); //set text for text view
textView2 = (TextView) findViewById(R.id.simpleTextView);
textView2.setText(""); //set text for text view
Predict(patient, model);
}
});
}
private ArrayList<Integer> getheartrates(String filename)
{
String line;
ArrayList<Integer> heartrates = new ArrayList<Integer>();
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open(filename)));
while ((line = reader.readLine()) != null) {
heartrates.add(Integer.parseInt(line));
}
}
catch (IOException e)
{
}
Log.d("FileRead:",heartrates.toString());
return heartrates;
}
private ArrayList<Double> getz(String filename)
{
String line;
ArrayList<Double> heartrates = new ArrayList<Double>();
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open(filename)));
while ((line = reader.readLine()) != null) {
heartrates.add(Double.parseDouble(line));
}
}
catch (IOException e)
{
}
Log.d("FileRead:",heartrates.toString());
return heartrates;
}
private int predictSVM(List<Integer> heartrates)
{
//ArrayList<Integer> predict = new ArrayList<Integer>();
int predict = 0;
int y;
for(int i =0 ;i < heartrates.size();i++)
{
y = (-1 * heartrates.get(i)) + 59;
if (y >= 1)
{
predict = 1;
break;
}
}
return predict;
}
private int predictKNN(List<Integer> training, List<Integer> tr_labels, List<Integer> test)
{
int predict = 0;
int tr;
int te;
ArrayList<Integer> x = null;
for (int j=0; j < test.size();j++)
{
te = test.get(j);
ArrayList<ArrayList<Integer>> distance_list = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < training.size(); i++) {
tr = training.get(i);
x = new ArrayList<Integer>();
x.add(Math.abs(tr - te));
x.add(tr_labels.get(i));
distance_list.add(x);
}
Collections.sort(distance_list, new Comparator<ArrayList<Integer>>()
{
public int compare(ArrayList<Integer> p1, ArrayList<Integer> p2) {
return p1.get(0).compareTo(p2.get(0));
}
});
//Collections.reverse(distance_list);
Log.d("Predict:",distance_list.toString() );
int num_brady = 0;
int num_non = 0;
for (int i =0; i<4; i++)
{
x = distance_list.get(i);
if (x.get(1) == 1)
{
num_brady++;
}
else
{
num_non ++;
}
}
if(num_brady > num_non)
{
predict =1;
break;
}
}
return predict;
}
public void Detect(String patient, String model)
{
ArrayList<Integer> heartrates = null;
float avg;
int fp=0, fn=0, tn=0, tp=0;
int i;
int brady_count = 0;
Log.d("Detect:", patient);
if (patient.equals("Patient 1"))
Log.d("Detect:","FOUND");
long startTime = System.currentTimeMillis();
switch(patient) {
case ("Patient 1"): {
heartrates = getheartrates("Patient_272.csv");
break;
}
case ("Patient 2"): {
heartrates = getheartrates("Patient_273.csv");
break;
}
case ("Patient 3"): {
heartrates = getheartrates("Patient_420.csv");
break;
}
case ("Patient 4"): {
heartrates = getheartrates("Patient_483.csv");
break;
}
}
if (heartrates != null && heartrates.size() > 0)
{
for (i=0; i < heartrates.size() - 3; i++)
{
avg = (heartrates.get(i) + heartrates.get(i+1) + heartrates.get(i+3))/3;
if (avg < 60 && heartrates.get(i) >= 60) {
fp = fp + 1;
}
if (avg > 60 && heartrates.get(i) <= 60) {
fn = fn + 1;
}
if (avg < 60 && heartrates.get(i) < 60) {
brady_count++;
tp = tp + 1;
}
if (avg > 60 && heartrates.get(i) > 60) {
tn = tn + 1;
}
}
}
if (brady_count > 0)
{
textView = (TextView) findViewById(R.id.simpleTextView);
textView.setText(" Bradycardia is Detected");
Log.d("Detect:","Brady Detected");
Log.d("Detect:","fp:" + Integer.toString(fp) + "fn:" + Integer.toString(fn)
+ "tp:" + Integer.toString(tp) + "tn:" + Integer.toString(tn));
}
else
{
textView = (TextView) findViewById(R.id.simpleTextView);
textView.setText(" Bradycardia is NOT Detected");
Log.d("Detect:","Brady NOT Detected");
}
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
Log.d("Detect:",Integer.toString((int)elapsedTime));
//set text for text view
textView2 = (TextView) findViewById(R.id.simpleTextView2);
textView2.setText("False Positives: " + Integer.toString(fp) + "\nFalse Negatives: " + Integer.toString(fn)
+ "\nTrue Positives: " + Integer.toString(tp) + "\nTrue Negatives: " + Integer.toString(tn)
+ "\nElapsed Time: " + Long.toString(elapsedTime) + "ms");
}
private int predictKMeans(String filename, List<Integer> test)
{
int predict = 0;
int brady_centroid = 59;
int non_centroid = 71;
int brady =0;
Log.d("predictKMeans:","entered");
for(int i=0; i<test.size();i++)
{
Log.d("predictKMeans:","testing");
if(Math.abs(test.get(i) - brady_centroid) < Math.abs(test.get(i) - non_centroid))
{
return 1;
}
}
return predict;
}
private int predictLogistic(String filename, List<Integer> test)
{
ArrayList<Double> z_list = null;
z_list = getz(filename);
int predict = 0;
double val;
for(int i =0; i<z_list.size();i++)
{
val = 1/(1+ Math.pow(Math.exp(1.0),-1 * z_list.get(i)));
if(val > 0.9)
{
predict = 1;
return predict;
}
}
return predict;
}
public void Predict(String patient, String model)
{
/* Context c = getApplicationContext();
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = c.registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level / (float)scale;*/
BatteryManager mBatteryManager = (BatteryManager)MainActivity.this.getSystemService(Context.BATTERY_SERVICE);
int level = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
double mAh_start = (3000 * level * 0.01);
//float batteryPct = level / (float)scale;
ArrayList<Integer> heartrates = null;
ArrayList<Integer> labels = null;
List<Integer> test = null;
int predict = 0;
String filename = "";
String filename_Z = "";
long startTime = System.currentTimeMillis();
switch(patient) {
case ("Patient 1"): {
filename = "Kmeans_Patient_272.csv";
filename_Z = "Z_272.csv";
heartrates = getheartrates("Patient_272.csv");
labels = getheartrates("Labels_272_2.csv");
test = heartrates.subList(20,29);
break;
}
case ("Patient 2"): {
filename = "Kmeans_Patient_273.csv";
filename_Z = "Z_273.csv";
heartrates = getheartrates("Patient_273.csv");
labels = getheartrates("Labels_273_2.csv");
test = heartrates.subList(20,29);
break;
}
case ("Patient 3"): {
filename = "Kmeans_Patient_420.csv";
filename_Z = "Z_420.csv";
heartrates = getheartrates("Patient_420.csv");
labels = getheartrates("Labels_420_2.csv");
test = heartrates.subList(20,29);
break;
}
case ("Patient 4"): {
filename = "Kmeans_Patient_483.csv";
filename_Z = "Z_483.csv";
heartrates = getheartrates("Patient_483.csv");
labels = getheartrates("Labels_483_2.csv");
test = heartrates.subList(20,29);
break;
}
}
if(heartrates !=null && test != null && labels !=null)
{
switch (model)
{
case("SVM"):
{
predict = predictSVM(test);
break;
}
case("K-Nearest Neighbor"):
{
ArrayList<Integer> training_data = getheartrates("Patient_272.csv");
ArrayList<Integer> training_labels = getheartrates("Labels_272_2.csv");
predict = predictKNN(training_data.subList(0,19), training_labels.subList(0,19), test);
break;
}
case("K-Means"):
{
predict = predictKMeans(filename, test);
break;
}
case("Logistic Regression"):
{
predict = predictLogistic(filename_Z, test);
break;
}
}
}
long endTime = System.currentTimeMillis();
long elapsedtime = endTime - startTime;
if (predict == 1)
{
Log.d("Predict:", "Brady Predicted");
textView = (TextView) findViewById(R.id.simpleTextView);
textView.setText( model + "\nBradycardia IS Predicted"); //set text for text view
//textView2.setText("");
}
else
{
Log.d("Predict:", "Brady NOT Predicted");
textView = (TextView) findViewById(R.id.simpleTextView);
textView.setText(model + "\nBradycardia is NOT Predicted"); //set text for text view
textView2 = (TextView) findViewById(R.id.simpleTextView2);
//textView2.setText("");
}
level = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
double mAh_end = (3000 * level * 0.01);
double mAh_consumed = mAh_start - mAh_end;
textView2 = (TextView) findViewById(R.id.simpleTextView2);
textView2.setText("Elapsed Time: " + Long.toString(elapsedtime) +"ms" + "\n Power Consumption: "
+ Double.toString(mAh_consumed) + "mAh");
}
}
| [
"pthumati@asu.edu"
] | pthumati@asu.edu |
afbe8c0839e9b94404facbf69a410aff97b37656 | 5212c9dcb065fbdcf594a44b279da7b44872cb75 | /src/main/java/cn/bluejoe/elfinder/controller/executors/GetCommandExecutor.java | 606db9de09ccfb60c18efdab4655a24277d305c7 | [
"BSD-2-Clause"
] | permissive | jiangjunt/elfinder-2.x-servlet | 3e780df5cc189fa338b634d32e2401283f3d83d1 | f0e7cedd3d9ce406e19e95ddc3a69416cd6c9cbc | refs/heads/0.9 | 2021-01-16T18:54:34.666720 | 2015-08-12T12:01:25 | 2015-08-12T12:01:25 | 40,657,110 | 1 | 0 | null | 2015-08-13T12:16:55 | 2015-08-13T12:16:55 | null | UTF-8 | Java | false | false | 970 | java | package cn.bluejoe.elfinder.controller.executors;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import cn.bluejoe.elfinder.controller.executor.AbstractJsonCommandExecutor;
import cn.bluejoe.elfinder.controller.executor.CommandExecutor;
import cn.bluejoe.elfinder.controller.executor.FsItemEx;
import cn.bluejoe.elfinder.service.FsService;
public class GetCommandExecutor extends AbstractJsonCommandExecutor implements CommandExecutor
{
@Override
public void execute(FsService fsService, HttpServletRequest request, ServletContext servletContext, JSONObject json)
throws Exception
{
String target = request.getParameter("target");
FsItemEx fsi = super.findItem(fsService, target);
InputStream is = fsi.openInputStream();
String content = IOUtils.toString(is, "utf-8");
is.close();
json.put("content", content);
}
}
| [
"bluejoe2008@gmail.com"
] | bluejoe2008@gmail.com |
675aa3850c825fa09818c47af064357012cad73a | ce0c23248c3408cec00f8b271a7d12899841279a | /Round.java | 14ab2d8607fe4201fce55512d9becc3df4e809da | [] | no_license | Kouloumpa/Black_jack-Project | a7433eadc12610ee7ae70fb6c96fb0c8f3407bb0 | d1c176389c38de252dfaeecddeef8a1715c1c801 | refs/heads/main | 2023-03-03T08:07:51.493868 | 2021-02-10T16:34:37 | 2021-02-10T16:34:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,841 | java | import java.util.ArrayList;
import java.util.Scanner;
public class Round {
// Δημιουργία αντικειμένου της κλάσης Scanner για είσοδο από το πληκτρολόγιο
Scanner console = new Scanner(System.in);
// Δημιουργία μεταβλητής κλάσης Dealer
private Dealer round_dealer;
// Δημιουργία δύο μεταβλητών ArrayList μία για τους παίχτες του γύρου και μία για αυτούς που ακόμα δεν έχουν παίξει με τον dealer
private ArrayList<Player> round_players = new ArrayList<>();
private ArrayList<Player> non_settled_players = new ArrayList<>();
// Ο δημιουργός της κλάσης που παίρνει σαν όρισμα ένα αντικείμενο της κλάσης River και δημιουργεί ένα αντικείμενο της κλάσης dealer
public Round(River river){
round_dealer = new Dealer(river);
}
// Συνάρτηση δημιουργίας αντικειμένου και προσθήκη παίχτη στην μεταβλητή round_players παίρνοντας σαν όρισμα έναν casinoCustomer
public void addPlayer(CasinoCustomer customer){
Player player = new Player(customer);
round_players.add(player);
}
// Συνάρτηση που καλείται για να παιχτεί ένας γύρος
public void playRound(){
// για κάθε παίχτη ζητάμε να ποντάρει και του μοιράζουμε ένα χαρτί
for(Player i : round_players){
non_settled_players.add(i);
i.placeBet();
round_dealer.deal(i);
}
// ο dealer τραβάει το πρώτο του χαρτί
round_dealer.draw();
System.out.println(round_dealer.toString());
// μοιράζουμε το δεύτερο χαρτί σε κάθε παίχτη
for(Player i : round_players){
round_dealer.deal(i);
System.out.println(i.toString());
}
// ο dealer τραβάει το δεύτερό του χαρτί
round_dealer.draw();
// ελέγχουμε αν ο dealer έκανε blackjack
if(round_dealer.getDealer_hand().isBlackjack()){
System.out.println("Dealer got BlackJack, sorry everyone.");
for(Player i : round_players) {
if(!i.getCasino_hand().isBlackjack()) {
round_dealer.settle(i);
}
non_settled_players.remove(i);
}
}
// αρχικά ελέγχουμε αν ο παίκτης έκανε blackjack και αν δεν έκανε τον ρωτάμε αν θέλει να σταματήσει στις δύο κάρτες ή αν θέλει να συνεχίσει
else{
for(Player i : round_players){
if(i.getCasino_hand().isBlackjack()) {
i.winsBlackJack();
non_settled_players.remove(i);
}
else{
System.out.println(i.toString() + ", do you want to stop here? 'y' for yes, 'n' for no");
char answer = console.next().charAt(0);
if(answer == 'n') {
// αν επιλέξει να συνεχίσει καλείται η playPlayer()
playPlayer(round_dealer, i);
}
}
}
// αφού έχουν παίξει όλοι οι παίκτες παίζει ο dealer και κανονίζει όλες τις υποχρεώσεις του προς τους παίκτες
round_dealer.play();
System.out.println(round_dealer.toString());
for(Player i : non_settled_players){
round_dealer.settle(i);
}
}
}
// Συνάρτηση που ο παίκτης παίζει απλά το χέρι του τραβώντας κάρτες
private void playNormalHand(Dealer dealer, Player player){
dealer.deal(player);
System.out.println(player.toString());
if(player.getCasino_hand().isBust()){
player.loses();
non_settled_players.remove(player);
}
else {
System.out.println(player.toString() + " draw another card? 'y' for yes, 'n' for no");
char answer = console.next().charAt(0);
if (answer == 'y') {
playNormalHand(dealer, player);
}
}
}
// Συνάρτηση που ελέγχουμε αν ο παίκτης θέλει να κάνει Split Double ή να παίξει απλά το χέρι του και καλούμε την ανάλογη συνάρτηση
private void playPlayer(Dealer dealer, Player player){
if(player.getCasino_hand().canSplit()){
if(player.wantsToSplit()){
playSplitHand(dealer, player);
}
else if(player.wantsToDouble()){
playDoubledHand(dealer, player);
}
else {
playNormalHand(dealer, player);
}
}
else if(player.wantsToDouble()){
playDoubledHand(dealer, player);
}
else {
playNormalHand(dealer, player);
}
}
// Συνάρτηση στην οποία ο παίκτης τραβάει μία κάρτα μόνο διπλασιάζοντας το στοίχημά του
private void playDoubledHand(Dealer dealer, Player player){
player.doubleBet();
dealer.deal(player);
System.out.println(player.toString());
if(player.getCasino_hand().isBust()){
player.loses();
non_settled_players.remove(player);
}
}
// Συνάρτηση στην οποία ο παίκτης χωρίζει το χέρι του σε δύο νέα χέρια
private void playSplitHand(Dealer dealer, Player player){
Hand[] two_hands = player.getCasino_hand().split();
// δημιουργούμε δύο νέα αντικείμενα Player όπου το καθένα έχει την μία από τις δύο κάρτες του αρχικού χεριού και το αρχικό ποντάρισμα
Player split1 = new Player(player.getCasino_customer(), two_hands[0], player.getCasino_bet());
Player split2 = new Player(player.getCasino_customer(), two_hands[1], player.getCasino_bet());
non_settled_players.remove(player);
// Προσθέτουμε τα καινούργια αντικείμενα στην λίστα με τους παίκτες όπου ο dealer δεν έχει ακόμα τακτοποιήσει
non_settled_players.add(split1);
non_settled_players.add(split2);
// ο παίκτης παίζει κανονικά το κάθε ένα από τα δύο χέρια
playNormalHand(dealer,split1);
playNormalHand(dealer,split2);
}
public static void main(String[] args) {
River river1 = new River(6);
Round round1 = new Round(river1);
CasinoCustomer customer1 = new CasinoCustomer("customer1", 50);
CasinoCustomer customer2 = new CasinoCustomer("customer2", 100);
CasinoCustomer customer3 = new CasinoCustomer("customer3", 200);
round1.addPlayer(customer1);
round1.addPlayer(customer2);
round1.addPlayer(customer3);
round1.playRound();
}
}
| [
"noreply@github.com"
] | Kouloumpa.noreply@github.com |
ef36bcceb651b73168b72e663d650797c854f65d | e57f8cba17e78a59a13ceb1bc055c196e5d906bb | /gabIM/realer-common/src/main/java/cn/com/realer/core/util/ImageUtil.java | 3dcbd7bccb5d753c995d5e23d765114eb81c9d53 | [] | no_license | kcsn/gabIM | a6707ecf2495de44e9c0b1898cdd87878e492058 | cae2234b65d08c31e3fafa53d5c2a6291ac1a3c1 | refs/heads/master | 2020-03-24T03:22:56.974526 | 2018-07-26T09:53:33 | 2018-07-26T09:53:33 | 142,417,028 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,760 | java | package cn.com.realer.core.util;
import net.coobird.thumbnailator.Thumbnails;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* 图片处理辅助类
*
* @author ShenHuaJie
* @since 2012-03-21
*/
public final class ImageUtil {
private ImageUtil() {
}
/**
* * 转换图片大小,不变形
*
* @param img 图片文件
* @param width 图片宽
* @param height 图片高
*/
public static final void changeImge(File img, int width, int height) {
try {
Thumbnails.of(img).size(width, height).keepAspectRatio(false).toFile(img);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("图片转换出错!", e);
}
}
/**
* 根据比例缩放图片
*
* @param orgImgFile 源图片路径
* @param scale 比例
* @param targetFile 缩放后的图片存放路径
* @throws IOException
*/
public static final void scale(BufferedImage orgImg, double scale, String targetFile) throws IOException {
Thumbnails.of(orgImg).scale(scale).toFile(targetFile);
}
public static final void scale(String orgImgFile, double scale, String targetFile) throws IOException {
Thumbnails.of(orgImgFile).scale(scale).toFile(targetFile);
}
/**
* 图片格式转换
*
* @param orgImgFile
* @param width
* @param height
* @param suffixName
* @param targetFile
* @throws IOException
*/
public static final void format(String orgImgFile, int width, int height, String suffixName, String targetFile)
throws IOException {
Thumbnails.of(orgImgFile).size(width, height).outputFormat(suffixName).toFile(targetFile);
}
/**
* 根据宽度同比缩放
*
* @param orgImg 源图片
* @param orgWidth 原始宽度
* @param targetWidth 缩放后的宽度
* @param targetFile 缩放后的图片存放路径
* @throws IOException
*/
public static final double scaleWidth(BufferedImage orgImg, int targetWidth, String targetFile) throws IOException {
int orgWidth = orgImg.getWidth();
// 计算宽度的缩放比例
double scale = targetWidth * 1.00 / orgWidth;
// 裁剪
scale(orgImg, scale, targetFile);
return scale;
}
public static final void scaleWidth(String orgImgFile, int targetWidth, String targetFile) throws IOException {
BufferedImage bufferedImage = ImageIO.read(new File(orgImgFile));
scaleWidth(bufferedImage, targetWidth, targetFile);
}
/**
* 根据高度同比缩放
*
* @param orgImgFile //源图片
* @param orgHeight //原始高度
* @param targetHeight //缩放后的高度
* @param targetFile //缩放后的图片存放地址
* @throws IOException
*/
public static final double scaleHeight(BufferedImage orgImg, int targetHeight, String targetFile) throws IOException {
int orgHeight = orgImg.getHeight();
double scale = targetHeight * 1.00 / orgHeight;
scale(orgImg, scale, targetFile);
return scale;
}
public static final void scaleHeight(String orgImgFile, int targetHeight, String targetFile) throws IOException {
BufferedImage bufferedImage = ImageIO.read(new File(orgImgFile));
// int height = bufferedImage.getHeight();
scaleHeight(bufferedImage, targetHeight, targetFile);
}
// 原始比例缩放
public static final void scaleWidth(File file, Integer width) throws IOException {
String fileName = file.getName();
String filePath = file.getAbsolutePath();
String postFix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
// 缩放
BufferedImage bufferedImg = ImageIO.read(file);
String targetFile = filePath + "_s" + postFix;
scaleWidth(bufferedImg, width, targetFile);
String targetFile2 = filePath + "@" + width;
new File(targetFile).renameTo(new File(targetFile2));
}
}
| [
"825969414@qq.com"
] | 825969414@qq.com |
9a353a105c115c0fbb47fcf76d64dd8f4f9d43f7 | aff4754615205c1096364ded81d237a443c8a4ee | /src/andres/basketball/Main.java | 72328c4f5e7ac13f4c1685e152dfa271b3c52dc2 | [] | no_license | Andres-Carranza/Physics-Simulator | 53fb185a9f7157a488548dc58f7aefe22ac7f94d | 82611edcee1916fd458b8e2d70e56a0db9dd8cb3 | refs/heads/master | 2022-10-13T21:31:22.191330 | 2020-06-14T09:18:32 | 2020-06-14T09:18:32 | 272,169,663 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,567 | java | package andres.basketball;
import mahir.shapes.*;
import processing.core.PApplet;
public class Main extends PApplet {
public static final double PPM =200;
private Rectangle bounds;
private Basketball ball;
//positive is downwards and to the right
public static final Line GROUND = new Line(50,750,950,750);
public static final Line ROOF = new Line(50,50,950,50);
public static final Line WALLS[] = {new Line(50,50,50,750), new Line(950,50,950,750)};
public Main() {
bounds = new Rectangle(0,0,1000,800);
ball = new Basketball(new Circle(100 ,750 - 2 * PPM ,.3*PPM,.3*PPM),new Vector(),new Vector(),1);
}
@Override
public synchronized void draw(){
background(255);
fill(0);
for(int i = 750; i >= 50; i-=100) {
new Line(50, i,950,i).draw(this);
text((750 - i) /PPM + "m",50, i);
}
ROOF.draw(this);
WALLS[0].draw(this);
WALLS[1].draw(this);
ball.draw(this);
/*
* Acting
*/
ball.act();
ball.checkCollision(bounds);
}
public void mousePressed() {
mouseDragged();
}
public void mouseDragged() {
Vector vi = new Vector(mouseX - ball.getCenter().x, mouseY - ball.getCenter().y).div(PPM/4);
ball.adjustShootingArc(vi);
}
public void mouseReleased() {
Vector vi = new Vector(mouseX - ball.getCenter().x, mouseY - ball.getCenter().y).div(PPM/4);
ball = new Basketball(ball.getShape(),vi,new Vector(0, PhysicsShape.g),1);
}
public static void main(String[] args) {
PApplet.main("andres.basketball.Main");
}
public void settings(){
size(1000, 800);
}
public void setup(){
}
} | [
"63977242+Andress-Carranza@users.noreply.github.com"
] | 63977242+Andress-Carranza@users.noreply.github.com |
2d6213800709173841c8db27f35b283ab2d42274 | e7e969c093fe245951e48814fc2b773c90089c90 | /src/main/java/com/example/springbootgraphql/repository/SongRepository.java | 0e89ea5fca14d9378c174852055c5b763aecc277 | [] | no_license | salimerid/spring-boot-graphql | 7add50dbc2782eefcb0535e3ce1b11d832bebebb | ca6ac47eff6f2c056a4c058e2457f007223153bf | refs/heads/master | 2022-02-03T03:09:38.842003 | 2019-08-27T05:56:00 | 2019-08-27T05:56:00 | 204,620,963 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 298 | java | package com.example.springbootgraphql.repository;
import com.example.springbootgraphql.model.Song;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SongRepository extends JpaRepository<Song, Integer> {
}
| [
"salim@kaicomsol.com"
] | salim@kaicomsol.com |
350a92e5ad54662c2df467d970db4bb19f4c05ea | b3329746320689e8e9a8b3fb078b9e207c8e237d | /EureKa-Client3/src/main/java/com/ckcj/web/ClientApplication.java | c456524ca5526e5f571b3961b37396473bb30d3f | [] | no_license | PrinceAutumn/PrinceAutumn | 7f8324c504165d7ae48a78a3d6903b2222be7729 | 053b8ba331b856a678f86feeda863936a9f89acc | refs/heads/master | 2023-06-24T23:16:22.270534 | 2021-07-16T09:22:14 | 2021-07-16T09:22:14 | 385,890,785 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 59 | java | package com.ckcj.web;
public class ClientApplication {
}
| [
"841679171@qq.com"
] | 841679171@qq.com |
6dbef3d6279dde7460ca0b3216282b6cfeb1a709 | c95b26c2f7dd77f5e30e2d1cd1a45bc1d936c615 | /azureus-core/src/main/java/org/gudy/azureus2/core3/tracker/server/TRTrackerServerTorrentStats.java | aa41475c56ae2577e6214f0a0a2b226ec6524ea2 | [] | no_license | ostigter/testproject3 | b918764f5c7d4c10d3846411bd9270ca5ba2f4f2 | 2d2336ef19631148c83636c3e373f874b000a2bf | refs/heads/master | 2023-07-27T08:35:59.212278 | 2023-02-22T09:10:45 | 2023-02-22T09:10:45 | 41,742,046 | 2 | 1 | null | 2023-07-07T22:07:12 | 2015-09-01T14:02:08 | Java | UTF-8 | Java | false | false | 1,516 | java | /*
* File : TRTrackerServerStats.java
* Created : 31-Oct-2003
* By : parg
*
* Azureus - a Java Bittorrent client
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.gudy.azureus2.core3.tracker.server;
/**
* @author parg
*/
public interface TRTrackerServerTorrentStats {
public int getSeedCount();
public int getLeecherCount();
public int getQueuedCount();
public long getScrapeCount();
public long getAnnounceCount();
public long getCompletedCount();
public long getUploaded();
public long getDownloaded();
public long getBiasedUploaded();
public long getBiasedDownloaded();
public long getAmountLeft();
public long getBytesIn();
public long getBytesOut();
public int getBadNATPeerCount();
public String getString();
}
| [
"oscar.stigter@e0aef87a-ea4e-0410-81cd-4b1fdc67522b"
] | oscar.stigter@e0aef87a-ea4e-0410-81cd-4b1fdc67522b |
136f629aa3f792ff75eeebc0dba69e6c6721353a | d836f40c4ec79b30f20a170f3065854879a75711 | /algorithm/src/test/java/com/strawbingo/algorithm/sword/ch5/UglyNumberTest.java | fca2a6868bdbebafe9e2209b937401ab8a5c84b3 | [] | no_license | strawbingo/javaExample | 01edaa59ef42f9848f32fce25e2e1a52bea1f5a8 | 51cca3a4b87297f7139933db7698a7e544beb970 | refs/heads/master | 2023-05-11T03:37:35.937297 | 2023-04-24T13:25:30 | 2023-04-24T13:25:30 | 136,164,863 | 0 | 0 | null | 2022-10-12T20:23:34 | 2018-06-05T11:06:32 | Java | UTF-8 | Java | false | false | 678 | java | package com.strawbingo.algorithm.sword.ch5;
import org.junit.Assert;
import org.junit.Test;
/**
* 题49:丑数
* 我们把只包含因子2、3和5数称作丑数(Ugly Number)。
* 求按从小到大的顺序的第1500个丑数。
* 例如,6、8都是丑数,但14不是,因为它包含因子7.习惯上我们把1当做第一个丑数。
*/
public class UglyNumberTest {
@Test
public void tetNthUglyNumber(){
UglyNumber uglyNumber = new UglyNumber();
Assert.assertEquals(1,uglyNumber.nthUglyNumber(1));
Assert.assertEquals(12,uglyNumber.nthUglyNumber(10));
Assert.assertEquals(15,uglyNumber.nthUglyNumber(11));
}
}
| [
"liubin@sensetime.com"
] | liubin@sensetime.com |
7fe110383d66c72eb87318237b2ab5e3242bdc63 | 289bb48965eae3a893200f3e108afb955dbe8919 | /src/main/java/es/urjc/code/dad/mail/batch/StudentItemProcessor.java | 42b30f1cbaa1a8ae9bba80ebef9e612900889f5f | [] | no_license | AntonioMembrino/mailSender | 9f2b4b916678f96f23ae0f534dec0d021a64192f | a4e73683e67c7e53a438e78fecfb6490de92fcd1 | refs/heads/master | 2023-03-06T02:16:40.915352 | 2020-02-23T15:58:38 | 2020-02-23T15:58:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,920 | java | package es.urjc.code.dad.mail.batch;
import java.util.HashMap;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;
import es.urjc.code.dad.mail.batch.model.Student;
public class StudentItemProcessor implements ItemProcessor<Student, MimeMessage> {
private static final Logger log = LoggerFactory.getLogger(StudentItemProcessor.class);
@Autowired
private JavaMailSender mailSender;
@Autowired
private VelocityEngine engine;
private String sender;
private String attachment;
public StudentItemProcessor(String sender, String attachment) {
this.sender = sender;
this.attachment = attachment;
}
@Override
public MimeMessage process(Student student) throws Exception {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
Map<String, Object> model = new HashMap<>();
model.put("name", student.getFullname());
model.put("code", student.getCode());
helper.setFrom(sender);
helper.setTo(student.getEmail());
helper.setCc(sender);
helper.setSubject(VelocityEngineUtils.mergeTemplateIntoString(engine, "email-subject.vm", "UTF-8", model));
helper.setText(VelocityEngineUtils.mergeTemplateIntoString(engine, "email-body.vm", "UTF-8", model));
log.info("Preparing message for: " + student.getEmail());
FileSystemResource file = new FileSystemResource(attachment);
helper.addAttachment(file.getFilename(), file);
return message;
}
}
| [
"a.membrino@lineargruppo.it"
] | a.membrino@lineargruppo.it |
f23a473f7586851143074516e8c7762fa9713753 | ddfb3a710952bf5260dfecaaea7d515526f92ebb | /build/tmp/expandedArchives/forge-1.15.2-31.2.0_mapped_snapshot_20200514-1.15.1-sources.jar_c582e790131b6dd3325b282fce9d2d3d/net/minecraft/entity/ai/brain/task/SpawnGolemTask.java | d2f799c8e4208a5651a943ac4b7aafac5b0ac6f2 | [
"Apache-2.0"
] | permissive | TheDarkRob/Sgeorsge | 88e7e39571127ff3b14125620a6594beba509bd9 | 307a675cd3af5905504e34717e4f853b2943ba7b | refs/heads/master | 2022-11-25T06:26:50.730098 | 2020-08-03T15:42:23 | 2020-08-03T15:42:23 | 284,748,579 | 0 | 0 | Apache-2.0 | 2020-08-03T16:19:36 | 2020-08-03T16:19:35 | null | UTF-8 | Java | false | false | 1,949 | java | package net.minecraft.entity.ai.brain.task;
import com.google.common.collect.ImmutableMap;
import java.util.Objects;
import net.minecraft.entity.ai.brain.Brain;
import net.minecraft.entity.ai.brain.memory.MemoryModuleStatus;
import net.minecraft.entity.ai.brain.memory.MemoryModuleType;
import net.minecraft.entity.merchant.villager.VillagerEntity;
import net.minecraft.util.LongSerializable;
import net.minecraft.util.math.BlockPosWrapper;
import net.minecraft.util.math.GlobalPos;
import net.minecraft.world.server.ServerWorld;
public class SpawnGolemTask extends Task<VillagerEntity> {
private long field_225461_a;
public SpawnGolemTask() {
super(ImmutableMap.of(MemoryModuleType.JOB_SITE, MemoryModuleStatus.VALUE_PRESENT, MemoryModuleType.LOOK_TARGET, MemoryModuleStatus.REGISTERED));
}
protected boolean shouldExecute(ServerWorld worldIn, VillagerEntity owner) {
if (worldIn.getGameTime() - this.field_225461_a < 300L) {
return false;
} else if (worldIn.rand.nextInt(2) != 0) {
return false;
} else {
this.field_225461_a = worldIn.getGameTime();
GlobalPos globalpos = owner.getBrain().getMemory(MemoryModuleType.JOB_SITE).get();
return Objects.equals(globalpos.getDimension(), worldIn.getDimension().getType()) && globalpos.getPos().withinDistance(owner.getPositionVec(), 1.73D);
}
}
protected void startExecuting(ServerWorld worldIn, VillagerEntity entityIn, long gameTimeIn) {
Brain<VillagerEntity> brain = entityIn.getBrain();
brain.setMemory(MemoryModuleType.LAST_WORKED_AT_POI, LongSerializable.of(gameTimeIn));
brain.getMemory(MemoryModuleType.JOB_SITE).ifPresent((p_225460_1_) -> {
brain.setMemory(MemoryModuleType.LOOK_TARGET, new BlockPosWrapper(p_225460_1_.getPos()));
});
entityIn.playWorkstationSound();
if (entityIn.func_223721_ek()) {
entityIn.func_213766_ei();
}
}
} | [
"iodiceandrea251@gmail.com"
] | iodiceandrea251@gmail.com |
9dfcd82a35a3f32c2789a94893ab5dbed7414638 | 00d34aabc31dd090130a51ffe42716ab8a96484d | /Space/core/src/ca/fivemedia/space/VerticalFloatingPlatformMoveController.java | dd72244756d5c9d38df36574b7e2319862d09266 | [] | no_license | FiveMedia/SpaceClones | 3485023bc4ff234063d96b3a018b8182b3d7ee51 | 0fd29447dc1c0b2b79ee433236d4ae7e6d0ed7d1 | refs/heads/master | 2021-01-10T17:22:36.717761 | 2016-01-17T12:34:58 | 2016-01-17T12:34:58 | 49,815,774 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,478 | java | package ca.fivemedia.space;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.tiled.*;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import ca.fivemedia.gamelib.*;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
public class VerticalFloatingPlatformMoveController extends BaseMoveController {
int m_ignoreCollisionTicks = 0;
boolean m_active = false;
public VerticalFloatingPlatformMoveController(float speed) {
super(0, 2.0f*speed);
m_accelY = 1.0f;
m_supportReverse = true;
}
public void move(BaseSprite sprite, PlayerSprite player, TiledMapTileLayer platformTiles, TiledMapTileLayer climbableTiles)
{
if (this.shouldMove(player,sprite))
{
this.accelerate(0, m_accelY*m_currDir);
//this.calculateNewLocation(1,1,sprite);
int spriteCol = 0;
if (m_ignoreCollisionTicks > 0)
{
m_ignoreCollisionTicks--;
} else
{
spriteCol = this.getSpriteCollisions(player.getParent(), sprite);
}
if (spriteCol == 1)
{
m_ignoreCollisionTicks = 60;
m_currDir = -m_currDir;
}
sprite.setVelocity(m_dx, m_dy);
}
}
} | [
"grant@fivemedia.ca"
] | grant@fivemedia.ca |
d1f4228609ad6c3f58b45ee24b8ac3d61b108b8b | 678f51ea91ff24799444e5624b7abb2f601c587e | /Savings.java | 803759d03aa07643012675f9e9daa3e685e688e9 | [] | no_license | schroding3r/Java-Final | d4dac94dbec84b3b4e563aa8c53d38848fd6db88 | 72ca7cb5bbd9d432c842636f611e674e2d5ba7bb | refs/heads/master | 2021-03-12T19:41:53.760502 | 2011-11-18T04:54:55 | 2011-11-18T04:54:55 | 2,703,976 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 462 | java | package banking;
public class Savings extends Account
{
public void withdraw(double a)
{
balance-=a;
numberOfTransactions++;
if(numberOfTransactions>freeTransactions||vPremStat())
{
balance-=feeCost;
}
}
public void deposit(double a)
{
balance+=a;
numberOfTransactions++;
if(numberOfTransactions>freeTransactions||vPremStat())
{
balance-=feeCost;
}
}
public void compoundInterest()
{
balance+=balance*(interestRate/100);
}
} | [
"schroding3r@mailinator.com"
] | schroding3r@mailinator.com |
0b0b38bf4334afe27a32f883cdecfd581eb00279 | d5f041cbcbe6cb0edd5aeea5bb8f220f0261ab4b | /src/main/java/com/acceptic/test/opt/service/impl/CampaignRecordServiceImpl.java | 2227288fddf3f00f79673bc1277e581673e77fa2 | [] | no_license | Aqueelone/optimizationJob | 05d32c1c9dc03a9d0d844cd47faa7a9d6276cfc2 | b2c84f47d4bfec8c391d0a6dc6181ca4c777bbc2 | refs/heads/master | 2020-03-09T06:17:11.258789 | 2018-11-30T16:42:53 | 2018-11-30T16:42:53 | 127,305,301 | 0 | 0 | null | 2018-04-03T12:16:52 | 2018-03-29T14:43:24 | Java | UTF-8 | Java | false | false | 2,915 | java | package com.acceptic.test.opt.service.impl;
import com.acceptic.test.opt.service.CampaignRecordService;
import com.acceptic.test.opt.domain.CampaignRecord;
import com.acceptic.test.opt.repository.CampaignRecordRepository;
import com.acceptic.test.opt.service.dto.CampaignRecordDTO;
import com.acceptic.test.opt.service.mapper.CampaignRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service Implementation for managing CampaignRecord.
*/
@Service
@Transactional
public class CampaignRecordServiceImpl implements CampaignRecordService {
private final Logger log = LoggerFactory.getLogger(CampaignRecordServiceImpl.class);
private final CampaignRecordRepository campaignRecordRepository;
private final CampaignRecordMapper campaignRecordMapper;
public CampaignRecordServiceImpl(CampaignRecordRepository campaignRecordRepository, CampaignRecordMapper campaignRecordMapper) {
this.campaignRecordRepository = campaignRecordRepository;
this.campaignRecordMapper = campaignRecordMapper;
}
/**
* Save a campaignRecord.
*
* @param campaignRecordDTO the entity to save
* @return the persisted entity
*/
@Override
public CampaignRecordDTO save(CampaignRecordDTO campaignRecordDTO) {
log.debug("Request to save CampaignRecord : {}", campaignRecordDTO);
CampaignRecord campaignRecord = campaignRecordMapper.toEntity(campaignRecordDTO);
campaignRecord = campaignRecordRepository.save(campaignRecord);
return campaignRecordMapper.toDto(campaignRecord);
}
/**
* Get all the campaignRecords.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Override
@Transactional(readOnly = true)
public Page<CampaignRecordDTO> findAll(Pageable pageable) {
log.debug("Request to get all CampaignRecords");
return campaignRecordRepository.findAll(pageable)
.map(campaignRecordMapper::toDto);
}
/**
* Get one campaignRecord by id.
*
* @param id the id of the entity
* @return the entity
*/
@Override
@Transactional(readOnly = true)
public CampaignRecordDTO findOne(Long id) {
log.debug("Request to get CampaignRecord : {}", id);
CampaignRecord campaignRecord = campaignRecordRepository.findOne(id);
return campaignRecordMapper.toDto(campaignRecord);
}
/**
* Delete the campaignRecord by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete CampaignRecord : {}", id);
campaignRecordRepository.delete(id);
}
}
| [
"jhipster-bot@users.noreply.github.com"
] | jhipster-bot@users.noreply.github.com |
718de2e7d2f1f0642f74a1f0e61d2eef846beabe | 4586ef1690f515737029bf8ca28d1c04d679e6eb | /Project3/bll/OrderItemBLL.java | 01c7fccc033eacf327a67b0b9063c97cf697ab80 | [] | no_license | StrujanFlorentina/Fundamental-Programming-Techniques | 7c75aeac80b9c9a07d55dd06002fbbc54c28f18a | 233cdf459fab6abfe38d0d2c762137c3bafd630a | refs/heads/main | 2023-04-20T20:06:59.789981 | 2021-05-05T15:24:08 | 2021-05-05T15:24:08 | 364,615,436 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,330 | java | package bll;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import com.itextpdf.text.DocumentException;
import bll.validators.OrderItemClientValidator;
import bll.validators.OrderItemPNameValidator;
import bll.validators.OrderItemPQuantityValidator;
import bll.validators.Validator;
import dao.ClientDAO;
import dao.OrderDAO;
import dao.OrderItemDAO;
import dao.ProductDAO;
import model.Client;
import model.OrderItem;
import model.Orderc;
import model.Product;
import presentation.Bill;
import presentation.BillError;
/**
* <h1>OrderItemDAO</h1> Clasa OrderItemBLL implementeaza logica operatiilor pe
* baza de date
*
* @author FlorentinaStrujan
* @since 2020-04-12
*/
public class OrderItemBLL {
private List<Validator<OrderItem>> validators = new ArrayList<Validator<OrderItem>>();
public OrderItemBLL() {
validators.add(new OrderItemPNameValidator());
validators.add(new OrderItemPQuantityValidator());
validators.add(new OrderItemClientValidator());
}
/**
* Metoda este folosita pentru a gasi un order item dupa numele clientului ce a
* cumparat un produs si numele produsului,apelandu-se metoda din OrderItemDAO
* ce face conexiunea cu baza de date warehouse
*
* @param name Este primul parametru al metodei. Reprezinta denumirea
* cumparatorului
* @param prod Este al doilea parametru al metodei. Reprezinta denumirea
* produsului
* @return OrderItem Se va returna order item-ul corespunzator in caz de reusita
*/
public OrderItem findOrderItemByName(String name, String prod) {
OrderItem st = OrderItemDAO.findByName(name, prod);
if (st == null) {
throw new NoSuchElementException("The OrderItem with client name " + name + " was not found!");
}
return st;
}
/**
* Metoda este folosita pentru a insera un order item in tabela
* respectiva,apelandu-se metode din OrderItemDAO, OrderDAO, ClientDAO si
* ProductDAO ce fac conexiunea cu baza de date warehouse. Aceasta metoda este
* cea mai ampla din proiect din cauza faptului ca in momentul inserarii unui
* order item exista mai multe cazuri de inserari si updatatari la nivelul
* celorlalte tabele din baza de date astfel: in momentul inserarii unui order
* item e necesar ca produsul sa existe in tabela Product, iar catitatea
* acestuia sa fie mai mare sau egala cu cantitatea produsului de inserat in
* order item si este necesar ca si numele clientului de inserat sa existe in
* tabela Client. In caz de succes, se updateaza cantitatea produsului
* corespunzator din tabela Product. Daca numele clientului exista in tabela
* Orderc, se updateaza totalul corespunzator.Altfel, se va adauga clientul cu
* pretul aferent produsului cumparat.Mai avem si situatia cand numele
* produsului si numele clientului de inserat exista in tabela OrderItem. In
* acest caz, se va updata cantitatea aferenta.
*
* @param p Este singurul parametru al metodei. Reprezinta order item-ul de
* inserat
* @return int Se va returna id-ul order item-ului inserat in caz de reusita si
* -1 in caz de esec
* @throws FileNotFoundException
* @throws DocumentException
*/
public int insertOrderItem(OrderItem p) throws FileNotFoundException, DocumentException {
int result;
Product prod = ProductDAO.findByName(p.getProductName());
Client cli = ClientDAO.findByName(p.getClient());
Orderc ord = OrderDAO.findByName(p.getClient());
float newPrice = prod.getPrice() * p.getProductQuantity();
for (Validator<OrderItem> v : validators) {
v.validate(p);
}
if (OrderItemDAO.findByName(p.getClient(), p.getProductName()) == null && prod != null
&& prod.getQuantity() >= p.getProductQuantity() && cli != null) {
if (ord != null)
OrderDAO.update(newPrice, p.getClient());
else
OrderDAO.insert(new Orderc(0, p.getClient(), newPrice));
OrderDAO.update(p.getProductQuantity(), p.getProductName());
result = OrderItemDAO.insert(p);
ProductDAO.updateMinus(p.getProductQuantity(), p.getProductName());
ArrayList<OrderItem> arr = OrderItemDAO.findByClient(p.getClient());
Orderc orde = OrderDAO.findByName(p.getClient());
Bill bill = new Bill(orde, arr);
bill.generate();
return result;
} else if (prod != null && prod.getQuantity() >= p.getProductQuantity() && cli != null) {
if (ord != null)
OrderDAO.update(newPrice, p.getClient());
else
OrderDAO.insert(new Orderc(0, p.getClient(), newPrice));
OrderDAO.update(p.getProductQuantity(), p.getProductName());
result = OrderItemDAO.updateAdauga(p);
ProductDAO.updateMinus(p.getProductQuantity(), p.getProductName());
ArrayList<OrderItem> arr = OrderItemDAO.findByClient(p.getClient());
Orderc orde = OrderDAO.findByName(p.getClient());
Bill bill = new Bill(orde, arr);
bill.generate();
return result;
} else {
BillError bi = new BillError(p);
bi.generate();
return -1;
}
}
/**
* Metoda este folosita pentru a popula un vector cu order item-urile din tabela
* respectiva,apelandu-se metoda din OrderItemDAO ce face conexiunea cu baza de
* date warehouse
*
* @return ArrayList<OrderItem> Se va returna vectorul de order item-uri in caz
* de reusia si null in caz de esec
*/
public ArrayList<OrderItem> reportOrderItem() {
ArrayList<OrderItem> st = OrderItemDAO.report();
if (st == null) {
throw new NoSuchElementException("The OrderItem was not found!");
}
return st;
}
/**
* Metoda este folosita pentru a modifica cantitatea unui produs coresunzator
* unui oredr item din tabela orderitem pe baza numelui acestuia,apelandu-se
* metoda din OrderItemDAO ce face conexiunea cu baza de date warehouse
*
* @param p Este singurul parametru al metodei. Reprezinta order item-ul pe baza
* caruia se va micsora cantitatea prdusului
* @return int Se va returna 0 in caz de esec si 1 in caz de reusita
*/
public int updateAOrderItem(OrderItem p) {
int st = OrderItemDAO.updateAdauga(p);
if (st == 0) {
throw new NoSuchElementException("The OrderItem was not found!");
}
return st;
}
}
| [
"noreply@github.com"
] | StrujanFlorentina.noreply@github.com |
8d87899da035b1e980ab4ac71b39f7d70df7d3ce | 35bbfe03d30c9075bfe54039519b375f8c19b5ec | /spring-boot-jwt/src/main/java/ezc/model/JwtRequest.java | 71ca90d7d45c7b3f6c71c8783f9ae2df6ef66bbc | [] | no_license | goutham580/spring-boot-jwt | c53131a03dd39e740e83302732d347750a97c9a3 | 8ce95fb69c126247d548e07cd04c06ea5f9e022c | refs/heads/master | 2022-04-28T05:39:31.333464 | 2020-05-01T09:58:37 | 2020-05-01T09:58:37 | 260,425,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 690 | java | package ezc.model;
import java.io.Serializable;
public class JwtRequest implements Serializable {
private static final long serialVersionUID = 5926468583005150707L;
private String username;
private String password;
//need default constructor for JSON Parsing
public JwtRequest()
{
}
public JwtRequest(String username, String password) {
this.setUsername(username);
this.setPassword(password);
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
} | [
"goutham580@gmail.com"
] | goutham580@gmail.com |
8c43a81d600998b5161e1a4f5d96f2e9fd66c344 | 4c6a7887ed4a468e1ef1bfef478fedb4bc154c17 | /Mage.Sets/src/mage/cards/u/UnbridledGrowth.java | 57dc533a690eb2746c783788459e9a39f84d879c | [] | no_license | maxlebedev/mage | fc7a91ee8ee2319e2018d202eac3ffed439e4083 | f6e6d806e0e2fec3a86a1ff1808d884f55065215 | refs/heads/master | 2021-01-24T20:33:11.868182 | 2017-03-21T06:30:33 | 2017-03-21T06:30:33 | 67,287,514 | 1 | 0 | null | 2016-09-03T11:50:40 | 2016-09-03T11:50:40 | null | UTF-8 | Java | false | false | 3,932 | java | /*
* Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of BetaSteward_at_googlemail.com.
*/
package mage.cards.u;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.abilities.mana.AnyColorManaAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.AttachmentType;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.Zone;
import mage.target.TargetPermanent;
import mage.target.common.TargetLandPermanent;
/**
*
* @author fireshoes
*/
public class UnbridledGrowth extends CardImpl {
public UnbridledGrowth(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{G}");
this.subtype.add("Aura");
// Enchant land
TargetPermanent auraTarget = new TargetLandPermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.Benefit));
Ability ability = new EnchantAbility(auraTarget.getTargetName());
this.addAbility(ability);
// Enchanted land has "{T}: Add one mana of any color to your mana pool."
Ability gainedAbility = new AnyColorManaAbility(new TapSourceCost());
Effect effect = new GainAbilityAttachedEffect(gainedAbility, AttachmentType.AURA);
effect.setText("Enchanted land has \"{T}: Add one mana of any color to your mana pool.\"");
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, effect));
// Sacrifice Unbridled Growth: Draw a card.
this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), new SacrificeSourceCost()));
}
public UnbridledGrowth(final UnbridledGrowth card) {
super(card);
}
@Override
public UnbridledGrowth copy() {
return new UnbridledGrowth(this);
}
}
| [
"fireshoes@fireshoes-PC"
] | fireshoes@fireshoes-PC |
5fb60132fb2595cebbc4db52e0e5d21fa4617634 | 979dfe839d53ccdfcd8715538b1d7fcfd15e1ef2 | /br.com.heroku.phonecat.backend/src/main/java/model/Camera.java | 57d1886f088f967e32f89b0bf8a297810728ef29 | [] | no_license | eliasadriano2010/heroku-phonecat-backend | f22f7b077c2767835a7bab060dad8eac73e15df0 | 41c23a3fe6ded3c0c2c32d52590955a2010d9f5f | refs/heads/master | 2020-05-29T14:37:59.883809 | 2016-08-18T11:44:10 | 2016-08-18T11:44:10 | 63,640,252 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,112 | java | package model;
import org.codehaus.jackson.annotate.JsonProperty;
import net.vz.mongodb.jackson.Id;
import net.vz.mongodb.jackson.ObjectId;
public class Camera {
@ObjectId
@Id
private String id;
private boolean flash;
private boolean video;
private String primary;
public Camera() {
super();
}
public Camera(String id, boolean flash, boolean video, String primary) {
super();
this.id = id;
this.flash = flash;
this.video = video;
this.primary = primary;
}
@JsonProperty("_id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isFlash() {
return flash;
}
public void setFlash(boolean flash) {
this.flash = flash;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public String getPrimary() {
return primary;
}
public void setPrimary(String primary) {
this.primary = primary;
}
@Override
public String toString() {
return "Camera [id=" + id + ", flash=" + flash + ", video=" + video
+ ", primary=" + primary + "]";
}
} | [
"eliasadriano@192.168.0.101"
] | eliasadriano@192.168.0.101 |
88f22b66b6466a869819c551fbfaaa877b0df92c | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/8/8_77db263f94ab481b8e6afb7821a7e1c2c6d27621/SubscribeAction/8_77db263f94ab481b8e6afb7821a7e1c2c6d27621_SubscribeAction_t.java | 37f7e020680de91330035bc33c39b91b99c8648f | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 6,980 | java | /*
Copyright (c) 2000-2005 University of Washington. All rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in
all copies and supporting documentation;
The name, identifiers, and trademarks of the University of Washington
are not used in advertising or publicity without the express prior
written permission of the University of Washington;
Recipients acknowledge that this distribution is made available as a
research courtesy, "as is", potentially with defects, without
any obligation on the part of the University of Washington to
provide support, services, or repair;
THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR
IMPLIED, WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE UNIVERSITY OF
WASHINGTON BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT (INCLUDING
NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION WITH
THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* **********************************************************************
Copyright 2005 Rensselaer Polytechnic Institute. All worldwide rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in all
copies and supporting documentation;
The name, identifiers, and trademarks of Rensselaer Polytechnic
Institute are not used in advertising or publicity without the
express prior written permission of Rensselaer Polytechnic Institute;
DISCLAIMER: The software is distributed" AS IS" without any express or
implied warranty, including but not limited to, any implied warranties
of merchantability or fitness for a particular purpose or any warrant)'
of non-infringement of any current or pending patent rights. The authors
of the software make no representations about the suitability of this
software for any particular purpose. The entire risk as to the quality
and performance of the software is with the user. Should the software
prove defective, the user assumes the cost of all necessary servicing,
repair or correction. In particular, neither Rensselaer Polytechnic
Institute, nor the authors of the software are liable for any indirect,
special, consequential, or incidental damages related to the software,
to the maximum extent the law permits.
*/
package org.bedework.webcommon.subs;
import org.bedework.calfacade.CalFacadeException;
import org.bedework.calfacade.svc.BwSubscription;
import org.bedework.calsvci.CalSvcI;
import org.bedework.webcommon.BwAbstractAction;
import org.bedework.webcommon.BwActionFormBase;
import org.bedework.webcommon.BwSession;
import edu.rpi.sss.util.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Subscribe a user to a calendar.
*
* <p>Parameters are:<ul>
* <li>"calid" Id of calendar</li>
* <li>"name" Name of subscription</li>
* <li>"email" y/n for email .</li>
* <li>"freebusy" y/n for affects free busy.</li>
* <li>"view" Optional name of view to which we add subscription.</li>
* <li>"addtodefaultview" Optional y/n to add to default view.</li>
* </ul>
*
* <p>Forwards to:<ul>
* <li>"error" some form of fatal error.</li>
* <li>"reffed" subscription is referenced.</li>
* <li>"noAccess" user not authorised.</li>
* <li>"cancelled" for a cancelled request.</li>
* <li>"success" subscribed ok.</li>
* </ul>
*
* @author Mike Douglass douglm@rpi.edu
*/
public class SubscribeAction extends BwAbstractAction {
/* (non-Javadoc)
* @see org.bedework.webcommon.BwAbstractAction#doAction(javax.servlet.http.HttpServletRequest, org.bedework.webcommon.BwSession, org.bedework.webcommon.BwActionFormBase)
*/
public String doAction(HttpServletRequest request,
HttpServletResponse response,
BwSession sess,
BwActionFormBase form) throws Throwable {
if (form.getGuest()) {
return "noAccess"; // First line of defence
}
if (getReqPar(request, "delete") != null) {
return unsubscribe(request, form);
}
BwSubscription sub = form.getSubscription();
CalSvcI svc = form.fetchSvci();
String viewName = getReqPar(request, "view");
boolean addToDefaultView = false;
if (viewName == null) {
addToDefaultView = true;
String str = getReqPar(request, "addtodefaultview");
if (str != null) {
addToDefaultView = str.equals("y");
}
}
Boolean bool = getBooleanReqPar(request, "unremoveable");
if (bool != null) {
if (!form.getUserAuth().isSuperUser()) {
return "noAccess"; // Only super user for that flag
}
sub.setUnremoveable(bool.booleanValue());
}
if (!validateSub(sub, form)) {
return "retry";
}
if (getReqPar(request, "addSubscription") != null) {
try {
svc.addSubscription(sub);
} catch (CalFacadeException cfe) {
if (CalFacadeException.duplicateSubscription.equals(cfe.getMessage())) {
form.getErr().emit(cfe.getMessage());
return "success"; // User will see message and we'll stay on page
}
throw cfe;
}
} else if (getReqPar(request, "updateSubscription") != null) {
svc.updateSubscription(sub);
} else {
}
if ((viewName == null) && !addToDefaultView) {
// We're done - not adding to a view
return "success";
}
if (sub != null) {
svc.addViewSubscription(viewName, sub);
}
form.setSubscriptions(svc.getSubscriptions());
return "success";
}
private boolean validateSub(BwSubscription sub,
BwActionFormBase form) {
sub.setName(Util.checkNull(sub.getName()));
if (sub.getName() == null) {
form.getErr().emit("org.bedework.validation.error.missingfield", "name");
return false;
}
sub.setUri(Util.checkNull(sub.getUri()));
if (!sub.getInternalSubscription() && (sub.getUri() == null)) {
form.getErr().emit("org.bedework.validation.error.missingfield", "uri");
return false;
}
return true;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
744ee5202b16f7f33790c870561f861894f7e9aa | 1aa6119a1e33e50ef13a88545240f8d708ef5299 | /Homework/src/com/imooc/homework4/Tricycle.java | d643bba4b55ec33378a28ac83e14cb03fd1433da | [] | no_license | larryxiao625/Java-study | 08140d573d5000f174d69972a6b3beea18cc554c | ca9bf0045d307d1f5eb6ad34674ebac1eabb2e99 | refs/heads/master | 2022-11-01T12:33:45.061084 | 2018-08-22T13:59:08 | 2018-08-22T13:59:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 239 | java | package com.imooc.homework4;
public class Tricycle extends NonMotor{
public Tricycle() {
super.setWheel(3);
}
public String work() {
String str="三轮车是一款有"+this.getWheel()+"个轮子的非机动车";
return str;
}
}
| [
"romerxzh@gmail.com"
] | romerxzh@gmail.com |
3f72126fa354ae71b41353d036faea550198741a | 9a5baca04aa668bdf2408d9e8a085c9eb9ac79a0 | /GLA-war/src/java/jsf_bean/ItemManagedBean.java | 5048bef75d40a42569fa5056ec5b00768c671e02 | [] | no_license | Zhephyr54/GLA | b0f7de500d04c691897b3aba69c98d5402e44071 | 59487505794055d5338cb08f88634ae3122b1039 | refs/heads/master | 2021-05-11T13:20:40.519216 | 2018-01-31T12:52:33 | 2018-01-31T12:52:33 | 117,677,007 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,776 | java | /*
* 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 jsf_bean;
import db.dao.BiddingDAO;
import db.dao.ItemDAO;
import entity.Bidding;
import entity.Item;
import entity.User;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
//import javax.validation.constraints.Digits;
/**
*
* @author alexis
*/
@Named(value = "itemBean")
@ViewScoped
public class ItemManagedBean implements Serializable {
@EJB
ItemDAO itemDAO;
@EJB
BiddingDAO biddingDAO;
private long itemId;
private Item item;
//@Digits(integer = 7, fraction = 2, message = "Prix invalide. Exemple : 12.55")
private BigDecimal bid;
/**
* Creates a new instance of ItemManagedBean
*/
public ItemManagedBean() {
}
public long getItemId() {
return itemId;
}
public void setItemId(long itemId) {
this.itemId = itemId;
}
public Item getItem() {
return item;
}
public BigDecimal getBid() {
return bid;
}
public void setBid(BigDecimal bid) {
this.bid = bid;
}
public void onload() {
this.item = itemDAO.findById(itemId);
}
/**
* Form submit for outbid.
*/
public void outbid() {
User user = (User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sessionUtilisateur");
Bidding bidding = new Bidding(bid, user, item);
biddingDAO.create(bidding);
itemDAO.edit(item);
}
}
| [
"ale.lanoix@gmail.com"
] | ale.lanoix@gmail.com |
29e861e48a62e198e5d8c08c54bca3bf06fdf628 | abb872495f8ce2b33ae46007a606179a72b106ac | /censusspring/src/main/java/census/exceptions/LengthExcedeException.java | 79745cdd768e2569366f7f4ea4a9fab55dc1b442 | [] | no_license | infitake/census | 67a1646cfe537115bd5d111749daf95dafe1accd | 12f4b2b0d746748f29799473339b8263aa429aa1 | refs/heads/main | 2023-06-04T09:06:22.086373 | 2021-07-04T04:16:38 | 2021-07-04T04:16:38 | 382,760,160 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 758 | java | package census.exceptions;
public class LengthExcedeException extends Exception {
public LengthExcedeException() {
// TODO Auto-generated constructor stub
}
public LengthExcedeException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public LengthExcedeException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public LengthExcedeException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public LengthExcedeException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
}
| [
"rvndryadv@gmail.com"
] | rvndryadv@gmail.com |
8430cd71f25444b18c30ec8c53149fc3fdff2ed3 | 45d4296ccd2c549a1e791e74c9edc9ddb920aa16 | /src/main/java/operators/Increment.java | 05440bcde30eb467c12ea9f0c15acaa8e61cb19d | [] | no_license | Ricky-Bustillos-Study/java-features-part-2 | 335c73d157c04b6504b52f8788d8fce4b246560b | 1f0831794f5b499c3efa6a80a7856b9d1b17d437 | refs/heads/master | 2023-07-11T02:54:33.532506 | 2021-08-04T18:57:30 | 2021-08-04T18:57:30 | 392,107,053 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package operators;
public class Increment {
public static void main(String[] args) {
var number = 1;
System.out.println(++number);
var variable = 10;
System.out.println(variable--);
System.out.println(variable);
}
}
| [
"henrique.ssbl@hotmail.com"
] | henrique.ssbl@hotmail.com |
ccf931ed1de8c8cfe96c597d6a00569e03509714 | 857bf806121aa469a997434fbd89e8cbe533d4cf | /ilauncher/app/src/androidTest/java/cn/jiarong/ilauncher/ApplicationTest.java | 880cd990d4da3088294b125a7f8dde5989f8575a | [
"Apache-2.0"
] | permissive | smnc/ilauncher | 83d27b02430723fbce9f6abb9628e0ab2aec5079 | 87e2933b8911f4bb437a813f7cdd48299820c04b | refs/heads/master | 2021-12-04T21:42:25.998074 | 2015-05-19T01:09:10 | 2015-05-19T01:09:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 351 | java | package cn.jiarong.ilauncher;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"gengjiarong@gmail.com"
] | gengjiarong@gmail.com |
6eed3ea027db6c2b1a1b9498e93ecce5a55362f3 | c4d82b5d25597527fb60cdeb59a866832b832b92 | /src/com/prim/business/cost/SummTypes.java | 77fb59f1112242c34674a4c08fd562ee66416d1e | [] | no_license | primlibs/buhgalter | 7284b9e4fa147e3d085cefef696aecc82994cf71 | 8d81d1180511cb3d3b675cdb76de5b240a56fa9b | refs/heads/master | 2021-01-01T05:31:53.021874 | 2014-07-18T12:48:22 | 2014-07-18T12:48:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,317 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.prim.business.cost;
import com.prim.business.agreement.EnsuringTypes;
import java.util.LinkedHashMap;
import java.util.Map;
/**
*
* виды сумм, по которым могут рассчитываться затраты в процентах
*
* @author Rice Pavel
*/
public enum SummTypes {
BALANCES(1, "По остаткам"), DOCUMENTS(2, "По документам");
private Integer id;
private String name;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
SummTypes(int id, String name) {
this.id = id;
this.name = name;
}
public static Map<String, Object> all() {
Map<String, Object> map = new LinkedHashMap();
for (SummTypes type : SummTypes.values()) {
map.put(type.id.toString(), type.name);
}
return map;
}
public static String getNameById(Object typeId) {
String name = "";
if (typeId != null) {
Map<String, Object> all = all();
String typeIdString = typeId.toString();
if (all.get(typeIdString) != null) {
name = all.get(typeIdString).toString();
}
}
return name;
}
}
| [
"User@anufreychukvs"
] | User@anufreychukvs |
2154eea7023ed1d66d53366ec39ecf57e70064d3 | 58e1f3c009f0e9158d62454cad23a24883fd433b | /ppblossom-theone-gateway/src/main/java/com/meicai/ppblossom/theone/gateway/util/HttpclientUtils.java | 2a73b7f62ca0766bdb24397bd5d05bf2c79f83dd | [] | no_license | haibin918/ppblossom-theone | 964c57d174815ab09cc0855869138b57c47c2c82 | fba89b228aec6f1f791561924029c4754a8aea52 | refs/heads/main | 2023-05-07T12:13:23.097108 | 2021-06-04T02:46:44 | 2021-06-04T02:46:44 | 373,692,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,081 | java | //package com.meicai.ppblossom.theone.gateway.util;
///**
// *
// */
//
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.HttpEntity;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.config.Registry;
//import org.apache.http.config.RegistryBuilder;
//import org.apache.http.conn.socket.ConnectionSocketFactory;
//import org.apache.http.conn.socket.PlainConnectionSocketFactory;
//import org.apache.http.conn.ssl.NoopHostnameVerifier;
//import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
//import org.apache.http.conn.ssl.TrustStrategy;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
//import org.apache.http.util.EntityUtils;
//
//import javax.net.ssl.SSLContext;
//import java.io.IOException;
//import java.nio.charset.Charset;
//import java.security.KeyManagementException;
//import java.security.KeyStoreException;
//import java.security.NoSuchAlgorithmException;
//import java.security.cert.X509Certificate;
//import java.util.concurrent.TimeUnit;
//
//@Slf4j
//public class HttpclientUtils {
//// private static Logger logger = LoggerFactory.getLogger(HttpclientUtils.class);
//
// public static final int DEFAULT_SOCKET_TIMEOUT = 5000;
// public static final int DEFAULT_CONNECT_TIMEOUT = 5000;
// public static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 5000;
// public static final int DEFAULT_SOCKET_PRINT_TIMEOUT = 30000;
// public static final int DEFAULT_CONNECT_PRINT_TIMEOUT = 30000;
// public static final int DEFAULT_CONNECTION_PRINT_REQUEST_TIMEOUT = 30000;
// // private static final String DEFAULT_AGENT = "MEICAI/PSPMC";
// private static CloseableHttpClient httpClient;
//
// static {
// //https config
// TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
// SSLContext sslContext = null;
// try {
// sslContext = org.apache.http.ssl.SSLContexts.custom()
// .loadTrustMaterial(null, acceptingTrustStrategy)
// .build();
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// } catch (KeyManagementException e) {
// e.printStackTrace();
// } catch (KeyStoreException e) {
// e.printStackTrace();
// }
//
// SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext
// , null, null, NoopHostnameVerifier.INSTANCE);
//
// Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
// .register("http", PlainConnectionSocketFactory.getSocketFactory())
// .register("https", csf)
// .build();
//
// PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
// //最大连接数3000
// connectionManager.setMaxTotal(100);
// //路由链接数400
// connectionManager.setDefaultMaxPerRoute(100);
// RequestConfig requestConfig = RequestConfig.custom()
// .setSocketTimeout(10000)
// .setConnectTimeout(2000)
// .setConnectionRequestTimeout(1000)
// .build();
//
//
// httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
// .setConnectionManager(connectionManager)
// .evictExpiredConnections()
// .evictIdleConnections(30, TimeUnit.SECONDS)
// .build();
// }
//
// public static String postJsonWithTimeOut(String url, String jsonEntity, int timeout) throws IOException {
// long start = System.currentTimeMillis();
// //建立Request的对象,一般用目标url来构造,Request一般配置addHeader、setEntity、setConfig
// HttpPost req = new HttpPost(url);
// //setConfig,添加配置,如设置请求超时时间,连接超时时间
// RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(1000).build();
// req.setConfig(reqConfig);
// req.setHeader("Content-Type", "application/json;charset=UTF-8");
// //setEntity,添加内容
// req.setEntity(new StringEntity(jsonEntity, Charset.forName("UTF-8")));
// //执行Request请求,CloseableHttpClient的execute方法返回的response都是CloseableHttpResponse类型
// //其常用方法有getFirstHeader(String)、getLastHeader(String)、headerIterator(String)取得某个Header name对应的迭代器、getAllHeaders()、getEntity、getStatus等
// CloseableHttpResponse response = null;
// try {
// response = httpClient.execute(req);
// //用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
// String result = EntityUtils.toString(response.getEntity(), "UTF-8");
// log.info("http {} cost:{},req:{},resp:{}", url, System.currentTimeMillis() - start, jsonEntity, result);
// return result;
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
// public static String postJsonWithTimeOutAndToken(String url, int timeout) throws IOException {
// long start = System.currentTimeMillis();
// //建立Request的对象,一般用目标url来构造,Request一般配置addHeader、setEntity、setConfig
// HttpPost req = new HttpPost(url);
// //setConfig,添加配置,如设置请求超时时间,连接超时时间
// RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(1000).build();
// req.setConfig(reqConfig);
// req.setHeader("Content-Type", "application/json;charset=UTF-8");
// req.setHeader("token", "F6F7F04F4D5648818EC7A9097ADD3BB9");
// //setEntity,添加内容
// //req.setEntity(new StringEntity(jsonEntity, Charset.forName("UTF-8")));
// //执行Request请求,CloseableHttpClient的execute方法返回的response都是CloseableHttpResponse类型
// //其常用方法有getFirstHeader(String)、getLastHeader(String)、headerIterator(String)取得某个Header name对应的迭代器、getAllHeaders()、getEntity、getStatus等
// CloseableHttpResponse response = null;
// try {
// response = httpClient.execute(req);
// //用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
// String result = EntityUtils.toString(response.getEntity(), "UTF-8");
// log.info("http {} cost:{},req:{},resp:{}", url, System.currentTimeMillis() - start, "", result);
// return result;
// } finally {
// if (response != null) {
// response.close();
// }
// }
// }
//
// public static String get(String url) throws IOException {
// long start = System.currentTimeMillis();
// String result = "";
// HttpGet get = new HttpGet(url);
// CloseableHttpResponse httpResponse = null;
// httpResponse = httpClient.execute(get);
// try {
// HttpEntity entity = httpResponse.getEntity();
// if (null != entity) {
// result = EntityUtils.toString(entity);
// }
// } finally {
// httpResponse.close();
// }
// log.info("http {} cost:{},resp:{}", url, System.currentTimeMillis() - start, result);
// return result;
// }
//
//}
| [
"guohaibin@meicai.cn"
] | guohaibin@meicai.cn |
fe623b21d65ee11d3e4f5b5054518c6c323cd634 | dc98d7bfdc637690f192cc002f2a9babc0da53f5 | /cn.ieclipse.smartqq/src/cn/ieclipse/wechat/WXRobotCallback.java | 9964edd1b544a405f51ae460f7437a3787a9770a | [] | no_license | LH-Rider/SmartQQ4Eclipse | a858b4daa3bc812b4dc9f4c3f2d990aa656a6648 | 807623172b5a1bd81b252a75d9be70ec7bcba6fc | refs/heads/master | 2021-09-01T23:48:15.545526 | 2017-12-29T07:56:15 | 2017-12-29T07:56:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,601 | java | package cn.ieclipse.wechat;
import org.eclipse.jface.preference.IPreferenceStore;
import cn.ieclipse.smartim.IMClientFactory;
import cn.ieclipse.smartim.IMPlugin;
import cn.ieclipse.smartim.IMRobotCallback;
import cn.ieclipse.smartim.model.IContact;
import cn.ieclipse.smartim.model.impl.AbstractFrom;
import cn.ieclipse.smartim.model.impl.AbstractMessage;
import cn.ieclipse.smartim.preferences.RobotPreferencePage;
import cn.ieclipse.wechat.console.WXChatConsole;
import cn.ieclipse.wechat.views.WXContactView;
import io.github.biezhi.wechat.api.WechatClient;
import io.github.biezhi.wechat.model.GroupFrom;
import io.github.biezhi.wechat.model.User;
import io.github.biezhi.wechat.model.UserFrom;
import io.github.biezhi.wechat.model.WechatMessage;
public class WXRobotCallback extends IMRobotCallback {
private WXChatConsole console;
private WechatClient client;
private WXContactView fContactView;
public WXRobotCallback(WXContactView fContactView) {
this.fContactView = fContactView;
}
@Override
public void onReceiveMessage(AbstractMessage message, AbstractFrom from) {
if (!isEnable()) {
return;
}
client = getClient();
if (!client.isLogin()) {
return;
}
try {
WechatMessage m = (WechatMessage) message;
if (m.MsgType == WechatMessage.MSGTYPE_TEXT) {
console = IMPlugin.getDefault().findConsole(WXChatConsole.class,
from.getContact(), false);
answer(from, m);
}
} catch (Exception e) {
IMPlugin.getDefault().log("机器人回应异常", e);
}
}
@Override
public void onReceiveError(Throwable e) {
// TODO Auto-generated method stub
}
public void answer(AbstractFrom from, WechatMessage m) {
IPreferenceStore store = IMPlugin.getDefault().getPreferenceStore();
String robotName = store.getString(RobotPreferencePage.ROBOT_NAME);
// auto reply friend
if (from instanceof UserFrom
&& store.getBoolean(RobotPreferencePage.FRIEND_REPLY_ANY)) {
String reply = getTuringReply(String.valueOf(m.FromUserName),
m.getText().toString());
if (reply != null) {
String input = robotName + reply;
if (console == null) {
send(from, input);
}
else {
console.post(input);
}
}
}
// newbie
if (from.isNewbie() && from instanceof GroupFrom) {
GroupFrom gf = (GroupFrom) from;
String welcome = store.getString(RobotPreferencePage.GROUP_WELCOME);
if (welcome != null && !welcome.isEmpty() && gf != null) {
String input = welcome;
if (gf.getMember() != null) {
input = input.replaceAll("{memo}", "");
input = input.replaceAll("{user}",
gf.getMember().getName());
}
if (console != null) {
console.post(robotName + input);
}
else {
send(from, robotName + input);
}
}
return;
}
// @
if (atMe(from, m)) {
String msg = m.getText().toString();
String reply = getTuringReply(String.valueOf(m.FromUserName), msg);
if (reply != null) {
String input = robotName + "@" + from.getMember().getName()
+ SEP + reply;
if (console != null) {
console.post(input);
}
else {
send(from, input);
}
}
return;
}
// replay any
if (store.getBoolean(RobotPreferencePage.GROUP_REPLY_ANY)) {
if (from.isNewbie() || isMySend(m.FromUserName)) {
return;
}
if (console == null) {
return;
}
if (from instanceof UserFrom) {
return;
}
else if (from instanceof GroupFrom) {
if (((GroupFrom) from).getMember().isUnknown()) {
return;
}
}
String reply = getTuringReply(String.valueOf(m.FromUserName),
m.getText().toString());
if (reply != null) {
String input = robotName + "@" + from.getName() + SEP + reply;
if (console != null) {
console.post(input);
}
}
}
}
private boolean atMe(AbstractFrom from, WechatMessage m) {
return false;
}
private User getAccount() {
IContact me = client.getAccount();
return (User) me;
}
private void send(AbstractFrom from, String message) {
WechatMessage msg = client.createMessage(0, message, from.getContact());
client.sendMessage(msg, from.getContact());
}
private WechatClient getClient() {
return (WechatClient) IMClientFactory.getInstance().getWechatClient();
}
private boolean isMySend(String uin) {
User me = getAccount();
if (me != null && me.getUin().equals(uin)) {
return true;
}
return false;
}
}
| [
"li.jamling@gmail.com"
] | li.jamling@gmail.com |
801681cf9f1acd437e0b46a8eb055b47446d8ef4 | 3a3170a844ca6c601ab54568c692302d0f7c25eb | /2nd year/SEPT-DEC/CIS-2232 Advanced OOP/Assignments/Assignment3/gradesCalculator/src/main/java/info/hccis/admin/web/package-info.java | 166b703f871cfa2aed57d3c2c4f4b7694f0f5355 | [
"Apache-2.0"
] | permissive | krystofurr/HC-CIS | a34c55ca94ef17ad7bdc0e773d3a7bd9d1dbf348 | 61a747b7d82fbf6fdac87115e1c91a70f3493a74 | refs/heads/master | 2021-01-10T07:57:59.482365 | 2016-01-09T21:04:07 | 2016-01-09T21:04:07 | 47,044,526 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 80 | java |
/**
*
* Web Presentation Layer
*
*/
package info.hccis.admin.web;
| [
"krystofurr@gmail.com"
] | krystofurr@gmail.com |
7d28396e7f9edfc030e2f7233d70981da4203a58 | dbdb65d52a52b05d7a64765f24cad4a93d2dc327 | /dgmall-product/src/main/java/com/donggua/dgmall/product/service/AttrService.java | 604211c1bae65b9214b38418c6ccf8607bb12103 | [] | no_license | tianrundong/dgmall | c7bf5ad79bd1cdfe0f751d3a745dfca3d8cce55f | 81a68191d026031411c79e9e3c2ecaeb47a61357 | refs/heads/master | 2021-06-02T06:55:46.792858 | 2020-04-09T08:48:47 | 2020-04-09T08:48:47 | 254,316,620 | 3 | 0 | null | 2020-04-09T08:50:10 | 2020-04-09T08:38:57 | JavaScript | UTF-8 | Java | false | false | 449 | java | package com.donggua.dgmall.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.donggua.common.utils.PageUtils;
import com.donggua.dgmall.product.entity.AttrEntity;
import java.util.Map;
/**
* 商品属性
*
* @author tianrundong
* @email 1004028919@qq.com
* @date 2020-04-04 14:22:37
*/
public interface AttrService extends IService<AttrEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| [
"1004028919@qq.com"
] | 1004028919@qq.com |
11a3672b1b6b5c41ac3af04c55fb855ad16fa0a6 | 97cda285663a8bbf751b39321b695d97b6f69474 | /Checkstyle/src/com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.java | c1c4004f1907224f6100e92acfc90f908d9dc689 | [] | no_license | clustercompare/clustercompare-data | 838c4de68645340546dd5e50b375dcf877591b3e | 163d05bdc5f4a03da8155ffb1f922a9421733589 | refs/heads/master | 2020-12-25T23:10:16.331657 | 2015-12-11T10:37:43 | 2015-12-11T10:37:43 | 39,699,972 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,025 | java | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2010 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import antlr.collections.AST;
import com.google.common.collect.Lists;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.ScopeUtils;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import java.util.LinkedList;
/**
* <p>
* Abstract class for checking that an overriding method with no parameters
* invokes the super method.
* </p>
* @author Rick Giles
*/
public abstract class AbstractSuperCheck
extends Check
{
/**
* Stack node for a method definition and a record of
* whether the method has a call to the super method.
* @author Rick Giles
*/
private static class MethodNode
{
/** method definition */
private final DetailAST mMethod;
/** true if the overriding method calls the super method */
private boolean mCallsSuper;
/**
* Constructs a stack node for a method definition.
* @param aAST AST for the method definition.
*/
public MethodNode(DetailAST aAST)
{
mMethod = aAST;
mCallsSuper = false;
}
/**
* Records that the overriding method has a call to the super method.
*/
public void setCallsSuper()
{
mCallsSuper = true;
}
/**
* Determines whether the overriding method has a call to the super
* method.
* @return true if the overriding method has a call to the super
* method.
*/
public boolean getCallsSuper()
{
return mCallsSuper;
}
/**
* Returns the overriding method definition AST.
* @return the overriding method definition AST.
*/
public DetailAST getMethod()
{
return mMethod;
}
}
/** stack of methods */
private final LinkedList<MethodNode> mMethodStack = Lists.newLinkedList();
@Override
public int[] getDefaultTokens()
{
return new int[] {
TokenTypes.METHOD_DEF,
TokenTypes.LITERAL_SUPER,
};
}
/**
* Returns the name of the overriding method.
* @return the name of the overriding method.
*/
protected abstract String getMethodName();
@Override
public void beginTree(DetailAST aRootAST)
{
mMethodStack.clear();
}
@Override
public void visitToken(DetailAST aAST)
{
if (isOverridingMethod(aAST)) {
mMethodStack.add(new MethodNode(aAST));
}
else if (isSuperCall(aAST)) {
final MethodNode methodNode = mMethodStack.getLast();
methodNode.setCallsSuper();
}
}
/**
* Determines whether a 'super' literal is a call to the super method
* for this check.
* @param aAST the AST node of a 'super' literal.
* @return true if aAST is a call to the super method
* for this check.
*/
private boolean isSuperCall(DetailAST aAST)
{
if (aAST.getType() != TokenTypes.LITERAL_SUPER) {
return false;
}
// dot operator?
DetailAST parent = aAST.getParent();
if ((parent == null) || (parent.getType() != TokenTypes.DOT)) {
return false;
}
// same name of method
AST sibling = aAST.getNextSibling();
// ignore type parameters
if ((sibling != null)
&& (sibling.getType() == TokenTypes.TYPE_ARGUMENTS))
{
sibling = sibling.getNextSibling();
}
if ((sibling == null) || (sibling.getType() != TokenTypes.IDENT)) {
return false;
}
final String name = sibling.getText();
if (!getMethodName().equals(name)) {
return false;
}
// 0 parameters?
final DetailAST args = parent.getNextSibling();
if ((args == null) || (args.getType() != TokenTypes.ELIST)) {
return false;
}
if (args.getChildCount() != 0) {
return false;
}
// in an overriding method for this check?
while (parent != null) {
if (parent.getType() == TokenTypes.METHOD_DEF) {
return isOverridingMethod(parent);
}
else if ((parent.getType() == TokenTypes.CTOR_DEF)
|| (parent.getType() == TokenTypes.INSTANCE_INIT))
{
return false;
}
parent = parent.getParent();
}
return false;
}
@Override
public void leaveToken(DetailAST aAST)
{
if (isOverridingMethod(aAST)) {
final MethodNode methodNode =
mMethodStack.removeLast();
if (!methodNode.getCallsSuper()) {
final DetailAST methodAST = methodNode.getMethod();
final DetailAST nameAST =
methodAST.findFirstToken(TokenTypes.IDENT);
log(nameAST.getLineNo(), nameAST.getColumnNo(),
"missing.super.call", nameAST.getText());
}
}
}
/**
* Determines whether an AST is a method definition for this check,
* with 0 parameters.
* @param aAST the method definition AST.
* @return true if the method of aAST is a method for this check.
*/
private boolean isOverridingMethod(DetailAST aAST)
{
if ((aAST.getType() != TokenTypes.METHOD_DEF)
|| ScopeUtils.inInterfaceOrAnnotationBlock(aAST))
{
return false;
}
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
final String name = nameAST.getText();
if (!getMethodName().equals(name)) {
return false;
}
final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS);
return (params.getChildCount() == 0);
}
}
| [
"mail@jan-melcher.de"
] | mail@jan-melcher.de |
e03234fa8efba4302d81d15e12907d61642c3017 | 05e5bee54209901d233f4bfa425eb6702970d6ab | /org/bukkit/plugin/AuthorNagException.java | 91e870fb3a167b2f9e3587875bde8b2eb1d8c2a3 | [] | no_license | TheShermanTanker/PaperSpigot-1.7.10 | 23f51ff301e7eb05ef6a3d6999dd2c62175c270f | ea9d33bcd075e00db27b7f26450f9dc8e6d18262 | refs/heads/master | 2022-12-24T10:32:09.048106 | 2020-09-25T15:43:22 | 2020-09-25T15:43:22 | 298,614,646 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 654 | java | /* */ package org.bukkit.plugin;
/* */
/* */
/* */
/* */
/* */
/* */ public class AuthorNagException
/* */ extends RuntimeException
/* */ {
/* */ private final String message;
/* */
/* */ public AuthorNagException(String message) {
/* 13 */ this.message = message;
/* */ }
/* */
/* */
/* */ public String getMessage() {
/* 18 */ return this.message;
/* */ }
/* */ }
/* Location: D:\Paper-1.7.10\PaperSpigot-1.7.10-R0.1-SNAPSHOT-latest.jar!\org\bukkit\plugin\AuthorNagException.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | [
"tanksherman27@gmail.com"
] | tanksherman27@gmail.com |
a3e766c5cd6e0b88f9542bfd7924220c98ecc365 | f69a8fa22d28e3f078c98c4a737516cf8bc172a4 | /src/shalom/bible/hymn/cion/fragment/Fragment_OldHymn.java | 685e3befb8b312fac488eca75a17df4f5f63b5a1 | [] | no_license | cion49235/BibleHymn_cion | b91d82a6e8f45971d2799ddb7f09215295290950 | b4e173f1d2a4aa6b8ef904f922a15fcd5e7c7d96 | refs/heads/master | 2021-05-06T11:43:52.100147 | 2018-06-25T08:38:45 | 2018-06-25T08:38:45 | 113,341,737 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,704 | java | package shalom.bible.hymn.cion.fragment;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import shalom.bible.hymn.cion.R;
import shalom.bible.hymn.cion.activity.HymnViewActivity;
import shalom.bible.hymn.cion.dao.DBOpenHelper_OldHymn;
import shalom.bible.hymn.cion.dao.Fragment_Data_OldHymn;
import shalom.bible.hymn.cion.util.KoreanTextMatch;
import shalom.bible.hymn.cion.util.KoreanTextMatcher;
public class Fragment_OldHymn extends Fragment implements OnClickListener, OnItemClickListener, OnScrollListener{
private EditText edit_searcher;
private DBOpenHelper_OldHymn mydb;
private SQLiteDatabase mdb;
private Cursor cursor;
private ArrayList<Fragment_Data_OldHymn> list;
private FragmentAdapter adapter;
private ListView listview;
private LinearLayout layout_nodata;
private String searchKeyword;
private ImageButton btn_close;
private KoreanTextMatch match1, match2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hymn1,container, false);
init_ui(view);
display_list();
seacher_start();
listview.setOnScrollListener(this);
listview.setOnItemClickListener(this);
btn_close.setOnClickListener(this);
return view;
}
@Override
public void onDestroy() {
super.onDestroy();
try {
edit_searcher.setText("");
}catch (NullPointerException e) {
}catch (Exception e) {
}
}
private void seacher_start(){
edit_searcher.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
searchKeyword = s.toString();
display_list();
if(adapter != null){
adapter.notifyDataSetChanged();
}
if(s.length() == 0){
btn_close.setVisibility(View.INVISIBLE);
}else{
btn_close.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
}
}
});
}
private void display_list(){
list = new ArrayList<Fragment_Data_OldHymn>();
mydb = new DBOpenHelper_OldHymn(getActivity());
mdb = mydb.getReadableDatabase();
cursor = mdb.rawQuery("select * from tongil_hymn", null);
while(cursor.moveToNext()){
if(searchKeyword != null && "".equals(searchKeyword.trim()) == false){
KoreanTextMatcher matcher1 = new KoreanTextMatcher(searchKeyword.toLowerCase());
KoreanTextMatcher matcher2 = new KoreanTextMatcher(searchKeyword.toUpperCase());
match1 = matcher1.match(cursor.getString(cursor.getColumnIndex("title")).toLowerCase());
match2 = matcher2.match(cursor.getString(cursor.getColumnIndex("title")).toUpperCase());
if(match1.success()){
list.add(new Fragment_Data_OldHymn(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("title")), cursor.getInt(cursor.getColumnIndex("description"))));
}else if (match2.success()){
list.add(new Fragment_Data_OldHymn(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("title")), cursor.getInt(cursor.getColumnIndex("description"))));
}
}else{
list.add(new Fragment_Data_OldHymn(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("title")), cursor.getInt(cursor.getColumnIndex("description"))));
}
}
cursor.close();
adapter = new FragmentAdapter();
listview.setAdapter(adapter);
if(listview.getCount() > 0){
layout_nodata.setVisibility(View.GONE);
}else{
layout_nodata.setVisibility(View.VISIBLE);
}
}
private void init_ui(View view){
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
layout_nodata = (LinearLayout)view.findViewById(R.id.layout_nodata);
edit_searcher = (EditText)view.findViewById(R.id.edit_searcher);
btn_close = (ImageButton)view.findViewById(R.id.btn_close);
listview = (ListView)view.findViewById(R.id.listview);
}
public class FragmentAdapter extends BaseAdapter{
public FragmentAdapter() {
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
try{
if(view == null){
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
view = layoutInflater.inflate(R.layout.fragment_hymn_listrow, parent, false);
}
ImageView img_more = (ImageView)view.findViewById(R.id.img_more);
img_more.setFocusable(false);
img_more.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int _id = list.get(position)._id;
int description = list.get(position).description;
String title = list.get(position).title;
Intent intent = new Intent(getActivity(), HymnViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("id", _id);
intent.putExtra("title", title);
intent.putExtra("description", description);
startActivity(intent);
}
});
TextView txt_subject = (TextView)view.findViewById(R.id.txt_name);
// txt_subject.setText(list.get(position).title);
setTextViewColorPartial(txt_subject, list.get(position).title, searchKeyword, Color.RED);
}catch (Exception e) {
}
return view;
}
private void setTextViewColorPartial(TextView view, String fulltext, String subtext, int color) {
try{
view.setText(fulltext, TextView.BufferType.SPANNABLE);
Spannable str = (Spannable) view.getText();
int i = fulltext.indexOf(subtext);
str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}catch (IndexOutOfBoundsException e) {
}
}
}
@Override
public void onClick(View v) {
if(v == btn_close){
edit_searcher.setText("");
display_list();
if(adapter != null){
adapter.notifyDataSetChanged();
}
InputMethodManager inputMethodManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(edit_searcher.getWindowToken(), 0);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment_Data_OldHymn data = (Fragment_Data_OldHymn)adapter.getItem(position);
int _id = data._id;
int description = data.description;
String title = data.title;
Intent intent = new Intent(getActivity(), HymnViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("id", _id);
intent.putExtra("title", title);
intent.putExtra("description", description);
startActivity(intent);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if(scrollState == OnScrollListener.SCROLL_STATE_FLING){
InputMethodManager inputMethodManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(edit_searcher.getWindowToken(), 0);
listview.setFastScrollEnabled(true);
}else{
listview.setFastScrollEnabled(false);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
}
| [
"cion49235@nate.com"
] | cion49235@nate.com |
ba1ae9ab139f816671e5a1b9c51ffc519646bc10 | 3cb3004c7b44f9886b095197192df38581e51826 | /atu-api-domain/src/main/java/com/atu/api/domain/query/ItemImageQuery.java | f0e25896c7535772c16449a741086075d42424b9 | [] | no_license | github188/atu_api | 0c8fe985285bb59adf79944665c2046dc970ef65 | 2df7c270c40b1bb54e2cc4ab7c014cb17f9f0540 | refs/heads/master | 2020-03-22T13:55:14.394152 | 2017-12-04T03:58:45 | 2017-12-04T03:58:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,674 | java | package com.atu.api.domain.query;
import java.io.Serializable;
import java.util.Date;
public class ItemImageQuery extends BaseSearchForMysqlVo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/** 自增ID */
private Integer id;
/** 商品ID */
private Integer itemId;
/** 图片地址 */
private String imageUrl;
/** 排序 */
private Integer sortNumber;
/** 有效性 */
private Integer yn;
/** 创建时间 */
private Date created;
/** 修改时间 */
private Date modified;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getSortNumber() {
return sortNumber;
}
public void setSortNumber(Integer sortNumber) {
this.sortNumber = sortNumber;
}
public Integer getYn() {
return yn;
}
public void setYn(Integer yn) {
this.yn = yn;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
} | [
"359953111@qq.com"
] | 359953111@qq.com |
bc392d0c496e643bbaa80d8a36109eedf6f33ae2 | ce82e8453686b03e7bcf8d3e061c3607ae0d303e | /src/main/java/com/mtjanney/deatheffects/util/PlayerWrapper.java | fb20fafc8bc158221768c0dde1947baf47f92c71 | [] | no_license | Rivzz/DeathEffects | a37894a5037447c9ef3fbcf75b2f6c33705301de | 9ce00a00ddca9cebe5ca9a0f6eceb33968eb8cc2 | refs/heads/master | 2022-06-01T00:26:25.936713 | 2020-04-30T20:36:38 | 2020-04-30T20:36:38 | 258,349,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 496 | java | package com.mtjanney.deatheffects.util;
public class PlayerWrapper
{
private String deathEffect;
private String soundEffect;
public void setDeathEffect(String deathEffect)
{
this.deathEffect = deathEffect;
}
public String getDeathEffect()
{
return deathEffect;
}
public void setSoundEffect(String soundEffect)
{
this.soundEffect = soundEffect;
}
public String getSoundEffect()
{
return soundEffect;
}
}
| [
"mtjanney2@hotmail.com"
] | mtjanney2@hotmail.com |
e286780ff8fb057679138f43c7ac60c5c5b413b6 | e8f5ada05a51c14232d621cdadbcc93466859bec | /test/de/jungblut/classification/regression/LogisticRegressionTest.java | c38cbebc782e341f1c89365ae843f64715278c60 | [
"Apache-2.0"
] | permissive | lhx0612/thomasjungblut-common | baf0c25effb73a26a8e6fc497f222bbd0ed9c217 | 0524c794c5a6d7d406e73ae60d8ba58dbcb0c008 | refs/heads/master | 2021-01-20T21:46:29.120225 | 2013-07-14T14:02:19 | 2013-07-14T14:02:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,000 | java | package de.jungblut.classification.regression;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import de.jungblut.classification.Classifier;
import de.jungblut.classification.eval.Evaluator;
import de.jungblut.classification.eval.Evaluator.EvaluationResult;
import de.jungblut.math.DoubleVector;
import de.jungblut.math.dense.DenseDoubleMatrix;
import de.jungblut.math.dense.DenseDoubleVector;
import de.jungblut.math.minimize.Fmincg;
import de.jungblut.reader.CsvDatasetReader;
import de.jungblut.reader.Dataset;
public class LogisticRegressionTest {
private static DoubleVector[] features;
private static DoubleVector[] outcome;
private static DenseDoubleVector y;
private static DenseDoubleMatrix x;
static {
LogisticRegression.SEED = 0L;
Dataset readCsv = CsvDatasetReader.readCsv("files/logreg/ex2data1.txt",
',', null, 2, 2);
features = readCsv.getFeatures();
outcome = readCsv.getOutcomes();
double[] classes = new double[outcome.length];
for (int i = 0; i < outcome.length; i++) {
classes[i] = outcome[i].get(0);
}
y = new DenseDoubleVector(classes);
x = new DenseDoubleMatrix(features);
}
@Test
public void testLogisticRegression() {
LogisticRegressionCostFunction fnc = new LogisticRegressionCostFunction(
new DenseDoubleMatrix(features), y, 1d);
DoubleVector theta = Fmincg.minimizeFunction(fnc, new DenseDoubleVector(
new double[] { 0, 0, 0 }), 1000, false);
assertEquals(theta.get(0), -25.05, 0.1);
assertEquals(theta.get(1), 0.2, 0.1);
assertEquals(theta.get(2), 0.2, 0.1);
}
@Test
public void testPredictions() {
LogisticRegression reg = new LogisticRegression(1.0d, new Fmincg(), 1000,
false);
reg.train(x, y);
DoubleVector predict = reg.predict(x, 0.5d);
double wrongPredictions = predict.subtract(y).abs().sum();
assertEquals(11.0d, wrongPredictions, 1e-4);
double trainAccuracy = (y.getLength() - wrongPredictions) / y.getLength();
assertTrue(trainAccuracy > 0.85);
}
@Test
public void testRegressionInterface() {
Classifier clf = new LogisticRegression(1.0d, new Fmincg(), 1000, false);
clf.train(features, outcome);
double trainingError = 0d;
for (int i = 0; i < features.length; i++) {
int predict = clf.getPredictedClass(features[i], 0.5d);
trainingError += Math.abs(outcome[i].get(0) - predict);
}
assertEquals("Training error was: " + trainingError
+ " and should have been between 9 and 13.", trainingError, 11, 2d);
}
@Test
public void testRegressionEvaluation() {
Classifier clf = new LogisticRegression(1.0d, new Fmincg(), 1000, false);
EvaluationResult eval = Evaluator.evaluateClassifier(clf, features,
outcome, 2, 0.9f, false, 0.5d);
assertEquals(1d, eval.getPrecision(), 1e-4);
assertEquals(10, eval.getTestSize());
assertEquals(90, eval.getTrainSize());
}
}
| [
"thomas.jungblut@gmail.com"
] | thomas.jungblut@gmail.com |
c46740fbb1e82bd5a78b5b050e943033fa62f8a1 | 197a4e62bcceea4d85d705d8935a0134c7c496a1 | /src/main/java/com/arms/domain/entity/LeaveHistory.java | 3e5fd0c1302ca86b147b7a983e27eeaec65c941f | [] | no_license | jajarrabbit/spring_hr_2017 | 18a4ca1698a09c65b9bacb8aeaa1a86819a1183f | 5b2ed0c62a1b73c09fb9349232652781d31548a3 | refs/heads/master | 2021-01-13T04:48:00.457725 | 2017-05-03T06:45:15 | 2017-05-03T06:45:15 | 78,701,536 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,054 | java | package com.arms.domain.entity;
import lombok.Data;
import javax.persistence.*;
import java.io.StringReader;
import java.util.Date;
/**
* Created by arms20170106 on 13/1/2560.
*/
@Data
@Entity
@Table(name = "leave_history")
public class LeaveHistory {
private Integer leaveId;
@Id
@GeneratedValue
@Column(name = "leave_id")
public Integer getLeaveId() {
return leaveId;
}
public void setLeaveId(Integer leaveId) {
this.leaveId = leaveId;
}
private Integer empId;
@Basic
@Column(name = "emp_id")
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
private Employee employee;
@ManyToOne
@JoinColumn(name = "emp_id", insertable = false, updatable = false)
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
private Date periodFrom;
@Basic
@Column(name = "period_from")
public Date getPeriodFrom() {
return periodFrom;
}
public void setPeriodFrom(Date periodFrom) {
this.periodFrom = periodFrom;
}
private Date periodUntil;
@Basic
@Column(name = "period_until")
public Date getPeriodUntil() {
return periodUntil;
}
public void setPeriodUntil(Date periodUntil) {
this.periodUntil = periodUntil;
}
private Integer categoryId;
@Basic
@Column(name = "category_id")
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
private LeaveType leaveType;
@ManyToOne
@JoinColumn(name = "category_id", insertable = false, updatable = false)
public LeaveType getLeaveType() {
return leaveType;
}
public void setLeaveType(LeaveType leaveType) {
this.leaveType = leaveType;
}
private String reason;
@Basic
@Column(name = "reason")
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
private String remark;
@Basic
@Column(name = "remark")
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
private Integer fullday;
@Basic
@Column(name = "fullday")
public Integer getFullday() {
return fullday;
}
public void setFullday(Integer fullday) {
this.fullday = fullday;
}
private Integer halfday;
@Basic
@Column(name = "halfday")
public Integer getHalfday() {
return halfday;
}
public void setHalfday(Integer halfday) {
this.halfday = halfday;
}
private Integer approve;
@Basic
@Column(name = "approve")
public Integer getApprove(){return approve;}
public void setApprove(Integer approve) {this.approve = approve;}
} | [
"benz.s@arms-thai.com"
] | benz.s@arms-thai.com |
d9b15c04697e395788bfadf6fb437b83d7e2c1e8 | a462db838066e14f99e2ac4ef7467da78eee28a9 | /CCIP CODES/WEEK 6/Consecutive_capital_letters.java | 8a22c51d1afa14f62860925936827138f68a1bc2 | [] | no_license | mad-99/YashKumar15480.github.io | e38cce93125e25385622fe0800a3cf775a723b0a | cd73f12e5041f2188d728d188940f9965859eb6c | refs/heads/main | 2023-06-16T04:49:03.382405 | 2021-07-17T16:26:30 | 2021-07-17T16:26:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 816 | java | import java.io.*;
import java.util.*;
import java.lang.*;
public class Solution {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a=sc.next();
char ch[] = a.toCharArray();
int flag=0;
for(int i=0;i<a.length();i++)
{
if(Character.isUpperCase(ch[i]) && Character.isUpperCase(ch[i+1]))
{
flag++; break;
/*if(ch[i+1]==ch[i]+2)
{
if(Character.isUpperCase(ch[i+1]))
{
//System.out.print("2Yes");
flag++;
break;
}
}
}*/
}}
if(flag==1)System.out.print("Yes");
else System.out.print("No");
}
} | [
"noreply@github.com"
] | mad-99.noreply@github.com |
bba4c1f9ce0d8b069152f994a15fc05e66370f68 | a74bcf1c0f9e047afd46d4a7b9ad264e27946081 | /Java/Android/OpenGLES/source/core/src/loon/core/graphics/LColorPool.java | 39f7e2aee839dcc3acb659dc07474bd0e9cba89a | [
"Apache-2.0"
] | permissive | windows10207/LGame | 7a260b64dcdac5e1bbde415e5f801691d3bfb9fd | 4599507d737a79b27d8f685f7aa542fd9f936cf7 | refs/heads/master | 2021-01-12T20:15:38.080295 | 2014-09-22T17:12:08 | 2014-09-22T17:12:08 | 24,441,072 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,480 | java | /**
* Copyright 2008 - 2012
*
* 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.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.3.3
*/
package loon.core.graphics;
import java.util.HashMap;
import loon.core.LRelease;
import loon.core.LSystem;
public class LColorPool implements LRelease {
private static LColorPool pool;
public static LColorPool $() {
synchronized (LColorPool.class) {
if (pool == null) {
pool = new LColorPool();
}
}
return pool;
}
private final LColor AlphaColor = new LColor(0f, 0f, 0f, 0f);
private HashMap<Integer, LColor> ColorMap = new HashMap<Integer, LColor>();
public LColor getColor(float r, float g, float b, float a) {
if (a <= 0.1f) {
return AlphaColor;
}
int hashCode = 1;
hashCode = LSystem.unite(hashCode, r);
hashCode = LSystem.unite(hashCode, g);
hashCode = LSystem.unite(hashCode, b);
hashCode = LSystem.unite(hashCode, a);
LColor color = ColorMap.get(hashCode);
if (color == null) {
color = new LColor(r, g, b, a);
ColorMap.put(hashCode, color);
}
return color;
}
public LColor getColor(int c) {
LColor color = ColorMap.get(c);
if (color == null) {
color = new LColor(c);
ColorMap.put(c, color);
}
return color;
}
public LColor getColor(float r, float g, float b) {
return getColor(r, g, b, 1f);
}
public LColor getColor(int r, int g, int b, int a) {
if (a <= 10) {
return AlphaColor;
}
int hashCode = 1;
hashCode = LSystem.unite(hashCode, r);
hashCode = LSystem.unite(hashCode, g);
hashCode = LSystem.unite(hashCode, b);
hashCode = LSystem.unite(hashCode, a);
LColor color = ColorMap.get(hashCode);
if (color == null) {
color = new LColor(r, g, b, a);
ColorMap.put(hashCode, color);
}
return color;
}
public LColor getColor(int r, int g, int b) {
return getColor(r, g, b, 1f);
}
@Override
public void dispose() {
if (ColorMap != null) {
ColorMap.clear();
}
}
}
| [
"longwind2012@hotmail.com"
] | longwind2012@hotmail.com |
80ca636f61f267b508de409b3b037be38fd84080 | bd2139703c556050403c10857bde66f688cd9ee6 | /skara/601/webrev.01-02/bots/merge/src/test/java/org/openjdk/skara/bots/merge/MergeBotTests.java | a7334a352929ecddab8b6122cef8b9c5f691a120 | [] | no_license | isabella232/cr-archive | d03427e6fbc708403dd5882d36371e1b660ec1ac | 8a3c9ddcfacb32d1a65d7ca084921478362ec2d1 | refs/heads/master | 2023-02-01T17:33:44.383410 | 2020-12-17T13:47:48 | 2020-12-17T13:47:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 47,919 | java | /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.skara.bots.merge;
import org.openjdk.skara.host.*;
import org.openjdk.skara.test.*;
import org.openjdk.skara.vcs.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.stream.Collectors;
import java.time.DayOfWeek;
import java.time.Month;
import java.time.ZonedDateTime;
import java.time.ZoneId;
import static org.junit.jupiter.api.Assertions.*;
class MergeBotTests {
@Test
void mergeMasterBranch(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test-mirror", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b.txt", "duke", "duke@openjdk.org");
var toFileC = toDir.resolve("c.txt");
Files.writeString(toFileC, "Hello C\n");
toLocalRepo.add(toFileC);
var toHashC = toLocalRepo.commit("Adding c.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs);
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
var hashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(hashes.contains(toHashA));
assertTrue(hashes.contains(fromHashB));
assertTrue(hashes.contains(toHashC));
var known = Set.of(toHashA, fromHashB, toHashC);
var merge = toCommits.stream().filter(c -> !known.contains(c.hash())).findAny().get();
assertTrue(merge.isMerge());
assertEquals(List.of("Automatic merge of test:master into master"), merge.message());
assertEquals("duke", merge.author().name());
assertEquals("duke@openjdk.org", merge.author().email());
assertEquals(0, toHostedRepo.pullRequests().size());
}
}
@Test
void failingMergeTest(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test-mirror", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B1\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b1.txt", "duke", "duke@openjdk.org");
var toFileB = toDir.resolve("b.txt");
Files.writeString(toFileB, "Hello B2\n");
toLocalRepo.add(toFileB);
var toHashB = toLocalRepo.commit("Adding b2.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs);
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
var toHashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(toHashes.contains(toHashA));
assertTrue(toHashes.contains(toHashB));
var pullRequests = toHostedRepo.pullRequests();
assertEquals(1, pullRequests.size());
var pr = pullRequests.get(0);
assertEquals("Merge test:master", pr.title());
assertTrue(pr.labels().contains("failed-auto-merge"));
}
}
@Test
void failingMergeShouldResultInOnlyOnePR(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test-mirror", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B1\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b1.txt", "duke", "duke@openjdk.org");
var toFileB = toDir.resolve("b.txt");
Files.writeString(toFileB, "Hello B2\n");
toLocalRepo.add(toFileB);
var toHashB = toLocalRepo.commit("Adding b2.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs);
TestBotRunner.runPeriodicItems(bot);
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
var toHashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(toHashes.contains(toHashA));
assertTrue(toHashes.contains(toHashB));
var pullRequests = toHostedRepo.pullRequests();
assertEquals(1, pullRequests.size());
var pr = pullRequests.get(0);
assertEquals("Merge test:master", pr.title());
}
}
@Test
void resolvedMergeConflictShouldResultInIntegrateCommand(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test-mirror", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B1\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b1.txt", "duke", "duke@openjdk.org", now);
var toFileB = toDir.resolve("b.txt");
Files.writeString(toFileB, "Hello B2\n");
toLocalRepo.add(toFileB);
var toHashB = toLocalRepo.commit("Adding b2.txt", "duke", "duke@openjdk.org", now);
var storage = temp.path().resolve("storage");
var master = new Branch("master");
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs);
TestBotRunner.runPeriodicItems(bot);
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
var toHashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(toHashes.contains(toHashA));
assertTrue(toHashes.contains(toHashB));
var pullRequests = toHostedRepo.pullRequests();
assertEquals(1, pullRequests.size());
var pr = pullRequests.get(0);
assertEquals("Merge test:master", pr.title());
assertTrue(pr.labels().contains("failed-auto-merge"));
assertTrue(forkLocalRepo.branches().contains(new Branch("master")));
assertTrue(forkLocalRepo.branches().contains(new Branch("2")));
// Bot should do nothing as long as PR is presnt
TestBotRunner.runPeriodicItems(bot);
pullRequests = toHostedRepo.pullRequests();
assertEquals(1, pullRequests.size());
pr = pullRequests.get(0);
// Simulate that the merge-conflict has been resolved by adding the "ready" label
pr.addLabel("ready");
TestBotRunner.runPeriodicItems(bot);
pullRequests = toHostedRepo.pullRequests();
assertEquals(1, pullRequests.size());
pr = pullRequests.get(0);
var numComments = pr.comments().size();
var lastComment = pr.comments().get(pr.comments().size() - 1);
assertEquals("/integrate", lastComment.body());
// Running the bot again should not result in another comment
TestBotRunner.runPeriodicItems(bot);
assertEquals(numComments, toHostedRepo.pullRequests().size());
}
}
final static class TestClock implements Clock {
ZonedDateTime now;
TestClock() {
this(null);
}
TestClock(ZonedDateTime now) {
this.now = now;
}
@Override
public ZonedDateTime now() {
return now;
}
}
@Test
void testMergeHourly(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test-mirror", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b.txt", "duke", "duke@openjdk.org");
var toFileC = toDir.resolve("c.txt");
Files.writeString(toFileC, "Hello C\n");
toLocalRepo.add(toFileC);
var toHashC = toLocalRepo.commit("Adding c.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
// Merge only at most once during the first minute every hour
var freq = MergeBot.Spec.Frequency.hourly(1);
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master, freq));
var clock = new TestClock(ZonedDateTime.of(2020, 1, 23, 15, 0, 0, 0, ZoneId.of("GMT+1")));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs, clock);
TestBotRunner.runPeriodicItems(bot);
// Ensure nothing has been merged
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
assertEquals(toHashC, toCommits.get(0).hash());
assertEquals(toHashA, toCommits.get(1).hash());
// Set the clock to the first minute of the hour
clock.now = ZonedDateTime.of(2020, 1, 23, 15, 1, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
// Should have merged
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
var hashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(hashes.contains(toHashA));
assertTrue(hashes.contains(fromHashB));
assertTrue(hashes.contains(toHashC));
var known = Set.of(toHashA, fromHashB, toHashC);
var merge = toCommits.stream().filter(c -> !known.contains(c.hash())).findAny().get();
assertTrue(merge.isMerge());
assertEquals(List.of("Automatic merge of test:master into master"), merge.message());
assertEquals("duke", merge.author().name());
assertEquals("duke@openjdk.org", merge.author().email());
assertEquals(0, toHostedRepo.pullRequests().size());
var fromFileD = fromDir.resolve("d.txt");
Files.writeString(fromFileD, "Hello D\n");
fromLocalRepo.add(fromFileD);
var fromHashD = fromLocalRepo.commit("Adding d.txt", "duke", "duke@openjdk.org");
// Since the time hasn't changed it should not merge again
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the minutes forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 1, 23, 15, 45, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the clock forward one hour, the bot should merge
clock.now = ZonedDateTime.of(2020, 1, 23, 16, 1, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(6, toCommits.size());
}
}
@Test
void testMergeDaily(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b.txt", "duke", "duke@openjdk.org");
var toFileC = toDir.resolve("c.txt");
Files.writeString(toFileC, "Hello C\n");
toLocalRepo.add(toFileC);
var toHashC = toLocalRepo.commit("Adding c.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
// Merge only at most once during the third hour every day
var freq = MergeBot.Spec.Frequency.daily(3);
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master, freq));
var clock = new TestClock(ZonedDateTime.of(2020, 1, 23, 2, 45, 0, 0, ZoneId.of("GMT+1")));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs, clock);
TestBotRunner.runPeriodicItems(bot);
// Ensure nothing has been merged
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
assertEquals(toHashC, toCommits.get(0).hash());
assertEquals(toHashA, toCommits.get(1).hash());
// Set the clock to the third hour of the day (minutes should not matter)
clock.now = ZonedDateTime.of(2020, 1, 23, 3, 37, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
// Should have merged
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
var hashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(hashes.contains(toHashA));
assertTrue(hashes.contains(fromHashB));
assertTrue(hashes.contains(toHashC));
var known = Set.of(toHashA, fromHashB, toHashC);
var merge = toCommits.stream().filter(c -> !known.contains(c.hash())).findAny().get();
assertTrue(merge.isMerge());
assertEquals(List.of("Automatic merge of master into master"), merge.message());
assertEquals("duke", merge.author().name());
assertEquals("duke@openjdk.org", merge.author().email());
assertEquals(0, toHostedRepo.pullRequests().size());
var fromFileD = fromDir.resolve("d.txt");
Files.writeString(fromFileD, "Hello D\n");
fromLocalRepo.add(fromFileD);
var fromHashD = fromLocalRepo.commit("Adding d.txt", "duke", "duke@openjdk.org");
// Since the time hasn't changed it should not merge
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the minutes forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 1, 23, 3, 45, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the hours forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 1, 23, 17, 45, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the clock forward one day, the bot should merge
clock.now = ZonedDateTime.of(2020, 1, 24, 3, 55, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(6, toCommits.size());
}
}
@Test
void testMergeWeekly(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test-mirror", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b.txt", "duke", "duke@openjdk.org");
var toFileC = toDir.resolve("c.txt");
Files.writeString(toFileC, "Hello C\n");
toLocalRepo.add(toFileC);
var toHashC = toLocalRepo.commit("Adding c.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
// Merge only at most once per week on Friday's at 12:00
var freq = MergeBot.Spec.Frequency.weekly(DayOfWeek.FRIDAY, 12);
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master, freq));
var clock = new TestClock(ZonedDateTime.of(2020, 1, 24, 11, 45, 0, 0, ZoneId.of("GMT+1")));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs, clock);
TestBotRunner.runPeriodicItems(bot);
// Ensure nothing has been merged
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
assertEquals(toHashC, toCommits.get(0).hash());
assertEquals(toHashA, toCommits.get(1).hash());
// Set the clock to the 12th hour of the day (minutes should not matter)
clock.now = ZonedDateTime.of(2020, 1, 24, 12, 37, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
// Should have merged
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
var hashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(hashes.contains(toHashA));
assertTrue(hashes.contains(fromHashB));
assertTrue(hashes.contains(toHashC));
var known = Set.of(toHashA, fromHashB, toHashC);
var merge = toCommits.stream().filter(c -> !known.contains(c.hash())).findAny().get();
assertTrue(merge.isMerge());
assertEquals(List.of("Automatic merge of test:master into master"), merge.message());
assertEquals("duke", merge.author().name());
assertEquals("duke@openjdk.org", merge.author().email());
assertEquals(0, toHostedRepo.pullRequests().size());
var fromFileD = fromDir.resolve("d.txt");
Files.writeString(fromFileD, "Hello D\n");
fromLocalRepo.add(fromFileD);
var fromHashD = fromLocalRepo.commit("Adding d.txt", "duke", "duke@openjdk.org");
// Since the time hasn't changed it should not merge
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the hours forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 1, 24, 13, 45, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the days forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 1, 25, 13, 45, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the clock forward one week, the bot should merge
clock.now = ZonedDateTime.of(2020, 1, 31, 12, 29, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(6, toCommits.size());
}
}
@Test
void testMergeMonthly(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b.txt", "duke", "duke@openjdk.org");
var toFileC = toDir.resolve("c.txt");
Files.writeString(toFileC, "Hello C\n");
toLocalRepo.add(toFileC);
var toHashC = toLocalRepo.commit("Adding c.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
// Merge only at most once per month on the 17th day at at 11:00
var freq = MergeBot.Spec.Frequency.monthly(17, 11);
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master, freq));
var clock = new TestClock(ZonedDateTime.of(2020, 1, 16, 11, 0, 0, 0, ZoneId.of("GMT+1")));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs, clock);
TestBotRunner.runPeriodicItems(bot);
// Ensure nothing has been merged
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
assertEquals(toHashC, toCommits.get(0).hash());
assertEquals(toHashA, toCommits.get(1).hash());
// Set the clock to the 17th day and at hour 11 (minutes should not matter)
clock.now = ZonedDateTime.of(2020, 1, 17, 11, 37, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
// Should have merged
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
var hashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(hashes.contains(toHashA));
assertTrue(hashes.contains(fromHashB));
assertTrue(hashes.contains(toHashC));
var known = Set.of(toHashA, fromHashB, toHashC);
var merge = toCommits.stream().filter(c -> !known.contains(c.hash())).findAny().get();
assertTrue(merge.isMerge());
assertEquals(List.of("Automatic merge of master into master"), merge.message());
assertEquals("duke", merge.author().name());
assertEquals("duke@openjdk.org", merge.author().email());
assertEquals(0, toHostedRepo.pullRequests().size());
var fromFileD = fromDir.resolve("d.txt");
Files.writeString(fromFileD, "Hello D\n");
fromLocalRepo.add(fromFileD);
var fromHashD = fromLocalRepo.commit("Adding d.txt", "duke", "duke@openjdk.org");
// Since the time hasn't changed it should not merge
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the hours forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 1, 17, 12, 45, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the days forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 1, 18, 11, 0, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the clock forward one month, the bot should merge
clock.now = ZonedDateTime.of(2020, 2, 17, 11, 55, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(6, toCommits.size());
}
}
@Test
void testMergeYearly(TestInfo testInfo) throws IOException {
try (var temp = new TemporaryDirectory()) {
var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));
var fromDir = temp.path().resolve("from.git");
var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);
var toDir = temp.path().resolve("to.git");
var toLocalRepo = Repository.init(toDir, VCS.GIT);
var toGitConfig = toDir.resolve(".git").resolve("config");
Files.write(toGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toHostedRepo = new TestHostedRepository(host, "test", toLocalRepo);
var forkDir = temp.path().resolve("fork.git");
var forkLocalRepo = Repository.init(forkDir, VCS.GIT);
var forkGitConfig = forkDir.resolve(".git").resolve("config");
Files.write(forkGitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
StandardOpenOption.APPEND);
var toFork = new TestHostedRepository(host, "test-mirror-fork", forkLocalRepo);
var now = ZonedDateTime.now();
var fromFileA = fromDir.resolve("a.txt");
Files.writeString(fromFileA, "Hello A\n");
fromLocalRepo.add(fromFileA);
var fromHashA = fromLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var fromCommits = fromLocalRepo.commits().asList();
assertEquals(1, fromCommits.size());
assertEquals(fromHashA, fromCommits.get(0).hash());
var toFileA = toDir.resolve("a.txt");
Files.writeString(toFileA, "Hello A\n");
toLocalRepo.add(toFileA);
var toHashA = toLocalRepo.commit("Adding a.txt", "duke", "duke@openjdk.org", now);
var toCommits = toLocalRepo.commits().asList();
assertEquals(1, toCommits.size());
assertEquals(toHashA, toCommits.get(0).hash());
assertEquals(fromHashA, toHashA);
var fromFileB = fromDir.resolve("b.txt");
Files.writeString(fromFileB, "Hello B\n");
fromLocalRepo.add(fromFileB);
var fromHashB = fromLocalRepo.commit("Adding b.txt", "duke", "duke@openjdk.org");
var toFileC = toDir.resolve("c.txt");
Files.writeString(toFileC, "Hello C\n");
toLocalRepo.add(toFileC);
var toHashC = toLocalRepo.commit("Adding c.txt", "duke", "duke@openjdk.org");
var storage = temp.path().resolve("storage");
var master = new Branch("master");
// Merge only at most once per year on the 29th day of May at at 07:00
var freq = MergeBot.Spec.Frequency.yearly(Month.MAY, 29, 07);
var specs = List.of(new MergeBot.Spec(fromHostedRepo, master, master, freq));
var clock = new TestClock(ZonedDateTime.of(2020, 5, 27, 11, 0, 0, 0, ZoneId.of("GMT+1")));
var bot = new MergeBot(storage, toHostedRepo, toFork, specs, clock);
TestBotRunner.runPeriodicItems(bot);
// Ensure nothing has been merged
toCommits = toLocalRepo.commits().asList();
assertEquals(2, toCommits.size());
assertEquals(toHashC, toCommits.get(0).hash());
assertEquals(toHashA, toCommits.get(1).hash());
// Set the clock to the 29th of May and at hour 11 (minutes should not matter)
clock.now = ZonedDateTime.of(2020, 5, 29, 7, 37, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
// Should have merged
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
var hashes = toCommits.stream().map(Commit::hash).collect(Collectors.toSet());
assertTrue(hashes.contains(toHashA));
assertTrue(hashes.contains(fromHashB));
assertTrue(hashes.contains(toHashC));
var known = Set.of(toHashA, fromHashB, toHashC);
var merge = toCommits.stream().filter(c -> !known.contains(c.hash())).findAny().get();
assertTrue(merge.isMerge());
assertEquals(List.of("Automatic merge of master into master"), merge.message());
assertEquals("duke", merge.author().name());
assertEquals("duke@openjdk.org", merge.author().email());
assertEquals(0, toHostedRepo.pullRequests().size());
var fromFileD = fromDir.resolve("d.txt");
Files.writeString(fromFileD, "Hello D\n");
fromLocalRepo.add(fromFileD);
var fromHashD = fromLocalRepo.commit("Adding d.txt", "duke", "duke@openjdk.org");
// Since the time hasn't changed it should not merge again
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the hours forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 5, 29, 8, 45, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the days forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 5, 30, 11, 0, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the months forward, the bot should not merge
clock.now = ZonedDateTime.of(2020, 7, 29, 7, 0, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(4, toCommits.size());
// Move the clock forward one year, the bot should merge
clock.now = ZonedDateTime.of(2021, 5, 29, 7, 55, 0, 0, ZoneId.of("GMT+1"));
TestBotRunner.runPeriodicItems(bot);
toCommits = toLocalRepo.commits().asList();
assertEquals(6, toCommits.size());
}
}
}
| [
"robin.westberg@oracle.com"
] | robin.westberg@oracle.com |
811ee6fe6c6d8bf34e6264d09707538906347360 | 88eeb93f5a179490faa700f5d7f1ae0217f9bdd9 | /src/main/java/pl/maciejwalkowiak/plist/handler/SimpleHandler.java | f074d7af940132f65f4402040358c50fdcd4f1b6 | [] | no_license | uddhav/java-plist-serializer | de915f9c9337cbf80d47ed0acdeaff23d321f6a4 | 24f2045ed448ebf93573934876ab2035e7b76ea8 | refs/heads/master | 2020-12-25T13:23:35.881499 | 2012-11-15T07:27:44 | 2012-11-15T07:27:44 | 6,698,530 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | java | package pl.maciejwalkowiak.plist.handler;
import pl.maciejwalkowiak.plist.XMLHelper;
/**
* Handler that just wraps object around key
*/
public abstract class SimpleHandler implements Handler {
public String handle(Object object) {
if (supports(object)) {
return XMLHelper.wrap(object).with(getWrap());
} else {
throw new ObjectNotSupportedException("Handler does not support: " + object);
}
}
protected abstract String getWrap();
}
| [
"maciej.walkowiak@young-internet.com"
] | maciej.walkowiak@young-internet.com |
5ab6bf5e10ed2c389f551657e5ef600bbd6f0f41 | 00b85668294e2b729d4649b11309ab785e6adef6 | /eclipse/1110f_TP3_TP4/src/uml/impl/TemplateSignatureImpl.java | 95e61c5d457350bb33fbd92e0fc7423074cbd127 | [] | no_license | Doelia/M2-modeles | d61eb955ba4a48ef473f17164847db90c091261f | 1030fff0775e60cc2a002d624bc07a8825d355ff | refs/heads/master | 2021-01-25T05:34:08.814437 | 2015-12-02T09:34:39 | 2015-12-02T09:34:39 | 42,939,571 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,903 | java | /**
*/
package uml.impl;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Map;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import org.eclipse.emf.ecore.util.EObjectValidator;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.InternalEList;
import uml.TemplateParameter;
import uml.TemplateSignature;
import uml.TemplateableElement;
import uml.UmlPackage;
import uml.util.UmlValidator;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Template Signature</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link uml.impl.TemplateSignatureImpl#getParameter <em>Parameter</em>}</li>
* <li>{@link uml.impl.TemplateSignatureImpl#getOwnedParameter <em>Owned Parameter</em>}</li>
* <li>{@link uml.impl.TemplateSignatureImpl#getTemplate <em>Template</em>}</li>
* </ul>
*
* @generated
*/
public class TemplateSignatureImpl extends ElementImpl implements TemplateSignature {
/**
* The cached value of the '{@link #getParameter() <em>Parameter</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameter()
* @generated
* @ordered
*/
protected EList<TemplateParameter> parameter;
/**
* The cached value of the '{@link #getOwnedParameter() <em>Owned Parameter</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOwnedParameter()
* @generated
* @ordered
*/
protected EList<TemplateParameter> ownedParameter;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TemplateSignatureImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return UmlPackage.eINSTANCE.getTemplateSignature();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TemplateParameter> getParameter() {
if (parameter == null) {
parameter = new EObjectResolvingEList<TemplateParameter>(TemplateParameter.class, this, UmlPackage.TEMPLATE_SIGNATURE__PARAMETER);
}
return parameter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TemplateParameter> getOwnedParameter() {
if (ownedParameter == null) {
ownedParameter = new EObjectContainmentWithInverseEList<TemplateParameter>(TemplateParameter.class, this, UmlPackage.TEMPLATE_SIGNATURE__OWNED_PARAMETER, UmlPackage.TEMPLATE_PARAMETER__SIGNATURE);
}
return ownedParameter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TemplateableElement getTemplate() {
if (eContainerFeatureID() != UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE) return null;
return (TemplateableElement)eInternalContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetTemplate(TemplateableElement newTemplate, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newTemplate, UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTemplate(TemplateableElement newTemplate) {
if (newTemplate != eInternalContainer() || (eContainerFeatureID() != UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE && newTemplate != null)) {
if (EcoreUtil.isAncestor(this, newTemplate))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newTemplate != null)
msgs = ((InternalEObject)newTemplate).eInverseAdd(this, UmlPackage.TEMPLATEABLE_ELEMENT__OWNED_TEMPLATE_SIGNATURE, TemplateableElement.class, msgs);
msgs = basicSetTemplate(newTemplate, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE, newTemplate, newTemplate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean own_elements(DiagnosticChain diagnostics, Map<Object, Object> context) {
// TODO: implement this method
// -> specify the condition that violates the invariant
// -> verify the details of the diagnostic, including severity and message
// Ensure that you remove @generated or mark it @generated NOT
if (false) {
if (diagnostics != null) {
diagnostics.add
(new BasicDiagnostic
(Diagnostic.ERROR,
UmlValidator.DIAGNOSTIC_SOURCE,
UmlValidator.TEMPLATE_SIGNATURE__OWN_ELEMENTS,
EcorePlugin.INSTANCE.getString("_UI_GenericInvariant_diagnostic", new Object[] { "own_elements", EObjectValidator.getObjectLabel(this, context) }),
new Object [] { this }));
}
return false;
}
return true;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case UmlPackage.TEMPLATE_SIGNATURE__OWNED_PARAMETER:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getOwnedParameter()).basicAdd(otherEnd, msgs);
case UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetTemplate((TemplateableElement)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case UmlPackage.TEMPLATE_SIGNATURE__OWNED_PARAMETER:
return ((InternalEList<?>)getOwnedParameter()).basicRemove(otherEnd, msgs);
case UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE:
return basicSetTemplate(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE:
return eInternalContainer().eInverseRemove(this, UmlPackage.TEMPLATEABLE_ELEMENT__OWNED_TEMPLATE_SIGNATURE, TemplateableElement.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case UmlPackage.TEMPLATE_SIGNATURE__PARAMETER:
return getParameter();
case UmlPackage.TEMPLATE_SIGNATURE__OWNED_PARAMETER:
return getOwnedParameter();
case UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE:
return getTemplate();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case UmlPackage.TEMPLATE_SIGNATURE__PARAMETER:
getParameter().clear();
getParameter().addAll((Collection<? extends TemplateParameter>)newValue);
return;
case UmlPackage.TEMPLATE_SIGNATURE__OWNED_PARAMETER:
getOwnedParameter().clear();
getOwnedParameter().addAll((Collection<? extends TemplateParameter>)newValue);
return;
case UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE:
setTemplate((TemplateableElement)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case UmlPackage.TEMPLATE_SIGNATURE__PARAMETER:
getParameter().clear();
return;
case UmlPackage.TEMPLATE_SIGNATURE__OWNED_PARAMETER:
getOwnedParameter().clear();
return;
case UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE:
setTemplate((TemplateableElement)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case UmlPackage.TEMPLATE_SIGNATURE__PARAMETER:
return parameter != null && !parameter.isEmpty();
case UmlPackage.TEMPLATE_SIGNATURE__OWNED_PARAMETER:
return ownedParameter != null && !ownedParameter.isEmpty();
case UmlPackage.TEMPLATE_SIGNATURE__TEMPLATE:
return getTemplate() != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
@SuppressWarnings("unchecked")
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case UmlPackage.TEMPLATE_SIGNATURE___OWN_ELEMENTS__DIAGNOSTICCHAIN_MAP:
return own_elements((DiagnosticChain)arguments.get(0), (Map<Object, Object>)arguments.get(1));
}
return super.eInvoke(operationID, arguments);
}
} //TemplateSignatureImpl
| [
"kyxalia@gmail.com"
] | kyxalia@gmail.com |
66ecbd93ed97fbe15fae16eb393841d2f7ce3b41 | 42b0272e290dc4d29ba7eaf88c84e574dea54f89 | /src/main/java/com/proxymcommunity/proxymCommunity/ProxymCommunityApplication.java | 3c6f8b209c229a43ceae0b7f47688e2f533bacd1 | [] | no_license | Firas-Secref/proxymCommunity | 59d7bc57c52210f01c2e0669ff1affe89e32a71b | ae8d3d8562e1b58899491ea25599c496f44a0009 | refs/heads/master | 2023-07-03T06:55:20.396531 | 2021-08-11T16:59:52 | 2021-08-11T16:59:52 | 382,375,806 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 346 | java | package com.proxymcommunity.proxymCommunity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProxymCommunityApplication {
public static void main(String[] args) {
SpringApplication.run(ProxymCommunityApplication.class, args);
}
}
| [
"sh.firas10@gmail.com"
] | sh.firas10@gmail.com |
d88a441286e64da14935d13bdc8a5e11b1582a81 | d54f891f3065506592da61460340f2e14dc1a393 | /src/test/java/ch/tbmelabs/springbootadmin/test/configuration/ActuatorEndpointSecurityConfigurationTest.java | 79483f99b138712e86d62e45fdf0cec4234d8ff8 | [
"MIT"
] | permissive | tbmelabs/tbmelabs-spring-boot-admin | 276681898e77bc1468203b4003474fdc5c7aa5b9 | 8296ab57b47c0d93149807042207abc85f4d9c30 | refs/heads/master | 2020-04-01T12:45:29.152185 | 2018-10-16T08:03:14 | 2018-10-16T08:03:14 | 153,222,290 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 799 | java | package ch.tbmelabs.springbootadmin.test.configuration;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.springframework.context.annotation.Configuration;
import ch.tbmelabs.actuatorendpointssecurityutils.annotation.EnableActuatorEndpointSecurity;
import ch.tbmelabs.springbootadmin.configuration.ActuatorEndpointSecurityConfiguration;
public class ActuatorEndpointSecurityConfigurationTest {
@Test
public void shouldBeAnnotated() {
assertThat(ActuatorEndpointSecurityConfiguration.class).hasAnnotation(Configuration.class)
.hasAnnotation(EnableActuatorEndpointSecurity.class);
}
@Test
public void shouldHavePublicConstructor() {
assertThat(new ActuatorEndpointSecurityConfiguration()).isNotNull();
}
}
| [
"timon.borter@post.ch"
] | timon.borter@post.ch |
40ea55f712cfb94264766dbf982c74da41281eed | 8b03b9ff5b57e48c90fdc94a421112523ae593e0 | /tests/testSimpleStatic.java | ce5edc5e195ec0a05188a845381b6c01c2a033a2 | [] | no_license | yang123vc/oop-project | 87c3ab68849295ab87d3551a9084cb432b4f85ca | a1d75cf8a729dea14f3bb47c2737e99c876801c5 | refs/heads/master | 2021-01-13T09:51:37.058026 | 2011-12-20T02:36:36 | 2011-12-20T02:36:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 672 | java | public class testSimpleStatic{
public static int getNum(){
return (4 + 4) * 12;
}
public static int getAge(){
return 5;
}
public static int getCount(){
return 40000;
}
public int getNumber(){
return 6;
}
public static void main(String [] args)
{
//System.out.println(Andrew.getCount());
//Andrew a = new Andrew("lolz");
//System.out.println(a.getCount());
//System.out.println(a.getAge());
//System.out.println(a.getLink());
System.out.println(getNum());
System.out.println(getAge());
System.out.println(getCount());
}
}
| [
"calvinhawkes@gmail.com"
] | calvinhawkes@gmail.com |
17b5a5115c4a8e3be56ebfd1a45f2f1e223bd9e6 | 5985a8bcd0126f05dc43e5f650e2efbb83235c05 | /app/src/main/java/com/example/dilani/itentproj/FirstActivity.java | 21d02bd5d9c12d63829e735ecbefeb8f490b3bca | [] | no_license | RashithaDileeshan/MadLabTute | eecb3208d4e79af3df5802b19f1624c4edea82d6 | d1fdae951f8ff4aad5150d2daadb3831c9b8bbd4 | refs/heads/master | 2020-06-26T23:18:02.029633 | 2019-07-31T05:31:21 | 2019-07-31T05:31:21 | 199,785,096 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 979 | java | package com.example.dilani.itentproj;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class FirstActivity extends AppCompatActivity {
public static final String NUMBER_1= "1";
public static final String NUMBER_2= "2";
private EditText num1,num2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
num1 = findViewById(R.id.editText2);
num2 = findViewById(R.id.editText4);
}
public void onClick (View view)
{
String no1 = num1.getText().toString();
String no2 = num2.getText().toString();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(NUMBER_1,no1);
intent.putExtra(NUMBER_2,no2);
startActivity(intent);
}
}
| [
"rashbatugedara9@gmail.com"
] | rashbatugedara9@gmail.com |
1c5aa873d8d6b8ad0663c9d45da36f945df333bd | d85196d81a249c2dd60e5e557c379c5299743897 | /src/main/java/org/web3j/abi/datatypes/generated/Fixed24x208.java | f539ab5ee0ebf68e0e7d3ee337d1b222085795b0 | [
"Apache-2.0"
] | permissive | nicksavers/web3j | 0861b2415975796baf48a2e7a5b24006bfbbefc8 | 97a4f38911156e961651dd288cf4c4560fa915c8 | refs/heads/master | 2020-07-27T23:48:06.643337 | 2016-11-10T21:52:37 | 2016-11-10T21:52:37 | 73,422,064 | 2 | 0 | null | 2016-11-10T21:24:50 | 2016-11-10T21:24:49 | null | UTF-8 | Java | false | false | 476 | java | package org.web3j.abi.datatypes.generated;
import java.math.BigInteger;
import org.web3j.abi.datatypes.Fixed;
/**
* <p>Auto generated code.<br>
* <strong>Do not modifiy!</strong><br>
* Please use Generator located in project X to update.</p>
*/
public class Fixed24x208 extends Fixed {
public Fixed24x208(BigInteger value) {
super(24, 208, value);
}
public Fixed24x208(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
super(24, 208, m, n);
}
}
| [
"conor10@gmail.com"
] | conor10@gmail.com |
99e60de75ef3be18f2d3752cdc37bdd5d9230e9b | 8358b567471ba20a1e86b30867ebbcca7af32b17 | /src/main/java/com/timur/pet_project/validator/Validator.java | 6bb1f46cb312c439328e36933a9f07e1ebf5a542 | [] | no_license | krangii17/webApp_without_frameworks | d9a21f5fed9450cf7f55f138a8d6370a280b6ea7 | e06e10b54692126ae3befa505f5022542cd94e56 | refs/heads/master | 2022-05-05T11:39:21.368225 | 2019-07-27T18:32:26 | 2019-07-27T18:32:26 | 157,877,851 | 3 | 0 | null | 2022-03-08T21:17:08 | 2018-11-16T14:24:30 | Java | UTF-8 | Java | false | false | 2,254 | java | package com.timur.pet_project.validator;
import com.timur.pet_project.dao.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern;
/**
* Created by timyr on 16.08.18.
*/
public class Validator {
static final Logger LOG = LoggerFactory.getLogger(Validator.class);
public boolean emailValidate(String email) {
if (email == null || email.isEmpty()) {
return false;
} else {
Pattern pattern = Pattern.compile(ValidatorEnum
.EMAIL_VALIDATOR
.getStatment());
return pattern.matcher(email).matches();
}
}
public boolean loginValidate(String login) {
if (login == null || login.isEmpty()) {
return false;
} else {
Pattern pattern = Pattern.compile(ValidatorEnum
.LOGIN_VALIDATOR
.getStatment());
return pattern.matcher(login).matches();
}
}
public boolean nameValidate(String name) {
if (name == null || name.isEmpty()) {
return false;
} else {
Pattern pattern = Pattern.compile(ValidatorEnum
.NAME_VALIDATOR
.getStatment());
return pattern.matcher(name).matches();
}
}
public boolean passwordValidate(String pass) {
if (pass == null || pass.isEmpty()) {
return false;
} else {
Pattern pattern = Pattern.compile(ValidatorEnum
.PASSWORD_VALIDATOR
.getStatment());
return pattern.matcher(pass).matches();
}
}
public boolean ageValidate(String age) {
if (age == null || age.isEmpty()) {
return false;
} else {
int intAge = Integer.parseInt(age);
if (intAge <= 5 || intAge >= 95) {
return false;
} else {
return true;
}
}
}
public boolean isUserRegistred(String email) {
UserDao userDao = new UserDao();
LOG.debug(userDao.getEntityByEmail(email).getEmail());
return userDao.getEntityByEmail(email).getEmail() == null;
}
}
| [
"timyrle45@gmail.com"
] | timyrle45@gmail.com |
e03e2da8bcbb35dc745439f63bdc43156f441667 | 008f76b33ed2e349c4482591dc85771049d6f895 | /src/test/java/com/horizon/leetcode/algorithms/Problem05Test.java | 680c5cceb5223a5d73347dddf058d12c2b334279 | [] | no_license | originer/Algorithmic-Practice | d4123fdc5c7857c9f3f1f87105bf76bc2a46dd66 | c5afcf17fefe91e1d8c00b92eea7ff71e10954a4 | refs/heads/master | 2021-06-01T17:08:40.957945 | 2019-12-02T08:32:53 | 2019-12-02T08:32:53 | 131,623,801 | 0 | 0 | null | 2020-10-13T04:36:19 | 2018-04-30T17:10:25 | Java | UTF-8 | Java | false | false | 1,475 | java | package com.horizon.leetcode.algorithms;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class Problem05Test {
@Test
public void shouldDetectLongestPalindrome() throws Exception {
final String input = "saasdcjkbkjnjnnknvjfknjnfjkvnjkfdnvjknfdkvjnkjfdnvkjnvjknjkgnbjkngkjvnjkgnbvkjngfreyh67ujrtyhytju789oijtnuk789oikmtul0oymmmmmmmmmmmmmmmm";
String l = Problem05.longestPalindrome(input);
assertThat(l, equalTo("mmmmmmmmmmmmmmmm"));
}
@Test
public void shouldFindLongestPalindromeString() throws Exception {
final String input = "racecar";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("racecar"));
}
@Test
public void shouldFindLongestPalindromeString_2() throws Exception {
final String input = "saas";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("saas"));
}
@Test
public void shouldFindLongestPalindromeString_3() throws Exception {
final String input = "forgeeksskeegfor";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("geeksskeeg"));
}
@Test
public void shouldFindLongestPalindromeString_4() throws Exception {
final String input = "abaccddccefe";
String s = Problem05.longestPalindrome1(input);
assertThat(s, equalTo("ccddcc"));
}
}
| [
"997072815@qq.com"
] | 997072815@qq.com |
11a428cf6ec740eb7f1960748eedfb2471b874cd | 684f50dd1ae58a766ce441d460214a4f7e693101 | /modules/escrow/escrow-fuyous-service/src/main/java/com/dimeng/p2p/escrow/fuyou/entity/TransactionQueryDetailedEntity.java | bf969a51eb1a3b0e21a8c0abed005db877d506c4 | [] | no_license | wang-shun/rainiee-core | a0361255e3957dd58f653ae922088219738e0d25 | 80a96b2ed36e3460282e9e21d4f031cfbd198e69 | refs/heads/master | 2020-03-29T16:40:18.372561 | 2018-09-22T10:05:17 | 2018-09-22T10:05:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,157 | java | package com.dimeng.p2p.escrow.fuyou.entity;
/**
*
* 交易查询接口明细实体类
*
* @author heshiping
* @version [版本号, 2015年5月25日]
*/
public class TransactionQueryDetailedEntity {
// 扩展类型
private String extTp;
// 交易日期
private String txnDate;
// 交易时分
private String txnTime;
// 交易请求方式
private String srcTp;
// 交易流水
private String mchntSsn;
// 交易金额
private String txnAmt;
// 成功交易金额
private String txnAmtSuc;
// 合同号
private String contractNo;
// 出账用户虚拟账户
private String outFuiouAcctNo;
// 出账用户名
private String outCustNo;
// 出账用户名称
private String outartifNm;
// 入账用户虚拟账户
private String inFuiouAcctNo;
// 入账用户名
private String inCustNo;
// 入账用户名称
private String inArtifNm;
// 交易备注
private String remark;
// 交易返回码
private String txnRspCd;
// 交易返回码描述
private String rspCdDesc;
public TransactionQueryDetailedEntity(){
}
public TransactionQueryDetailedEntity(String extTp, String txnDate,
String txnTime, String srcTp, String mchntSsn, String txnAmt,
String txnAmtSuc, String contractNo, String outFuiouAcctNo,
String outCustNo, String outartifNm, String inFuiouAcctNo,
String inCustNo, String inArtifNm, String remark, String txnRspCd,
String rspCdDesc) {
this.extTp = extTp;
this.txnDate = txnDate;
this.txnTime = txnTime;
this.srcTp = srcTp;
this.mchntSsn = mchntSsn;
this.txnAmt = txnAmt;
this.txnAmtSuc = txnAmtSuc;
this.contractNo = contractNo;
this.outFuiouAcctNo = outFuiouAcctNo;
this.outCustNo = outCustNo;
this.outartifNm = outartifNm;
this.inFuiouAcctNo = inFuiouAcctNo;
this.inCustNo = inCustNo;
this.inArtifNm = inArtifNm;
this.remark = remark;
this.txnRspCd = txnRspCd;
this.rspCdDesc = rspCdDesc;
}
public String getExtTp() {
return extTp;
}
public void setExtTp(String extTp) {
this.extTp = extTp;
}
public String getTxnDate() {
return txnDate;
}
public void setTxnDate(String txnDate) {
this.txnDate = txnDate;
}
public String getTxnTime() {
return txnTime;
}
public void setTxnTime(String txnTime) {
this.txnTime = txnTime;
}
public String getSrcTp() {
return srcTp;
}
public void setSrcTp(String srcTp) {
this.srcTp = srcTp;
}
public String getMchntSsn() {
return mchntSsn;
}
public void setMchntSsn(String mchntSsn) {
this.mchntSsn = mchntSsn;
}
public String getTxnAmt() {
return txnAmt;
}
public void setTxnAmt(String txnAmt) {
this.txnAmt = txnAmt;
}
public String getTxnAmtSuc() {
return txnAmtSuc;
}
public void setTxnAmtSuc(String txnAmtSuc) {
this.txnAmtSuc = txnAmtSuc;
}
public String getContractNo() {
return contractNo;
}
public void setContractNo(String contractNo) {
this.contractNo = contractNo;
}
public String getOutFuiouAcctNo() {
return outFuiouAcctNo;
}
public void setOutFuiouAcctNo(String outFuiouAcctNo) {
this.outFuiouAcctNo = outFuiouAcctNo;
}
public String getOutCustNo() {
return outCustNo;
}
public void setOutCustNo(String outCustNo) {
this.outCustNo = outCustNo;
}
public String getOutartifNm() {
return outartifNm;
}
public void setOutartifNm(String outartifNm) {
this.outartifNm = outartifNm;
}
public String getInFuiouAcctNo() {
return inFuiouAcctNo;
}
public void setInFuiouAcctNo(String inFuiouAcctNo) {
this.inFuiouAcctNo = inFuiouAcctNo;
}
public String getInCustNo() {
return inCustNo;
}
public void setInCustNo(String inCustNo) {
this.inCustNo = inCustNo;
}
public String getInArtifNm() {
return inArtifNm;
}
public void setInArtifNm(String inArtifNm) {
this.inArtifNm = inArtifNm;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getTxnRspCd() {
return txnRspCd;
}
public void setTxnRspCd(String txnRspCd) {
this.txnRspCd = txnRspCd;
}
public String getRspCdDesc() {
return rspCdDesc;
}
public void setRspCdDesc(String rspCdDesc) {
this.rspCdDesc = rspCdDesc;
}
}
| [
"humengmeng@rainiee.com"
] | humengmeng@rainiee.com |
e07c87cda467b84ab1d54af5df7869fa31b5195f | 11c738675ac7f20dcef217b85f4043750b57994c | /src/com/com/Less10/abstr/Shape.java | 45c71518866e398e1b627719ea178ab660aebc81 | [] | no_license | beskonechnost/new | d0240cf7db64850b43198ede7a6bf0a4b165821b | b4d9aa030a0d8a24eca33b4d87b4cb2c835623db | refs/heads/master | 2021-01-22T12:07:34.429825 | 2016-01-11T20:09:07 | 2016-01-11T20:09:07 | 42,803,492 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 245 | java | package com.com.Less10.abstr;
/**
* Created by uitsc_000 on 18.10.2015.
*/
public abstract class Shape {
protected String color = "red";
public abstract void draw();
public Shape(String color){
this.color = color;
}
}
| [
"goodlak13@bk.ru"
] | goodlak13@bk.ru |
c221aa67fe12773874dc3ba41761d3c996f60fee | 3b34ec3651055b290f99ebb43a7db0169022c924 | /DS4P/consent2share/pg/consent-gen-pg/src/test/java/gov/samhsa/consent/pg/ConsentBuilderImplTest.java | b2da0b4d03b58054b344154c05bef5aa2a348699 | [
"BSD-3-Clause"
] | permissive | pmaingi/Consent2Share | f9f35e19d124cd40275ef6c43953773f0a3e6f25 | 00344812cd95fdc75a9a711d35f92f1d35f10273 | refs/heads/master | 2021-01-11T01:20:55.231460 | 2016-09-29T16:58:40 | 2016-09-29T16:58:40 | 70,718,518 | 1 | 0 | null | 2016-10-12T16:21:33 | 2016-10-12T16:21:33 | null | UTF-8 | Java | false | false | 14,473 | java | /*******************************************************************************
* Open Behavioral Health Information Technology Architecture (OBHITA.org)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package gov.samhsa.consent.pg;
import static gov.samhsa.consent2share.commonunit.matcher.ArgumentMatchers.matching;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import gov.samhsa.acs.common.param.Params;
import gov.samhsa.acs.common.tool.XmlTransformer;
import gov.samhsa.consent.ConsentBuilderImpl;
import gov.samhsa.consent.ConsentDto;
import gov.samhsa.consent.ConsentDtoFactory;
import gov.samhsa.consent.ConsentGenException;
import gov.samhsa.consent.PatientDto;
import gov.samhsa.consent.XslResource;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
@RunWith(MockitoJUnitRunner.class)
public class ConsentBuilderImplTest {
public static final String C2S_ACCOUNT_ORG = "C2S_ACCOUNT_ORG";
@InjectMocks
ConsentBuilderImpl sut;
@Mock
ConsentDtoFactory consentDtoFactoryMock;
@Mock
XmlTransformer xmlTransformerMock;
@Mock
XacmlXslUrlProviderImpl xacmlXslUrlProviderImplMock;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() {
ReflectionTestUtils.setField(sut, "c2sAccountOrg", C2S_ACCOUNT_ORG);
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2Cdar2() throws ConsentGenException {
// Arrange
final long consentId = 1;
final ConsentDto consentDtoMock = mock(ConsentDto.class);
final String c2cdar2XslUrlMock = "c2cdar2XslUrlMock";
when(consentDtoFactoryMock.createConsentDto(anyLong())).thenReturn(
consentDtoMock);
final String cdar2Mock = "cdar2";
when(xacmlXslUrlProviderImplMock.getUrl(XslResource.CDAR2XSLNAME))
.thenReturn(c2cdar2XslUrlMock);
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2cdar2XslUrlMock), isA(Optional.class),
isA(Optional.class))).thenReturn(cdar2Mock);
// Act
final String cdar2 = sut.buildConsent2Cdar2(consentId);
// Assert
assertEquals(cdar2Mock, cdar2);
verify(xmlTransformerMock).transform(
eq(consentDtoMock),
eq(c2cdar2XslUrlMock),
argThat(matching((Optional<Params> params) -> params
.isPresent() == false)), isA(Optional.class));
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2Cdar2_ConsentGenException()
throws ConsentGenException {
// Arrange
thrown.expect(ConsentGenException.class);
final long consentId = 1;
final String c2cdar2XslUrlMock = "c2cdar2XslUrlMock";
final ConsentDto consentDtoMock = mock(ConsentDto.class);
when(xacmlXslUrlProviderImplMock.getUrl(XslResource.CDAR2XSLNAME))
.thenReturn(c2cdar2XslUrlMock);
when(consentDtoFactoryMock.createConsentDto(anyLong())).thenReturn(
consentDtoMock);
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2cdar2XslUrlMock), isA(Optional.class),
isA(Optional.class))).thenThrow(
new RuntimeException("Error in saxon transform"));
// Act
sut.buildConsent2Cdar2(consentId);
// Assert
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2Xacml() throws ConsentGenException {
// Arrange
final String eidMock = "eidMock";
final String mrnMock = "mrnMock";
final String c2xacmlXslUrlMock = "c2xacmlXslUrlMock";
final Long consentId = new Long(1);
final ConsentDto consentDtoMock = mock(ConsentDto.class);
final PatientDto patientDtoMock = mock(PatientDto.class);
when(xacmlXslUrlProviderImplMock.getUrl(XslResource.XACMLXSLNAME))
.thenReturn(c2xacmlXslUrlMock);
when(consentDtoFactoryMock.createConsentDto(consentId)).thenReturn(
consentDtoMock);
when(consentDtoMock.getPatientDto()).thenReturn(patientDtoMock);
// when(patientDtoMock.getEnterpriseIdentifier()).thenReturn(eidMock);
when(patientDtoMock.getMedicalRecordNumber()).thenReturn(mrnMock);
final String xacmlMock = "xacml";
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2xacmlXslUrlMock), isA(Optional.class),
isA(Optional.class))).thenReturn(xacmlMock);
// Act
final String xacml = sut.buildConsent2Xacml(consentId);
// Assert
assertEquals(xacmlMock, xacml);
verify(xmlTransformerMock).transform(
eq(consentDtoMock),
eq(c2xacmlXslUrlMock),
argThat(matching((Optional<Params> params) -> params
.isPresent() == true
&& params.get().toMap().size() == 1
&& params.get().get(ConsentBuilderImpl.PARAM_MRN)
.equals(mrnMock))), isA(Optional.class));
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2Xacml_ConsentGenException()
throws ConsentGenException {
// Arrange
final String eidMock = "eidMock";
final String mrnMock = "mrnMock";
final String c2xacmlXslUrlMock = "c2xacmlXslUrlMock";
thrown.expect(ConsentGenException.class);
final Long consentId = new Long(1);
final ConsentDto consentDtoMock = mock(ConsentDto.class);
final PatientDto patientDtoMock = mock(PatientDto.class);
when(xacmlXslUrlProviderImplMock.getUrl(XslResource.XACMLXSLNAME))
.thenReturn(c2xacmlXslUrlMock);
when(consentDtoMock.getPatientDto()).thenReturn(patientDtoMock);
// when(patientDtoMock.getEnterpriseIdentifier()).thenReturn(eidMock);
when(patientDtoMock.getMedicalRecordNumber()).thenReturn(mrnMock);
when(consentDtoFactoryMock.createConsentDto(consentId)).thenReturn(
consentDtoMock);
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2xacmlXslUrlMock), isA(Optional.class),
isA(Optional.class))).thenThrow(
new RuntimeException("Error in saxon transform"));
// Act
sut.buildConsent2Xacml(consentId);
// Assert
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2XacmlPdfConsentFrom()
throws ConsentGenException {
// Arrange
final String mrnMock = "mrnMock";
final String eidMock = "eidMock";
final String polId = "C2S.PG-DEV.RmETWp:&2.16.840.1.113883.3.704.100.200.1.1.3.1&ISO:1578821153:1427467752:XM2UoY";
final String polIdNew = "C2S.PG-DEV.RmETWp:&2.16.840.1.113883.3.704.100.200.1.1.3.1&ISO:1427467752:C2S_ACCOUNT_ORG:XM2UoY";
final String c2xacmlpdfConsentFromXslUrlMock = "c2xacmlpdfConsentFromXslUrlMock";
final Long consentId = new Long(1);
final ConsentDto consentDtoMock = mock(ConsentDto.class);
final PatientDto patientDtoMock = mock(PatientDto.class);
when(
xacmlXslUrlProviderImplMock
.getUrl(XslResource.XACMLPDFCONSENTFROMXSLNAME))
.thenReturn(c2xacmlpdfConsentFromXslUrlMock);
when(consentDtoFactoryMock.createConsentDto(consentId)).thenReturn(
consentDtoMock);
when(consentDtoMock.getPatientDto()).thenReturn(patientDtoMock);
when(consentDtoMock.getConsentReferenceid()).thenReturn(polId);
// when(patientDtoMock.getEnterpriseIdentifier()).thenReturn(eidMock);
when(patientDtoMock.getMedicalRecordNumber()).thenReturn(mrnMock);
final String xacmlMock = "xacml";
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2xacmlpdfConsentFromXslUrlMock),
isA(Optional.class), isA(Optional.class))).thenReturn(
xacmlMock);
// Act
final String xacml = sut.buildConsent2XacmlPdfConsentFrom(consentId);
// Assert
assertEquals(xacmlMock, xacml);
verify(xmlTransformerMock).transform(
eq(consentDtoMock),
eq(c2xacmlpdfConsentFromXslUrlMock),
argThat(matching((Optional<Params> params) -> params
.isPresent() == true
&& params.get().toMap().size() == 2
&& params.get().toMap()
.get(ConsentBuilderImpl.PARAM_MRN)
.equals(mrnMock)
&& params.get().toMap()
.get(ConsentBuilderImpl.PARAM_POLICY_ID)
.equals(polIdNew))), isA(Optional.class));
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2XacmlPdfConsentFrom_ConsentGenException()
throws ConsentGenException {
// Arrange
final String eidMock = "eidMock";
final String mrnMock = "mrnMock";
final String c2xacmlpdfConsentFromXslUrlMock = "c2xacmlpdfConsentFromXslUrlMock";
thrown.expect(ConsentGenException.class);
final Long consentId = new Long(1);
final ConsentDto consentDtoMock = mock(ConsentDto.class);
final PatientDto patientDtoMock = mock(PatientDto.class);
when(
xacmlXslUrlProviderImplMock
.getUrl(XslResource.XACMLPDFCONSENTFROMXSLNAME))
.thenReturn(c2xacmlpdfConsentFromXslUrlMock);
when(consentDtoMock.getPatientDto()).thenReturn(patientDtoMock);
// when(patientDtoMock.getEnterpriseIdentifier()).thenReturn(eidMock);
when(patientDtoMock.getMedicalRecordNumber()).thenReturn(mrnMock);
when(consentDtoFactoryMock.createConsentDto(consentId)).thenReturn(
consentDtoMock);
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2xacmlpdfConsentFromXslUrlMock),
isA(Optional.class), isA(Optional.class))).thenThrow(
new RuntimeException("Error in saxon transform"));
// Act
sut.buildConsent2XacmlPdfConsentFrom(consentId);
// Assert
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2XacmlPdfConsentTo() throws ConsentGenException {
// Arrange
final String eidMock = "eidMock";
final String mrnMock = "mrnMock";
final String polId = "C2S.PG-DEV.RmETWp:&2.16.840.1.113883.3.704.100.200.1.1.3.1&ISO:1578821153:1427467752:XM2UoY";
final String polIdNew = "C2S.PG-DEV.RmETWp:&2.16.840.1.113883.3.704.100.200.1.1.3.1&ISO:1578821153:C2S_ACCOUNT_ORG:XM2UoY";
final String c2xacmlpdfConsentToXslUrlMock = "c2xacmlpdfConsentToXslUrlMock";
final Long consentId = new Long(1);
final ConsentDto consentDtoMock = mock(ConsentDto.class);
final PatientDto patientDtoMock = mock(PatientDto.class);
when(
xacmlXslUrlProviderImplMock
.getUrl(XslResource.XACMLPDFCONSENTTOXSLNAME))
.thenReturn(c2xacmlpdfConsentToXslUrlMock);
when(consentDtoFactoryMock.createConsentDto(consentId)).thenReturn(
consentDtoMock);
when(consentDtoMock.getConsentReferenceid()).thenReturn(polId);
when(consentDtoMock.getPatientDto()).thenReturn(patientDtoMock);
// when(patientDtoMock.getEnterpriseIdentifier()).thenReturn(eidMock);
when(patientDtoMock.getMedicalRecordNumber()).thenReturn(mrnMock);
final String xacmlMock = "xacml";
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2xacmlpdfConsentToXslUrlMock), isA(Optional.class),
isA(Optional.class))).thenReturn(xacmlMock);
// Act
final String xacml = sut.buildConsent2XacmlPdfConsentTo(consentId);
// Assert
assertEquals(xacmlMock, xacml);
verify(xmlTransformerMock).transform(
eq(consentDtoMock),
eq(c2xacmlpdfConsentToXslUrlMock),
argThat(matching((Optional<Params> params) -> params
.isPresent() == true
&& params.get().toMap().size() == 2
&& params.get().toMap()
.get(ConsentBuilderImpl.PARAM_MRN)
.equals(mrnMock)
&& params.get().toMap()
.get(ConsentBuilderImpl.PARAM_POLICY_ID)
.equals(polIdNew))), isA(Optional.class));
}
@SuppressWarnings("unchecked")
@Test
public void testBuildConsent2XacmlPdfConsentTo_ConsentGenException()
throws ConsentGenException {
// Arrange
final String eidMock = "eidMock";
final String mrnMock = "mrnMock";
final String polId = "C2S.PG-DEV.RmETWp:&2.16.840.1.113883.3.704.100.200.1.1.3.1&ISO:1578821153:1427467752:XM2UoY";
final String c2xacmlpdfConsentToXslUrlMock = "c2xacmlpdfConsentToXslUrlMock";
thrown.expect(ConsentGenException.class);
final Long consentId = new Long(1);
final ConsentDto consentDtoMock = mock(ConsentDto.class);
final PatientDto patientDtoMock = mock(PatientDto.class);
when(
xacmlXslUrlProviderImplMock
.getUrl(XslResource.XACMLPDFCONSENTTOXSLNAME))
.thenReturn(c2xacmlpdfConsentToXslUrlMock);
when(consentDtoMock.getPatientDto()).thenReturn(patientDtoMock);
when(consentDtoMock.getConsentReferenceid()).thenReturn(polId);
// when(patientDtoMock.getEnterpriseIdentifier()).thenReturn(eidMock);
when(patientDtoMock.getMedicalRecordNumber()).thenReturn(mrnMock);
when(consentDtoFactoryMock.createConsentDto(consentId)).thenReturn(
consentDtoMock);
when(
xmlTransformerMock.transform(eq(consentDtoMock),
eq(c2xacmlpdfConsentToXslUrlMock), isA(Optional.class),
isA(Optional.class))).thenThrow(
new RuntimeException("Error in saxon transform"));
// Act
sut.buildConsent2XacmlPdfConsentTo(consentId);
// Assert
}
}
| [
"Jiahao.Li@JIAHAOLILT.fei.local"
] | Jiahao.Li@JIAHAOLILT.fei.local |
1b7163d81d75aa17449f53d3598912f2c0922ad6 | 2c563f8927ac2a3f8accf09f63d6c7584f8bea4d | /code/maven02_item/src/test/java/com/tedu/maven02_item/AppTest.java | 8c6793fe03f2503b437098c7ff841d863d3bc6b0 | [] | no_license | cui1427137878/Aspringboot | 64aed1607f3060cccf7937469567cafc701564e8 | 6ff35cd0236ef86bbc48b150b2524c3a23de7312 | refs/heads/master | 2023-03-01T10:15:14.831996 | 2021-02-04T02:33:20 | 2021-02-04T02:33:20 | 335,803,861 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 649 | java | package com.tedu.maven02_item;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"1427134878@qq.com"
] | 1427134878@qq.com |
3d4fb13d1dcd4fc24b33e4631a67c357c65d801e | c5c6a8b9405e4886e357f5f01b538d58e4b40991 | /carkyp/src/com/carkyp/domain/Address.java | fe88e9f1530ba5fd8b536156fd1b0d05ade3e71f | [] | no_license | odedmar/Git | c9866216a87303a6ba8731f5e5794559c0b5514c | 89384adf2512c735ccb0fd984a6c88d8ec91b2a8 | refs/heads/master | 2021-01-21T12:52:58.027336 | 2016-06-02T07:17:25 | 2016-06-02T07:17:25 | 22,685,164 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 904 | java | package com.carkyp.domain;
public class Address {
private String street;
private String number;
private String city;
public Address(){}
public Address(String street, String number, String city) {
super();
this.street = street;
this.number = number;
this.city = city;
}
public final String getStreet() {
return street;
}
public final void setStreet(String street) {
this.street = street;
}
public final String getCity() {
return city;
}
public final void setCity(String city) {
this.city = city;
}
public final String getNumber() {
return number;
}
public final void setNumber(String number) {
this.number = number;
}
@Override
public String toString() {
return "Address [street=" + street + ", number=" + number + ", city="
+ city + "]";
}
}
| [
"odedd.markovich@gmail.com"
] | odedd.markovich@gmail.com |
26df7fc843db9558f7584a27459e70dd846024db | 880f6b5b85cb42a126c65c1c5d060a67f5182f7c | /src/insertInterval/Solution2.java | 6cfc7ca4739606872b87f68846ad2f4c3d482337 | [] | no_license | flamearrow/Solutions | 418e7e65eb020fe63b9fb092057704d509127bea | f70440941f94da9d6fb62edf2659692c8b3deba3 | refs/heads/master | 2020-12-24T15:14:32.605376 | 2020-12-16T08:17:41 | 2020-12-16T08:17:41 | 14,934,811 | 9 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,496 | java | package insertInterval;
import java.util.ArrayList;
public class Solution2 {
public ArrayList<Interval> insert2(ArrayList<Interval> intervals,
Interval newInterval) {
ArrayList<Interval> ret = new ArrayList<Interval>();
Interval cur = newInterval;
boolean done = false;
for (Interval itv : intervals) {
if (done) {
ret.add(itv);
} else {
int rst = compareInterval(cur, itv);
// cur is before itv, add cur and next, copy over the remaining intervals
if (rst == -1) {
ret.add(cur);
ret.add(itv);
done = true;
}
// cur overlaps with itv, update cur
else if (rst == 0) {
cur.start = Math.min(cur.start, itv.start);
cur.end = Math.max(cur.end, itv.end);
}
// cur is after itv add itv
else if (rst == 1) {
ret.add(itv);
}
}
}
if (!done) {
ret.add(cur);
}
return ret;
}
int compareInterval(Interval i1, Interval i2) {
if (i1.end < i2.start) {
return -1;
} else if (i1.start > i2.end) {
return 1;
} else
return 0;
}
public ArrayList<Interval> insert(ArrayList<Interval> intervals,
Interval newInterval) {
ArrayList<Interval> ret = new ArrayList<Interval>();
Interval cur = newInterval;
boolean addRest = false;
for (Interval i : intervals) {
if (!addRest) {
int rst = cross(i, cur);
// i is ahead of cur
if (rst == -1) {
ret.add(i);
}
// i crosses cur
else if (rst == 0) {
cur = merge(i, cur);
}
// i is after cur
else if (rst == 1) {
ret.add(cur);
ret.add(i);
addRest = true;
}
} else {
ret.add(i);
}
}
// we haven't add cur yet, cur should be the last entry
if (!addRest) {
ret.add(cur);
}
return ret;
}
// -1: i1 before i2
// 1 : i1 after i2
// 0 : i1 crosses with i2
private int cross(Interval i1, Interval i2) {
if (i1.end < i2.start)
return -1;
if (i2.end < i1.start)
return 1;
return 0;
}
private Interval merge(Interval i1, Interval i2) {
return new Interval(Math.min(i1.start, i2.start), Math.max(i1.end,
i2.end));
}
public static void main(String[] args) {
ArrayList<Interval> intervals = new ArrayList<Interval>();
intervals.add(new Interval(3, 4));
intervals.add(new Interval(6, 7));
intervals.add(new Interval(9, 10));
intervals.add(new Interval(12, 16));
Interval newInterval = new Interval(7, 9);
ArrayList<Interval> merged = new Solution2().insert(intervals,
newInterval);
System.out.println(merged);
}
}
| [
"arrow.cen@gmail.com"
] | arrow.cen@gmail.com |
0dd2e17796a6e2c46b7f04ede34e32fd8794eb45 | 1b8bb33a158836c030ce9cda9de79d9bdd4348b3 | /src/main/java/net/sf/commons/ssh/connection/AbstractConnection.java | b702f6cb3b9f85f9319421d9a2dd5a1456d19fb1 | [] | no_license | Fob/Commons-SSH | 0d540f317cae4ed4ab8cc0576f4f44d6e942889a | 0123adc65c13f688ed29410f37aa4f9af2d6f674 | refs/heads/master | 2020-04-13T22:10:54.019786 | 2018-10-09T15:05:10 | 2018-10-09T15:05:10 | 2,053,216 | 9 | 12 | null | 2018-10-09T15:05:11 | 2011-07-15T13:26:18 | Java | UTF-8 | Java | false | false | 5,456 | java | package net.sf.commons.ssh.connection;
import net.sf.commons.ssh.common.AbstractContainer;
import net.sf.commons.ssh.common.LogUtils;
import net.sf.commons.ssh.common.Status;
import net.sf.commons.ssh.common.UnexpectedRuntimeException;
import net.sf.commons.ssh.errors.Error;
import net.sf.commons.ssh.errors.ErrorLevel;
import net.sf.commons.ssh.event.ProducerType;
import net.sf.commons.ssh.event.events.AuthenticatedEvent;
import net.sf.commons.ssh.options.Properties;
import net.sf.commons.ssh.session.*;
import java.io.IOException;
/**
* @author fob
* @date 24.07.2011
* @since 2.0
*/
public abstract class AbstractConnection extends AbstractContainer<Session> implements Connection {
public AbstractConnection(Properties properties) {
super(properties);
}
@Override
protected void configureDefault(Properties properties) {
super.configureDefault(properties);
}
@Override
public ProducerType getProducerType() {
return ProducerType.CONNECTION;
}
@Override
public ShellSession openShellSession() throws IOException {
ShellSession session = createShellSession();
session.open();
return session;
}
@Override
public SubsystemSession openSubsystemSession() throws IOException {
SubsystemSession session = createSubsystemSession();
session.open();
return session;
}
@Override
public ExecSession openExecSession(String command) throws IOException {
ExecSession session = createExecSession();
ExecSessionPropertiesBuilder.getInstance().setCommand(session, command);
session.open();
return session;
}
@Override
public SFTPSession openSFTPSession() throws IOException {
SFTPSession session = createSFTPSession();
session.open();
return session;
}
@Override
public ScpSession openScpSession() throws IOException {
ScpSession session = createScpSession();
session.open();
return session;
}
@Override
public boolean isConnecting() {
return getContainerStatus() == Status.CONNECTING;
}
@Override
public boolean isAuthenticating() {
return getContainerStatus() == Status.AUTHENTICATING;
}
@Override
public void connect(boolean authenticate) throws ConnectionException, AuthenticationException, HostCheckingException {
synchronized (statusLock) {
if (status == Status.CONNECTING || status == Status.AUTHENTICATING || status == Status.INPROGRESS
|| status == Status.CONNECTED || status == Status.AUTHENTICATED) {
LogUtils.warn(log, "connection {0} already opening", this);
return;
}
try {
ConnectionPropertiesBuilder.getInstance().verify(this);
} catch (Exception e) {
throw new ConnectionException("Verification Connection Properties failed", e);
}
status = Status.CONNECTING;
}
try {
connectImpl(authenticate);
} catch (Exception e) {
setContainerStatus(Status.UNKNOWN);
Error error = new Error("Connection failed", this, ErrorLevel.ERROR, e, "connect(" + authenticate + ")", log);
error.writeLog();
this.pushError(error);
if (e instanceof AuthenticationException)
throw (AuthenticationException) e;
else if (e instanceof ConnectionException)
throw (ConnectionException) e;
else if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new UnexpectedRuntimeException("Connection failed", e);
}
}
protected abstract void connectImpl(boolean authenticate) throws ConnectionException, AuthenticationException, HostCheckingException;
@Override
public void authenticate() throws AuthenticationException {
synchronized (statusLock) {
if (status == Status.AUTHENTICATING || status == Status.AUTHENTICATED || status == Status.INPROGRESS) {
LogUtils.debug(log, "this connection {0} already authenticated", this);
return;
}
if (!isConnected()) {
LogUtils.debug(log, "connection sould be in status CONNECTED before authenticate");
throw new AuthenticationException("connection sould be in status CONNECTED before authenticate");
}
status = Status.AUTHENTICATING;
}
try {
authenticateImpl();
} catch (Exception e) {
synchronized (statusLock) {
if (status == Status.AUTHENTICATING)
status = Status.UNKNOWN;
}
Error error = new Error("Authentication failed", this, ErrorLevel.ERROR, e, "authenticate()", log);
pushError(error);
if (e instanceof AuthenticationException)
throw (AuthenticationException) e;
else if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new AuthenticationException("Authentication Failed", e);
}
}
public void authenticateImpl() throws AuthenticationException {
setContainerStatus(Status.INPROGRESS);
fire(new AuthenticatedEvent(this));
}
}
| [
"egor.ziborov@phystech.edu"
] | egor.ziborov@phystech.edu |
0e5cf7c2eb8f37bbcff8dc3d48c3eafc590337d8 | ae7d0c540e66b23a7368f85ff52ebca5fdaa15a1 | /First_Week/Task10.java | 418b21241f6df2f5126ca334ead963ee24c975ce | [] | no_license | DaydreaMine/java | 4f6d01c45037835fd3ab2d20444f42a86ff2ebd4 | 4029257339d59a65f97a430b8bab8c763e625d5c | refs/heads/master | 2021-01-02T00:45:56.334913 | 2020-05-13T12:29:49 | 2020-05-13T12:29:49 | 239,418,045 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 304 | java | //4.找出能被5或6整除,但不能被两者同时整除的数
class Task10 {
public static void main(String[] args) {
for (int i = 1; i < 1111111; i++) {
if ((i % 5 == 0 || i % 6 == 0) && (i % 30 != 0)) {
System.out.println(i);
}
}
}
} | [
"60591189+DaydreaMine@users.noreply.github.com"
] | 60591189+DaydreaMine@users.noreply.github.com |
981145a20bd971fe6178f28a9a0d663d849e9285 | 84cf958baa3124e50ae7ab50c1962adac99b2faf | /src/main/java/irc/irc__client/ServerListener.java | 524b2d6d358db0257171446d8d62524f703f4592 | [] | no_license | Vadrey/Java-Projekt-IRC_client | 759e9fdf4b14c0be95e9556aec0e8804600bfcc0 | b9ce1f1083a7ee0a78a8379debe95837fcc77c79 | refs/heads/master | 2021-09-10T09:44:36.713686 | 2018-03-23T21:21:31 | 2018-03-23T21:21:31 | 120,498,090 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,904 | java | package irc.irc__client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ServerListener extends Thread implements Runnable {
private BufferedReader bin = null;
private List<IServerMessageListener> messageListeners;
private List<IServerNewUserListener> newUsersListeners;
private Socket socket;
public ServerListener(Socket irc) throws IOException {
socket = irc;
messageListeners = new ArrayList<>();
newUsersListeners = new ArrayList<>();
bin = new BufferedReader(new InputStreamReader(irc.getInputStream()));
}
public void registerMessageListener(IServerMessageListener listener) {
messageListeners.add(listener);
}
@Override
public void run() {
while(true) {
try{
String serverMessage = bin.readLine();
if(serverMessage != null) {
String user = "someUser";
String message = serverMessage;
// Leśmin tu wyggogluj jak przy użyciu regexp wyciagnąć user name i message sie nauczysz czegos pozytecznego :)
for (IServerMessageListener l: messageListeners) {
l.onMessage(user, message);
}
}
} catch(IOException e) {
System.out.println("Cannot read lines from server.");
}
}
}
public Socket getSocket() {
return socket;
}
public void addLoggedUser(String userName) {
for (IServerNewUserListener l: newUsersListeners) {
l.onNewUser(userName);
}
}
public void registerNewUserListener(IServerNewUserListener listener) {
newUsersListeners.add(listener);
}
}
| [
"thorontir@o2.pl"
] | thorontir@o2.pl |
1a7c77bea6dfa833cc610a98231b5a665d84266e | a061ff830d8be17301aeb84da759e494a577a3cb | /app/src/main/java/com/example/foodorderapp/adapters/HomeAdapter.java | 02c3a58bce01e0e34c6e76e163d35e9a5da4ec44 | [] | no_license | vikasmys295/FoodOrder | 9252b103374374c0b2f29dfa6cda4f0a270c27d3 | b9ddb8963da5f6cc870cac5d4420fd7cc0ff6d5c | refs/heads/master | 2023-06-15T05:16:35.758186 | 2021-07-19T06:28:26 | 2021-07-19T06:28:26 | 387,360,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,276 | java | package com.example.foodorderapp.adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.foodorderapp.R;
import com.example.foodorderapp.RestaurantDetailActivity;
import com.example.foodorderapp.model.Restaurant;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
Context context;
List<Restaurant> restaurantList;
public HomeAdapter(Context context, List<Restaurant> restaurantList) {
this.context = context;
this.restaurantList = restaurantList;
}
@NonNull
@Override//inflate the content_list
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_list,parent,false);
return new MyViewHolder(view);
}
@Override//binding the views
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Restaurant restaurant = restaurantList.get(position);
holder.restaurantNames.setText(restaurant.getRestaurant_name());
Picasso.with(context).load(restaurant.getRestaurant_photo()).resize(180,180)
.into(holder.restaurantPhoto);
}
@Override
public int getItemCount() {
return restaurantList.size();
}
//updating the text after filterable
public void updateList(List<Restaurant> newlist){
restaurantList = new ArrayList<>();
restaurantList.addAll(newlist);
notifyDataSetChanged();
}
//inner class for MyviewHolder
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView restaurantNames;
ImageView restaurantPhoto;
public MyViewHolder(@NonNull final View itemView) {
super(itemView);
restaurantNames = (TextView)itemView.findViewById(R.id.restname);
restaurantPhoto = (ImageView)itemView.findViewById(R.id.imageView2);
context = itemView.getContext();
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Restaurant restaurants = restaurantList.get(getLayoutPosition());
Intent intent = new Intent(context, RestaurantDetailActivity.class);
intent.putExtra("rest_name",restaurants.getRestaurant_name());
intent.putExtra("rest_photo",restaurants.getRestaurant_photo());
intent.putExtra("rest_address",restaurants.getRestaurant_address());
intent.putExtra("rest_rating",restaurants.getRestaurant_rating());
intent.putExtra("rest_avg",restaurants.getRestaurant_avg_price());
intent.putExtra("rest_dish",restaurants.getRestaurant_dishes_type());
context.startActivity(intent);
}
});
}
}
}
| [
"vikasmys1995@gmail.com"
] | vikasmys1995@gmail.com |
979407729d5a51c01c0dd653a0b552e91a734ccb | cda14f1577935ffac392ebe41e445e2f7d939c3b | /Employee_Management/src/controller/EditServlet.java | 8d6b182bc994acc4f91c2030c480f69267c33b16 | [] | no_license | phaneendranarla/WebMVCProjects | 700d5086b8eb37064e8847399434d1933b441b7e | 22da083a2d9470eb5c28e3cd01e715d59421d370 | refs/heads/master | 2023-03-26T22:00:44.413641 | 2021-03-28T12:14:44 | 2021-03-28T12:14:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,185 | java | package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.Service;
/**
* Servlet implementation class EditServlet
*/
@WebServlet("/EditServlet")
public class EditServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public EditServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
String save = request.getParameter("save");
Service s = new Service();
if(action!=null)
{
if(action.equalsIgnoreCase("update"))
{
int id = Integer.parseInt(request.getParameter("id"));
request.setAttribute("id", id);
RequestDispatcher rd = request.getRequestDispatcher("edit.jsp");
rd.forward(request, response);
}
}
if(save!=null)
{
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String country = request.getParameter("country");
int i = s.update(id,name,password,email,country);
RequestDispatcher rd = request.getRequestDispatcher("update.jsp");
rd.forward(request, response);
}
}
}
| [
"noreply@github.com"
] | phaneendranarla.noreply@github.com |
69a958c7d9f056e88c712eb7485eed748d535e5b | 8fa22a7bd7098d3ad45ba8fa94f95e11717b366b | /program/service-java/commerce/src/com/meeno/framework/exception/BusinessCheckException.java | bf15785ce485154324e2827483a6054ad1809752 | [] | no_license | haohuiyao/commerce | 5df803d3a3a36d77b42cde9813d559a46b0546dc | 0e5e202ee949fc0b85f66cb745a2ed68195d9080 | refs/heads/master | 2021-01-20T22:55:50.193516 | 2017-08-30T03:11:20 | 2017-08-30T03:11:20 | 101,831,231 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,281 | java | package com.meeno.framework.exception;
public class BusinessCheckException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
private Throwable rootCause;
public BusinessCheckException(String arg0) {
super(arg0);
this.errorKey = arg0;
rootCause = this;
}
public BusinessCheckException() {
super();
}
public BusinessCheckException(String s, Throwable e) {
this(s);
if (e instanceof BusinessCheckException) {
rootCause = ((BusinessCheckException) e).rootCause;
} else {
rootCause = e;
}
}
public BusinessCheckException(Throwable e) {
this("", e);
}
public Throwable getRootCause() {
return rootCause;
}
private String errorKey;
public String getErrorKey() {
return errorKey;
}
private String[] errorParam;
private Object[] errorObjectParam;
public Object[] getErrorObjectParam() {
return errorObjectParam;
}
public void setErrorObjectParam(Object[] errorObjectParam) {
this.errorObjectParam = errorObjectParam;
}
public BusinessCheckException(String key, Object[] objectParam) {
this(key);
this.errorObjectParam = objectParam;
}
public String[] getErrorParam() {
return errorParam;
}
public void setErrorParam(String[] errorParam) {
this.errorParam = errorParam;
}
}
| [
"haohuiyao2020@163.com"
] | haohuiyao2020@163.com |
77a2df606854fd92c571a2465108301b147fbebf | c775ec1df56fd15ad5976631c10480515e35c27b | /Exercise7.java | 9e0e950e81872b577eb48bf5415487bf8de452bd | [] | no_license | vilarj/CS1 | ef8fb512babb084d724ded6762d07678be20529b | d143705addad7f767c0333cbf6152e302be5ad54 | refs/heads/master | 2021-03-02T01:15:01.322246 | 2020-03-08T14:18:21 | 2020-03-08T14:18:21 | 245,826,331 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 835 | java | /*
* Write a method that is passed a String array and returns the longest String
* (the one with the most characters).
* If there are multiple String objects that are tied for the longest,
* return the last such String. Write a main() method to test your method.
*
*/
public class Exercise7 {
public static void main(String[] args) {
String[] vals = {"addadsad", "shjfhdg", "MORE STUFF", "jsdhfjkhfsakgjhfkjgh"};
String correct = longString(vals);
System.out.println("This is the largest string: " + correct);
}
public static String longString(String[] a) {
String longest = "";
int maxLength = -1;
for(int i = 0; i < longest.length(); i++) {
if(a[i].length() >= maxLength) {
maxLength = a[i].length();
longest = a[i];
}
}
return longest;
}
}
| [
"noreply@github.com"
] | vilarj.noreply@github.com |
db7c363a5c13df57b7d877611fc72030f1e3b079 | 4a794d11959c1882dff6670df147e37c1109f330 | /Difficulty 2/hittingtargets.java | e6780d22addd92ca335665bb5407054a32cf2591 | [] | no_license | chxue/kattis_solutions | 0428e186395b0eef44228be36092a61e507fb5ea | 29fb8589e3514bb4d41d12d33cade4d0f7d564fd | refs/heads/master | 2021-01-21T14:08:34.791284 | 2016-06-07T08:26:30 | 2016-06-07T08:26:30 | 55,374,826 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,236 | java | import java.util.*;
class hittingtargets{
//Difficulty: 1.5
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
List<List<Integer>> shapes = new ArrayList<List<Integer>>();
for (int i = 0; i < m; i++){
int read = 3;
if (sc.next().equals("rectangle")){
read = 4;
}
List<Integer> shape = new ArrayList<Integer>();
for (int j = 0; j < read; j++){
shape.add(sc.nextInt());
}
shapes.add(shape);
}
int n = sc.nextInt();
for (int i = 0; i < n; i++){
int x = sc.nextInt(), y = sc.nextInt(), count = 0;
for (int j = 0; j < shapes.size(); j++){
if (hit(shapes.get(j), x, y)){
count++;
}
}
System.out.println(count);
}
}
public static boolean hit(List<Integer> shape, int x, int y){
if (shape.size() == 4){
if (x >= shape.get(0) && y >= shape.get(1) &&
x <= shape.get(2) && y <= shape.get(3)){
return true;
}
return false;
} else {
if (Math.pow(x-shape.get(0),2) + Math.pow(y-shape.get(1),2) <=
Math.pow(shape.get(2),2)){
return true;
}
return false;
}
}
} | [
"chxue@chenxiaos-mbp.wireless.davidson.edu"
] | chxue@chenxiaos-mbp.wireless.davidson.edu |
328c5c63e467c24a4efd499217b0712fca61c350 | 252527b59f58a82e35baa203d4d864e766ff919f | /src/main/java/fpt/edu/bpcrs/contract/Contract.java | 4d5a6e10237841363f20d2754e52041daa0acf5a | [] | no_license | bpcrs/chaincode-java | 83b06c16d258b20f893a80494e6778e3203e40f9 | 8f94895fab94c7588677082e33ca7fde2f8ce1f2 | refs/heads/master | 2022-11-24T06:11:09.841617 | 2020-07-19T11:01:22 | 2020-07-19T11:01:22 | 266,160,541 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | package fpt.edu.bpcrs.contract;
import java.time.LocalDateTime;
public class Contract {
private int accountRenter;
private int accountLessor;
private int carId;
private double price;
private LocalDateTime createdTime;
private int bookingId;
private Agreement agreement;
private StatusEnum status;
private double distance;
}
| [
"hungpt.se@gmail.com"
] | hungpt.se@gmail.com |
55e7303f64dc3ace85e2da45d08776d20fe0f685 | c48568c77d074e513f1145cb3bbe2a854c896eb5 | /Java/UTR labosi/src/proba.java | 84b06be3cb680a35bc2ec8c794f9cddc23c3bd57 | [] | no_license | ArchonAmon/Labosi | 033556ac528779e3cd820637ce0355dfefcd0c3c | f5b96c2e8a861e4fb73bfc25c887e72a7d39b1ce | refs/heads/master | 2023-03-06T20:49:34.280405 | 2021-02-22T14:23:48 | 2021-02-22T14:23:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 387 | java | import java.io.*;
public class proba {
public static void main(String args[]) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
while (s != null) {
int x = Integer.parseInt(s);
System.out.println(x*x);
s = reader.readLine();
}
}
}
| [
"afiraser@gmail.com"
] | afiraser@gmail.com |
607b51598ddda9a4c6b794db1a7c66bb10612cdd | 762b5252c5b79dc6e232ddacf32492ee50ddfb9b | /src/main/java/datamodels/items/Item.java | 51fcfa20975f0421a605b1f0a79678ed60daba1c | [] | no_license | mmmicedcoffee/the-escape | d6a09663fa85c48d967c8c5102b7e39d95344990 | a331653ed92624cae4f849e16886b2f2d448bc68 | refs/heads/master | 2021-01-23T15:09:07.071691 | 2012-11-05T06:32:57 | 2012-11-05T06:32:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 903 | java | package datamodels.items;
import datamodels.Player;
public abstract class Item {
protected final String name;
protected String description;
protected boolean canPickUp;
protected String probeMessage;
public Item(String name,
String description,
boolean canPickUp,
String probeMessage) {
this.name = name;
this.description = description;
this.canPickUp = canPickUp;
this.probeMessage = probeMessage;
}
public String getName() {
return name;
}
public void pickedUp() {
canPickUp = false;
}
public boolean canPickUp() {
return canPickUp;
}
public void probe() {
System.out.println(probeMessage);
}
abstract public void interact(Player player);
@Override
public String toString() {
return description;
}
}
| [
"miss.irene.chen@gmail.com"
] | miss.irene.chen@gmail.com |
41aa2741653ce23dfab1348b03a5914e1c255aa3 | 92d79f9ce37ca996fc3b099a67bc7f06c5d22d11 | /tickets/src/main/java/com/tickets/tickets/repository/ReservationRepository.java | c2a30a3906cb39a0e90db383bcb434aa8ca8fe87 | [] | no_license | shrutikadge/Shruti | 7a76e8513c09aa59fd31cdfcacec306d213496f5 | cfe9d195422627825468d7c7969fa70a815ee6b9 | refs/heads/master | 2021-06-06T19:48:53.820913 | 2018-10-23T06:01:15 | 2018-10-23T06:01:15 | 58,985,337 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 402 | java | package com.tickets.tickets.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.tickets.tickets.entity.Reservation;
@Repository
public interface ReservationRepository extends CrudRepository<Reservation, Long>{
List<Reservation> findByDate(Date date);
}
| [
"shruti.kadge@agfa.com"
] | shruti.kadge@agfa.com |
9691b9423ff1ffa6e7e0b8f70e3c5b89f7b1409c | 74f5958d5679a3ce1b07f505bbe79389220256e6 | /src/main/java/com/pow/study/spel/List.java | ce02871e19edbda07086344e28cd13ced4fe6b5d | [] | no_license | hjkyoyo/spring-expression-study | 498c54af2b56d8a5798f03b7aebe5d6de512d452 | f98c7c3a8a531b84d1fae796f4daa2eb0e7e8fc8 | refs/heads/master | 2020-04-01T00:10:45.945680 | 2018-10-12T02:58:11 | 2018-10-12T02:58:11 | 152,685,510 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,157 | java | package com.pow.study.spel;
import com.pow.study.spel.inventor.Inventor;
import com.pow.study.spel.inventor.Society;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;
import java.util.GregorianCalendar;
import java.util.Map;
/**
* @author power
* @date 2018/10/11 下午2:55
*/
public class List {
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext simpleEvaluationContext = SimpleEvaluationContext.forReadWriteDataBinding().build();
Society ieee = new Society();
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(1856, 7, 9);
Inventor inventor = new Inventor("Alice Miller", calendar.getTime(), "America");
ieee.addMember(inventor);
String name = parser.parseExpression("Members[0].Name").getValue(simpleEvaluationContext, ieee, String.class);
System.out.println(name);
}
}
| [
"huangjikun@jd.com"
] | huangjikun@jd.com |
50079a52a2506ce2d08f742c7e469f762d46be55 | c72224100d92a3e720db829177e63163c8284c8a | /1 - Fundamental Level/Java Fundamentals/Intro-Java-Homework/src/com/company/P05_PrintACharacterTriangle.java | 121d0b5a90030ef492d0bba5eaa3d7cdaf8aeeed | [] | no_license | killer18ys/SoftUni | 1c7bf2cb420c9dc91860a3b91d3591c7b264ab3f | 8225c59b7835302b2122019723b69870689c7757 | refs/heads/master | 2020-04-19T16:34:13.220623 | 2015-12-16T17:21:52 | 2015-12-16T17:21:52 | 35,885,747 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 699 | java | package com.company;
import java.util.Scanner;
/**
* Created by Killer18ys on 13-10-2015.
*/
public class P05_PrintACharacterTriangle {
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int n = Integer.parseInt(console.nextLine());
for (int i = 0; i < n; i++) {
for (char j = 'a'; j < (char)(97 + i); j++) {
System.out.print(j + " ");
}
System.out.println();
}
for (int i = n; i > 0; i--) {
for (char j = 'a'; j < (char)(97 + i); j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
| [
"killer18ys@gmail.com"
] | killer18ys@gmail.com |
61ea443e6b173c6f0afc61cd72b9809b316442a0 | 5e3235edf3de262f4d10b9e9e1fcc3bd13d6b8b1 | /Code Snippet Repository/Roller/Roller506.java | e1a587e06df39743385daa6c890ccc6606f58445 | [] | no_license | saber13812002/DeepCRM | 3336a244d4852a364800af3181e03e868cf6f9f5 | be3e5e50e34a042d5ba7259ff5ff75c08ab32bb9 | refs/heads/master | 2023-03-16T00:08:06.473699 | 2018-04-18T05:29:50 | 2018-04-18T05:29:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,390 | java | private boolean _jspx_meth_s_005fproperty_005f3(javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// s:property
org.apache.struts2.views.jsp.PropertyTag _jspx_th_s_005fproperty_005f3 = (org.apache.struts2.views.jsp.PropertyTag) _005fjspx_005ftagPool_005fs_005fproperty_0026_005fvalue_005fnobody.get(org.apache.struts2.views.jsp.PropertyTag.class);
_jspx_th_s_005fproperty_005f3.setPageContext(_jspx_page_context);
_jspx_th_s_005fproperty_005f3.setParent(null);
// /WEB-INF/jsps/editor/TemplateEdit.jsp(236,20) name = value type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_s_005fproperty_005f3.setValue("bean.link");
int _jspx_eval_s_005fproperty_005f3 = _jspx_th_s_005fproperty_005f3.doStartTag();
if (_jspx_th_s_005fproperty_005f3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fs_005fproperty_0026_005fvalue_005fnobody.reuse(_jspx_th_s_005fproperty_005f3);
return true;
}
_005fjspx_005ftagPool_005fs_005fproperty_0026_005fvalue_005fnobody.reuse(_jspx_th_s_005fproperty_005f3);
return false;
}
| [
"Qing.Mi@my.cityu.edu.hk"
] | Qing.Mi@my.cityu.edu.hk |
4746f1c3ee99165ac279c4765203969078cba3ef | 8a63b0892998da88f779e8a105831b644232540c | /app/src/main/java/com/joshua/myapplication/viewutils/ViewUtils.java | 997cfbc36196b5b806cc4fe4f36317ec38bdfa8d | [] | no_license | Joshua-Lu/MyStudyApp | b57311677135f3f5e0c98236afbbb14bdae8cbf1 | 6ca03dfd1bcbcb72bf53459949ee34a1879535b7 | refs/heads/master | 2023-08-09T19:00:38.909776 | 2023-07-30T16:15:28 | 2023-07-30T16:15:28 | 225,662,424 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,437 | java | package com.joshua.myapplication.viewutils;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 实现ViewUtils注解功能的关键类
* <p>
* 通过反射的方法,解析注解,并实现View的绑定
* <p>
* Created by Joshua on 2021/3/13 17:17
*/
public class ViewUtils {
private static final String TAG = "ViewUtils";
public static void init(Activity activity) {
Log.d(TAG, "init() called with: activity = [" + activity + "]");
bindView(activity);
bindClickListener(activity);
}
/**
* 解析 FindViewById 注解,并找到对应的View,绑定到对应的变量上
*/
private static void bindView(Activity activity) {
Class<? extends Activity> clazz = activity.getClass();
// 找到activity中所有定义的成员变量
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
// 判断该变量上是否有加 FindViewById 注解
FindViewById annotation = field.getAnnotation(FindViewById.class);
if (annotation != null) {
// 有该注解,取得注解上的值
int viewId = annotation.value();
// 在这里执行 findViewById 找到对应的View
View view = activity.findViewById(viewId);
field.setAccessible(true);
try {
// 将找到的View设给对应的变量
field.set(activity, view);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 解析 SetOnClickListener 注解,并找到对应的View,
* 为该View设置OnClickListener,并在onClick方法里调用对应添加了注解的方法
*/
private static void bindClickListener(Activity activity) {
Class<? extends Activity> clazz = activity.getClass();
// 找到activity中所有定义的方法
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
SetOnClickListener annotation = method.getAnnotation(SetOnClickListener.class);
// 判断该方法上是否有加 SetOnClickListener 注解
if (annotation != null) {
// 有该注解,取得注解上的值
int viewId = annotation.value();
// 在这里执行 findViewById 找到对应的View
View view = activity.findViewById(viewId);
method.setAccessible(true);
// 在这里为对应的View执行 setOnClickListener
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
// 调用添加了注解的对应方法
method.invoke(activity, view);
} catch (Exception e) {
try {
method.invoke(activity);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
}
}
}
}
| [
"47053655+Joshua-Lu@users.noreply.github.com"
] | 47053655+Joshua-Lu@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.