repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
zorzella/guiceberry
src/com/google/guiceberry/junit3/AutoTearDownGuiceBerry.java
2628
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.guiceberry.junit3; import com.google.common.testing.TearDown; import com.google.common.testing.TearDownAccepter; import com.google.guiceberry.DefaultEnvSelector; import com.google.guiceberry.GuiceBerryEnvSelector; import com.google.guiceberry.GuiceBerry; import com.google.guiceberry.GuiceBerry.GuiceBerryWrapper; import com.google.inject.Module; import junit.framework.TestCase; /** * {@link GuiceBerry} adapter for JUnit3 {@link TearDownAccepter}s. * * @see ManualTearDownGuiceBerry * * @author Luiz-Otavio "Z" Zorzella */ public class AutoTearDownGuiceBerry { /** * Sets up the test, by creating an injector for the given * {@code guiceBerryEnvClass} and registering a {@link TearDown} against the * given {@code testCase}. * * <p>A canonical test will call this method in the its setUp method, and will * pass {@code this} as the testCase argument. See * {@code junit3_tdtc.tutorial_0_basic.Example0HelloWorldTest#setUp()}. * * <p>The parameter {@code T} is a {@link TearDownAccepter} or anything * equivalent to it. */ public static <T extends TestCase & TearDownAccepter> void setUp( /* TeaDownTestCase */ T testCase, Class<? extends Module> guiceBerryEnvClass) { setUp(testCase, DefaultEnvSelector.of(guiceBerryEnvClass)); } /** * Same as {@link #setUp(TearDownAccepter, Class)}, but with the given * {@code guiceBerryEnvSelector}. * * @see #setUp(TestCase, Class) */ public static <T extends TestCase & TearDownAccepter> void setUp( /* TeaDownTestCase */ T testCase, GuiceBerryEnvSelector guiceBerryEnvSelector) { final GuiceBerryWrapper toTearDown = GuiceBerry.INSTANCE.buildWrapper( ManualTearDownGuiceBerry.buildTestDescription(testCase, testCase.getName()), guiceBerryEnvSelector); testCase.addTearDown(new TearDown() { public void tearDown() throws Exception { toTearDown.runAfterTest(); } }) ; toTearDown.runBeforeTest(); } }
apache-2.0
AnkitAggarwalPEC/plumApp
app/src/main/java/io/github/froger/instamaterial/ui/view/LoadingFeedItemView.java
3315
package io.github.froger.instamaterial.ui.view; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewTreeObserver; import android.widget.FrameLayout; import butterknife.Bind; import butterknife.ButterKnife; import io.github.froger.instamaterial.R; /** * Created by Miroslaw Stanek on 09.12.2015. */ public class LoadingFeedItemView extends FrameLayout { @Bind(R.id.vSendingProgress) SendingProgressView vSendingProgress; @Bind(R.id.vProgressBg) View vProgressBg; private OnLoadingFinishedListener onLoadingFinishedListener; public LoadingFeedItemView(Context context) { super(context); init(); } public LoadingFeedItemView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public LoadingFeedItemView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public LoadingFeedItemView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { LayoutInflater.from(getContext()).inflate(R.layout.item_feed_loader, this, true); ButterKnife.bind(this); } public void startLoading() { vSendingProgress.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { vSendingProgress.getViewTreeObserver().removeOnPreDrawListener(this); vSendingProgress.simulateProgress(); return true; } }); vSendingProgress.setOnLoadingFinishedListener(new SendingProgressView.OnLoadingFinishedListener() { @Override public void onLoadingFinished() { vSendingProgress.animate().scaleY(0).scaleX(0).setDuration(200).setStartDelay(100); vProgressBg.animate().alpha(0.f).setDuration(200).setStartDelay(100) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { vSendingProgress.setScaleX(1); vSendingProgress.setScaleY(1); vProgressBg.setAlpha(1); if (onLoadingFinishedListener != null) { onLoadingFinishedListener.onLoadingFinished(); onLoadingFinishedListener = null; } } }).start(); } }); } public void setOnLoadingFinishedListener(OnLoadingFinishedListener onLoadingFinishedListener) { this.onLoadingFinishedListener = onLoadingFinishedListener; } public interface OnLoadingFinishedListener { void onLoadingFinished(); } }
apache-2.0
Stratio/deep-spark
deep-mongodb/src/main/java/com/stratio/deep/mongodb/reader/MongoReader.java
5826
/* * Copyright 2014, Stratio. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stratio.deep.mongodb.reader; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.apache.spark.Partition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.QueryBuilder; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; import com.stratio.deep.commons.exception.DeepExtractorInitializationException; import com.stratio.deep.commons.impl.DeepPartition; import com.stratio.deep.commons.rdd.IDeepRecordReader; import com.stratio.deep.mongodb.config.MongoDeepJobConfig; import com.stratio.deep.mongodb.partition.MongoPartition; /** * Created by rcrespo on 30/10/14. * * @param <T> the type parameter */ public class MongoReader<T> implements IDeepRecordReader<DBObject> { private static final Logger LOG = LoggerFactory.getLogger(MongoReader.class); /** * The Mongo client. */ private MongoClient mongoClient = null; /** * The Collection. */ private DBCollection collection = null; /** * The Db. */ private DB db = null; /** * The Db cursor. */ private DBCursor dbCursor = null; /** * The Mongo deep job config. */ private MongoDeepJobConfig mongoDeepJobConfig; /** * Instantiates a new Mongo reader. * * @param mongoDeepJobConfig the mongo deep job config */ public MongoReader(MongoDeepJobConfig mongoDeepJobConfig) { this.mongoDeepJobConfig = mongoDeepJobConfig; } /** * Close void. */ public void close() { if (dbCursor != null) { dbCursor.close(); } if (mongoClient != null) { mongoClient.close(); } } /** * Has next. * * @return the boolean */ public boolean hasNext() { return dbCursor.hasNext(); } /** * Next cells. * * @return the cells */ public DBObject next() { return dbCursor.next(); } /** * Init void. * * @param partition the partition */ public void init(Partition partition) { try { List<ServerAddress> addressList = new ArrayList<>(); for (String s : (List<String>) ((DeepPartition) partition).splitWrapper().getReplicas()) { addressList.add(new ServerAddress(s)); } //Credentials List<MongoCredential> mongoCredentials = new ArrayList<>(); if (mongoDeepJobConfig.getUsername() != null && mongoDeepJobConfig.getPassword() != null) { MongoCredential credential = MongoCredential.createMongoCRCredential(mongoDeepJobConfig.getUsername(), mongoDeepJobConfig.getDatabase(), mongoDeepJobConfig.getPassword().toCharArray()); mongoCredentials.add(credential); } mongoClient = new MongoClient(addressList, mongoCredentials); mongoClient.setReadPreference(ReadPreference.valueOf(mongoDeepJobConfig.getReadPreference())); db = mongoClient.getDB(mongoDeepJobConfig.getDatabase()); collection = db.getCollection(mongoDeepJobConfig.getCollection()); dbCursor = collection.find(generateFilterQuery((MongoPartition) partition), mongoDeepJobConfig.getDBFields()); } catch (UnknownHostException e) { throw new DeepExtractorInitializationException(e); } } /** * Create query partition. * * @param partition the partition * @return the dB object */ private DBObject createQueryPartition(MongoPartition partition) { QueryBuilder queryBuilderMin = QueryBuilder.start(partition.getKey()); DBObject bsonObjectMin = queryBuilderMin.greaterThanEquals(partition.splitWrapper().getStartToken()).get(); QueryBuilder queryBuilderMax = QueryBuilder.start(partition.getKey()); DBObject bsonObjectMax = queryBuilderMax.lessThan(partition.splitWrapper().getEndToken()).get(); QueryBuilder queryBuilder = QueryBuilder.start(); if (partition.splitWrapper().getStartToken() != null) { queryBuilder.and(bsonObjectMin); } if (partition.splitWrapper().getEndToken() != null) { queryBuilder.and(bsonObjectMax); } LOG.debug("mongodb query "+queryBuilder.get()); return queryBuilder.get(); } /** * Generate filter query. * * @param partition the partition * @return the dB object */ private DBObject generateFilterQuery(MongoPartition partition) { if (mongoDeepJobConfig.getQuery() != null) { QueryBuilder queryBuilder = QueryBuilder.start(); queryBuilder.and(createQueryPartition(partition), mongoDeepJobConfig.getQuery()); LOG.debug("mongodb query "+queryBuilder.get()); return queryBuilder.get(); } return createQueryPartition(partition); } }
apache-2.0
yunzhijia/isv
src/main/java/util/HttpHelperAsync.java
17355
package util; import java.io.IOException; import java.io.Serializable; import java.net.BindException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.concurrent.FutureCallback; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicNameValuePair; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class HttpHelperAsync { private static Logger logger = LoggerFactory.getLogger(HttpHelperAsync.class); private static final int DEFAULT_ASYNC_TIME_OUT = 10000; private static final int MAX_TOTEL = 100; private static final int MAX_CONNECTION_PER_ROUTE = 100; public static final String UTF8 = "UTF-8"; public static final String APPLICATION_JSON = "application/json"; public static final String APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; private static Get get = new Get(); private static Post post = new Post(); private static PostJSON postJSON = new PostJSON(); private static class HttpHelperAsyncClientHolder { private static HttpHelperAsyncClient instance = new HttpHelperAsyncClient(); } private static class HttpHelperAsyncClient { private CloseableHttpAsyncClient httpClient; private PoolingNHttpClientConnectionManager cm; private HttpHelperAsyncClient() {} private DefaultConnectingIOReactor ioReactor; private static HttpHelperAsyncClient instance; private Logger logger = LoggerFactory.getLogger(HttpHelperAsyncClient.class); public static HttpHelperAsyncClient getInstance() { instance = HttpHelperAsyncClientHolder.instance; try { instance.init(); } catch (Exception e) { } return instance; } private void init() throws Exception { ioReactor = new DefaultConnectingIOReactor(); ioReactor.setExceptionHandler(new IOReactorExceptionHandler() { public boolean handle(IOException ex) { if (ex instanceof BindException) { return true; } return false; } public boolean handle(RuntimeException ex) { if (ex instanceof UnsupportedOperationException) { return true; } return false; } }); cm=new PoolingNHttpClientConnectionManager(ioReactor); cm.setMaxTotal(MAX_TOTEL); cm.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE); httpClient = HttpAsyncClients.custom() .addInterceptorFirst(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } }}).addInterceptorFirst(new HttpResponseInterceptor() { public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity( new GzipDecompressingEntity(response.getEntity())); return; } } } } } }) .setConnectionManager(cm) .build(); httpClient.start(); } private Response execute(HttpUriRequest request, long timeoutmillis) throws Exception { HttpEntity entity = null; Future<HttpResponse> rsp = null; Response respObject=new Response(); //default error code respObject.setCode(400); if (request == null) return respObject; try{ if(httpClient == null){ StringBuilder sbuilder=new StringBuilder(); sbuilder.append("\n{").append(request.getURI().toString()).append("}\nreturn error " + "{HttpHelperAsync.httpClient 获取异常!}"); logger.info(sbuilder.toString()); respObject.setError(sbuilder.toString()); return respObject; } rsp = httpClient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { logger.info("completed successful!"); } public void failed(final Exception ex) { logger.info("excute failed:",ex); } public void cancelled() { logger.info("excute canclled!"); } }); HttpResponse resp = null; if(timeoutmillis > 0){ resp = rsp.get(timeoutmillis,TimeUnit.MILLISECONDS); }else{ resp = rsp.get(DEFAULT_ASYNC_TIME_OUT,TimeUnit.MILLISECONDS); } entity = resp.getEntity(); StatusLine statusLine = resp.getStatusLine(); respObject.setCode(statusLine.getStatusCode()); logger.info("Response:"); logger.info(statusLine.toString()); headerLog(resp); String result = new String(); if (respObject.getCode() == 200) { String encoding = ("" + resp.getFirstHeader("Content-Encoding")).toLowerCase(); if (encoding.indexOf("gzip") > 0) { entity = new GzipDecompressingEntity(entity); } result = new String(EntityUtils.toByteArray(entity),UTF8); respObject.setContent(result); } else { StringBuilder sbuilder=new StringBuilder(); sbuilder.append("\n{").append(request.getURI().toString()).append("}\nreturn error " + "{").append(resp.getStatusLine().getStatusCode()).append("}"); logger.info(sbuilder.toString()); try { result = new String(EntityUtils.toByteArray(entity),UTF8); respObject.setError(result); } catch(Exception e) { logger.error(e.getMessage(), e); result = e.getMessage(); } } TimeCalcUtil.logRunTime(); logger.info(result); } finally { EntityUtils.consumeQuietly(entity); } return respObject; } } public static class Headers extends HashMap<String, Object> { private static final long serialVersionUID = -6699349634305847872L; public Headers() { this.put("Content-Type", APPLICATION_X_WWW_FORM_URLENCODED); } } public static class Response { //返回结果状态码 private int code; //返回内容 private String content; //返回错误 private String error; public Response() { this.code = 400; } public String getError() { return error; } public void setError(String error) { this.error = error; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public JSONObject getJsonContent(){ return JSONObject.parseObject(content); } public JSONArray getJsonArrayContent(){ return JSONArray.parseArray(content); } public JSONObject getJsonError(){ return JSONObject.parseObject(error); } public String toString(){ return JSONObject.toJSON(this).toString(); } } private static abstract class HttpAsyncRequest { // 钩子 public Object setParameter(JSONObject parameters) { logger.info("{} Params: {}", TimeCalcUtil.getReqType(), parameters); return parameters; } // 钩子 public Object setParameter(Map<String, Object> parameters) { List<NameValuePair> params = new ArrayList<NameValuePair>(); if (null == parameters || parameters.isEmpty()) { return params; } Iterator<String> iterator = parameters.keySet().iterator(); StringBuffer paramsBuffer = new StringBuffer(); for (; iterator.hasNext();) { String name = iterator.next(); String value = parameters.get(name).toString(); params.add(new BasicNameValuePair(name, value)); if (iterator.hasNext()) { paramsBuffer.append(name).append("=").append(value).append("&"); } else { paramsBuffer.append(name).append("=").append(value); } } logger.info("{} Params: {}", TimeCalcUtil.getReqType(), paramsBuffer); return params; } // 钩子 @SuppressWarnings("unchecked") public HttpEntity setHttpEntity(Object params) throws Exception { List<NameValuePair> nameValuePairs = (List<NameValuePair>)params; UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, UTF8); return urlEncodedFormEntity; } // 钩子 public HttpUriRequest setHttpUriRequest(String url, HttpEntity httpEntity) throws Exception { HttpPost post = new HttpPost(url); post.setEntity(httpEntity); return post; } private void headers(HttpUriRequest request, Headers headers) { if (null != headers && !headers.isEmpty()) { Set<String> set = headers.keySet(); for (String name : set) { String value = "" + headers.get(name); logger.info("{}: {}", name, value); request.addHeader(name, value); } } } public Response request(String url, Headers headers, Map<String, Object> parameters, long timeoutMillis) throws Exception { try { preOpera(url, timeoutMillis); UrlParam urlParam = parseUrlParam(url, parameters); Object contentTypeObject = (null == headers ? null : headers.get("Content-Type")); String contentType = (null == contentTypeObject ? APPLICATION_X_WWW_FORM_URLENCODED : contentTypeObject.toString()); Response response = null; if (contentType.contains(APPLICATION_JSON)) { response = applicationJSON(url, headers, JSONObject.parseObject(JSONObject.toJSON(parameters).toString()), timeoutMillis); } else { Object params = setParameter(urlParam.parameters); params = params==null?new Object():params; HttpEntity httpEntity = setHttpEntity(params); HttpUriRequest request = setHttpUriRequest(urlParam.url, httpEntity); headers(request, headers); response = HttpHelperAsyncClient.getInstance().execute(request, timeoutMillis); } return response; } catch (AssertionError e) { throw new Exception(e); } } public Response request(String url, Headers headers, JSONObject parameters, long timeoutMillis) throws Exception { try { preOpera(url, timeoutMillis); return applicationJSON(url, headers, parameters, timeoutMillis); } catch (AssertionError e) { throw new Exception(e); } } private void preOpera(String url, long timeoutMillis) { // Assert.assertFalse("url is null or empty!", StringUtils.isEmpty(url)); TimeCalcUtil.setStartTimeUrl(System.currentTimeMillis(), url); if (0 == timeoutMillis) { timeoutMillis = DEFAULT_ASYNC_TIME_OUT; } } private UrlParam parseUrlParam(String url, Map<String, Object> params) { // Assert.assertFalse("url is null or empty!", StringUtils.isEmpty(url)); int wenhao = url.indexOf("?"); boolean hasUrlParam = -1 != wenhao && -1 != url.indexOf("="); if (null == params && hasUrlParam) { params = new HashMap<String, Object>(); } if (hasUrlParam) { String srcUrl = url; url = url.substring(0, wenhao); String keyValues = srcUrl.substring(wenhao + 1); if (StringUtils.isNotEmpty(keyValues)) { String[] keyValueArray = keyValues.split("&"); for (String keyValue : keyValueArray) { if (StringUtils.isNotEmpty(keyValue)) { String[] valuePair = keyValue.split("="); if (2 == valuePair.length) { String name = valuePair[0]; String value = valuePair[1]; if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) { params.put(name, value); } } } } } } return new UrlParam(url, params); } private Response applicationJSON(String url, Headers headers, JSONObject parameters, long timeoutMillis) throws Exception { Object params = setParameter(parameters); params = params==null?new Object():params; HttpEntity httpEntity = setHttpEntity(params); HttpUriRequest request = setHttpUriRequest(url, httpEntity); headers(request, headers); Response response = HttpHelperAsyncClient.getInstance().execute(request, timeoutMillis); return response; } } private static class UrlParam implements Serializable { private static final long serialVersionUID = -5041417788475125724L; private String url; private Map<String, Object> parameters; public UrlParam(String url, Map<String, Object> parameters) { this.url = url; this.parameters = parameters; } } private static class Get extends HttpAsyncRequest { @Override public HttpUriRequest setHttpUriRequest(String url, HttpEntity httpEntity) throws Exception { String param = EntityUtils.toString(httpEntity); url += (url.indexOf('?') != -1 ? "&" : "?") + param; HttpGet get = new HttpGet(url); return get; } } private static class Post extends HttpAsyncRequest { } private static class PostJSON extends HttpAsyncRequest { public HttpEntity setHttpEntity(Object params) throws Exception { JSONObject jsonParams = JSONObject.parseObject(params.toString()); StringEntity stringEntity = new StringEntity(jsonParams.toString(), UTF8); stringEntity.setContentType(APPLICATION_JSON); return stringEntity; } } private final static void headerLog(HttpResponse response) { Header[] headers = response.getAllHeaders(); headerLog(headers); } private final static void headerLog(Header[] headers) { for (Header header : headers) { String key = header.getName(); String value = header.getValue(); if(null != key){ logger.info(key + ": " + value); }else{ logger.info(value); } } } public static Response get(String url, Headers headers, Map<String, Object> parameters, long timeoutMillis) throws Exception { TimeCalcUtil.setReqType("Get"); return get.request(url, headers, parameters, timeoutMillis); } public static Response post(String url, Headers headers, Map<String, Object> parameters, long timeoutMillis) throws Exception { TimeCalcUtil.setReqType("Post"); return post.request(url, headers, parameters, timeoutMillis); } public static Response postJSON(String url, Headers headers, JSONObject parameters, long timeoutMillis) throws Exception { TimeCalcUtil.setReqType("Post"); return postJSON.request(url, headers, parameters, timeoutMillis); } }
apache-2.0
GESCC/danchu
momuck-web/src/main/java/com/danchu/momuck/vo/Account.java
3203
package com.danchu.momuck.vo; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.Date; /** * Account * * @author geine */ public class Account { @JsonProperty("seq_account") private int seqAccount; /** * @TODO 에러 메세지 한글로 변경 필요, 인코딩 세팅 */ @Pattern(regexp = "^[_0-9a-zA-Z-]+@[0-9a-zA-Z]+(.[_0-9a-zA-Z-]+)*$", message = "not email") private String email; private String password; @Size(min = 4, max = 45, message = "name is 4 to 45") private String name; @JsonProperty("profile_image") private String profileImage; @Max(value = 3, message = "not allow type") @Min(value = 1, message = "not allow type") @JsonProperty("account_type") private int accountType; @JsonProperty("is_facebook") private int isFacebook; @JsonProperty("is_kakao") private int isKakao; @JsonProperty("is_verify") private int isVerify; private Date created; public int getSeqAccount() { return seqAccount; } public void setSeqAccount(int seqAccount) { this.seqAccount = seqAccount; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getProfileImage() { return profileImage; } public void setProfileImage(String profileImage) { this.profileImage = profileImage; } public int getAccountType() { return accountType; } public void setAccountType(int accountType) { this.accountType = accountType; } public int isFacebook() { return isFacebook; } public void setFacebook(int facebook) { isFacebook = facebook; } public int isKakao() { return isKakao; } public void setKakao(int kakao) { isKakao = kakao; } public int isVerify() { return isVerify; } public void setVerify(int verify) { isVerify = verify; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } @Override public String toString() { return "Account{" + "seqAccount=" + seqAccount + ", email='" + email + '\'' + ", password='" + password + '\'' + ", name='" + name + '\'' + ", profileImage='" + profileImage + '\'' + ", accountType=" + accountType + ", isFacebook=" + isFacebook + ", isKakao=" + isKakao + ", isVerify=" + isVerify + ", created=" + created + '}'; } }
apache-2.0
jnidzwetzki/bboxdb
bboxdb-server/src/main/java/org/bboxdb/network/client/response/PageEndHandler.java
1891
/******************************************************************************* * * Copyright (C) 2015-2022 the BBoxDB project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.bboxdb.network.client.response; import java.nio.ByteBuffer; import org.bboxdb.network.client.connection.BBoxDBConnection; import org.bboxdb.network.client.future.network.NetworkOperationFuture; import org.bboxdb.network.packets.PacketEncodeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PageEndHandler implements ServerResponseHandler { /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(PageEndHandler.class); /** * Handle the end of a page * @return */ @Override public boolean handleServerResult(final BBoxDBConnection bBoxDBConnection, final ByteBuffer encodedPackage, final NetworkOperationFuture future) throws PacketEncodeException { if(logger.isDebugEnabled()) { logger.debug("Handle page end package from={}", bBoxDBConnection.getConnectionName()); } if(future == null) { logger.warn("Got handleMultiTupleEnd and pendingCall is empty"); return true; } future.setCompleteResult(false); future.fireCompleteEvent(); return true; } }
apache-2.0
fastcat-co/fastcatsearch3
core/src/main/java/org/fastcatsearch/ir/group/GroupEntryList.java
8148
/* * Copyright 2013 Websquared, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fastcatsearch.ir.group; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.fastcatsearch.ir.query.Group; /** * 하나의 그룹핑결과를 담는다. * 결과는 function갯수만큼 GroupEntry내에 여러개의 grouping value들이 추가될수 있다. * */ public class GroupEntryList { private List<GroupEntry> entryList; private int totalCount; //검색결과 갯수이며, 그룹핑 결과갯수는 아닌다. public GroupEntryList(){ } public GroupEntryList(List<GroupEntry> e, int totalCount){ this.entryList = e; this.totalCount = totalCount; } public GroupEntry getEntry(int i){ return entryList.get(i); } public List<GroupEntry> getEntryList(){ return entryList; } public int size(){ if(entryList == null){ return 0; } return entryList.size(); } public int totalCount(){ return totalCount; } public void setTotalCount(int totalCount){ this.totalCount = totalCount; } public void add(GroupEntry groupEntry) { if(entryList == null){ entryList = new ArrayList<GroupEntry>(); } entryList.add(groupEntry); } /** * 키값이 NULL일 경우, 항상 마지막에 출현하도록. * */ public static Comparator<GroupEntry> KeyAscendingComparator = new Comparator<GroupEntry>(){ @Override public int compare(GroupEntry o1, GroupEntry o2) { if(o1.key == null || o2.key == null) { return 0; } else if(o1.key == null) { return 1; } else if(o2.key == null) { return -1; } return o1.key.compareTo(o2.key); } }; public static Comparator<GroupEntry> KeyDescendingComparator = new Comparator<GroupEntry>(){ @Override public int compare(GroupEntry o1, GroupEntry o2) { if(o1.key == null || o2.key == null) { return 0; } else if(o1.key == null) { return 1; } else if(o2.key == null) { return -1; } return o2.key.compareTo(o1.key); } }; /** * Value값이 NULL일 경우, 0일수도 있으므로, 정렬순서에 맞게처리. * */ public static Comparator<GroupEntry> ValueAscendingComparator = new Comparator<GroupEntry>(){ @Override public int compare(GroupEntry o1, GroupEntry o2) { if(o1.groupingValue[0] == null && o2.groupingValue[0] == null) { return 0; } else if(o1.groupingValue[0] == null) { return -1; } else if(o2.groupingValue[0] == null) { return 1; } return o1.groupingValue[0].compareTo(o2.groupingValue[0]); } }; public static Comparator<GroupEntry> ValueDescendingComparator = new Comparator<GroupEntry>(){ @Override public int compare(GroupEntry o1, GroupEntry o2) { if(o1.groupingValue[0] == null && o2.groupingValue[0] == null) { return 0; } else if(o1.groupingValue[0] == null) { return 1; } else if(o2.groupingValue[0] == null) { return -1; } return o2.groupingValue[0].compareTo(o1.groupingValue[0]); } }; /** * 기존 정렬 방식에서 Key를 String이 아니라 숫자 기준으로 정렬 * */ public static Comparator<GroupEntry> KeyNumericAscendingComparator = new Comparator<GroupEntry>(){ @Override public int compare(GroupEntry o1, GroupEntry o2) { if(o1.key == null || o2.key == null) { return 0; } else if(o1.key == null) { return 1; } else if(o2.key == null) { return -1; } if (isStringDouble(o1.key) && isStringDouble(o2.key)) { double o1num = Double.parseDouble(o1.key); double o2num = Double.parseDouble(o2.key); return Double.compare(o1num, o2num); } else if (isStringInteger(o1.key) && isStringInteger(o2.key)) { int o1num = Integer.parseInt(o1.key); int o2num = Integer.parseInt(o2.key); return Integer.compare(o1num, o2num); } else if (isStringFloat(o1.key) && isStringFloat(o2.key)) { Float o1num = Float.parseFloat(o1.key); Float o2num = Float.parseFloat(o2.key); return Float.compare(o1num, o2num); } else if (isStringLong(o1.key) && isStringLong(o2.key)) { Long o1num = Long.parseLong(o1.key); Long o2num = Long.parseLong(o2.key); return Long.compare(o1num, o2num); } else { // 정수값이 아닐 경우 KEY_DESC와 동일하게 정렬 return o1.key.compareTo(o2.key); } } }; public static Comparator<GroupEntry> KeyNumericDescendingComparator = new Comparator<GroupEntry>(){ @Override public int compare(GroupEntry o1, GroupEntry o2) { if(o1.key == null || o2.key == null) { return 0; } else if(o1.key == null) { return 1; } else if(o2.key == null) { return -1; } if (isStringDouble(o1.key) && isStringDouble(o2.key)) { double o1num = Double.parseDouble(o1.key); double o2num = Double.parseDouble(o2.key); return Double.compare(o2num, o1num); } else if (isStringInteger(o1.key) && isStringInteger(o2.key)) { int o1num = Integer.parseInt(o1.key); int o2num = Integer.parseInt(o2.key); return Integer.compare(o2num, o1num); } else if (isStringFloat(o1.key) && isStringFloat(o2.key)) { Float o1num = Float.parseFloat(o1.key); Float o2num = Float.parseFloat(o2.key); return Float.compare(o2num, o1num); } else if (isStringLong(o1.key) && isStringLong(o2.key)) { Long o1num = Long.parseLong(o1.key); Long o2num = Long.parseLong(o2.key); return Float.compare(o2num, o1num); } else { // 정수값이 아닐 경우 KEY_DESC와 동일하게 정렬 return o2.key.compareTo(o1.key); } } }; public void sort(int sortOrder) { if(entryList == null){ return; } if(sortOrder == Group.SORT_KEY_ASC){ Collections.sort(entryList, GroupEntryList.KeyAscendingComparator); }else if(sortOrder == Group.SORT_KEY_DESC){ Collections.sort(entryList, GroupEntryList.KeyDescendingComparator); }else if(sortOrder == Group.SORT_VALUE_ASC){ Collections.sort(entryList, GroupEntryList.ValueAscendingComparator); }else if(sortOrder == Group.SORT_VALUE_DESC) { Collections.sort(entryList, GroupEntryList.ValueDescendingComparator); }else if(sortOrder == Group.SORT_KEY_NUMERIC_ASC){ Collections.sort(entryList, GroupEntryList.KeyNumericAscendingComparator); }else if(sortOrder == Group.SORT_KEY_NUMERIC_DESC){ Collections.sort(entryList, GroupEntryList.KeyNumericDescendingComparator); } } /* * String이 Integer 형식으로 변환이 가능한지 체크한다. * */ public static boolean isStringInteger(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; } } /* * String이 Double 형식으로 변환이 가능한지 체크한다. * */ public static boolean isStringDouble(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } } /* * String이 Float 형식으로 변환이 가능한지 체크한다. * */ public static boolean isStringFloat(String str) { try { Float.parseFloat(str); return true; } catch (NumberFormatException e) { return false; } } /* * String이 Long 형식으로 변환이 가능한지 체크한다. * */ public static boolean isStringLong(String str) { try { Long.parseLong(str); return true; } catch (NumberFormatException e) { return false; } } }
apache-2.0
ouzman/frisbee
app/src/main/java/org/gdg/frisbee/android/common/PeopleAdapter.java
3175
package org.gdg.frisbee.android.common; import android.content.Context; import android.support.annotation.DrawableRes; import android.text.TextUtils; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ArrayAdapter; import android.widget.TextView; import com.squareup.picasso.RequestCreator; import org.gdg.frisbee.android.R; import org.gdg.frisbee.android.api.model.GdgPerson; import org.gdg.frisbee.android.app.App; import org.gdg.frisbee.android.utils.Utils; import org.gdg.frisbee.android.widget.SquaredImageView; import butterknife.Bind; import butterknife.ButterKnife; public class PeopleAdapter extends ArrayAdapter<GdgPerson> { @DrawableRes private int placeholder; private SparseBooleanArray mConsumedMap; public PeopleAdapter(Context ctx) { this(ctx, 0); } public PeopleAdapter(Context ctx, @DrawableRes int placeholder) { super(ctx, R.layout.list_person_item); this.placeholder = placeholder; mConsumedMap = new SparseBooleanArray(); } public void setPlaceholder(@DrawableRes int placeholder) { this.placeholder = placeholder; } @Override public boolean hasStableIds() { return true; } @Override public long getItemId(int i) { return Utils.stringToLong(getItem(i).getUrl()); } @Override public View getView(int i, View convertView, ViewGroup parent) { final GdgPerson gdgPerson = getItem(i); View rowView = convertView; if (rowView == null) { rowView = LayoutInflater.from(getContext()).inflate(R.layout.list_person_item, parent, false); ViewHolder viewHolder = new ViewHolder(rowView); rowView.setTag(viewHolder); } final ViewHolder holder = (ViewHolder) rowView.getTag(); holder.primaryTextView.setText(gdgPerson.getPrimaryText()); holder.secondaryTextView.setText(gdgPerson.getSecondaryText()); if (!TextUtils.isEmpty(gdgPerson.getImageUrl())) { RequestCreator creator = App.getInstance().getPicasso() .load(gdgPerson.getImageUrl()); if (placeholder != 0) { creator.placeholder(placeholder); } creator.into(holder.thumbnailView); } if (!mConsumedMap.get(i)) { mConsumedMap.put(i, true); // In which case we magically instantiate our effect and launch it directly on the view Animation animation = AnimationUtils.makeInChildBottomAnimation(getContext()); rowView.startAnimation(animation); } return rowView; } static class ViewHolder { @Bind(android.R.id.text1) public TextView primaryTextView; @Bind(android.R.id.text2) public TextView secondaryTextView; @Bind(android.R.id.icon) public SquaredImageView thumbnailView; public ViewHolder(View v) { ButterKnife.bind(this, v); } } }
apache-2.0
mlopz/ETK4J
src/com/wildbitsfoundry/etk4j/control/TransferFunction.java
12993
package com.wildbitsfoundry.etk4j.control; import java.util.Arrays; import com.wildbitsfoundry.etk4j.math.MathETK; import com.wildbitsfoundry.etk4j.math.complex.Complex; import com.wildbitsfoundry.etk4j.math.polynomials.Polynomial; import com.wildbitsfoundry.etk4j.math.polynomials.RationalFunction; import com.wildbitsfoundry.etk4j.util.ComplexArrays; public class TransferFunction { private RationalFunction _rf; /*** * Constructs a transfer function from poles and zeros * @param zeros - zeros of the transfer function * @param poles - poles of the transfer function */ public TransferFunction(Complex[] zeros, Complex[] poles) { _rf = new RationalFunction(zeros, poles); } public TransferFunction(double gain, Complex[] poles) { Polynomial num = new Polynomial(gain); Polynomial den = new Polynomial(poles); _rf = new RationalFunction(num, den); } public TransferFunction(TransferFunction tf) { _rf = new RationalFunction(tf._rf); } public TransferFunction(Polynomial numerator, Polynomial denominator) { _rf = new RationalFunction(numerator, denominator); } public TransferFunction(double[] numerator, double[] denominator) { _rf = new RationalFunction(numerator, denominator); } public TransferFunction(RationalFunction rf) { _rf = rf; } public Complex[] getZeros() { return _rf.getZeros(); } public Complex[] getPoles() { return _rf.getPoles(); } public Polynomial getNumerator() { return _rf.getNumerator(); } public Polynomial getDenominator() { return _rf.getDenominator(); } public Complex evaluateAt(double f) { return _rf.evaluateAt(0.0, f); } public static void unwrapPhase(double[] phase) { int length = phase.length; double[] dp = new double[length]; double[] dps = new double[length]; double[] dpcorr = new double[length]; double[] cumulativesum = new double[length]; double cutoff = 180.0; int j; // incremental phase variation for (j = 0; j < length - 1; j++) { dp[j] = phase[j + 1] - phase[j]; } // equivalent phase variation in [-pi, pi] for (j = 0; j < length - 1; j++) { dps[j] = (dp[j] + 180.0) - Math.floor((dp[j] + 180.0) / (2 * 180.0)) * (2 * 180.0) - 180.0; } // preserve variation sign for +pi vs. -pi for (j = 0; j < length - 1; j++) { if ((dps[j] == -180.0) && (dp[j] > 0)) { dps[j] = 180.0; } } // incremental phase correction for (j = 0; j < length - 1; j++) { dpcorr[j] = dps[j] - dp[j]; } // Ignore correction when incremental variation is smaller than cutoff for (j = 0; j < length - 1; j++) { if (Math.abs(dp[j]) < cutoff) { dpcorr[j] = 0; } } // Find cumulative sum of deltas cumulativesum[0] = dpcorr[0]; for (j = 1; j < length - 1; j++) { cumulativesum[j] = cumulativesum[j - 1] + dpcorr[j]; } // Integrate corrections and add to P to produce smoothed phase values for (j = 1; j < length; j++) { phase[j] += cumulativesum[j - 1]; } } public TransferFunction add(final TransferFunction tf) { return new TransferFunction(_rf.add(tf._rf)); } public TransferFunction add(double d) { return new TransferFunction(_rf.add(d)); } public TransferFunction subtract(TransferFunction tf) { return new TransferFunction(_rf.subtract(tf._rf)); } public TransferFunction multiply(TransferFunction tf) { return new TransferFunction(_rf.multiply(tf._rf)); } public TransferFunction multiply(double d) { return new TransferFunction(_rf.multiply(d)); } @Override public String toString() { String num = _rf.getNumerator().toString(); String den = _rf.getDenominator().toString(); int numLength = num.length(); int denLength = den.length(); int divLength = Math.max(numLength, denLength) + 2; String divider = String.format("%0" + divLength + "d", 0).replace('0', '-'); int padLength = (int) Math.floor((divLength - Math.min(numLength, denLength)) * 0.5); String padding = String.format("%0" + padLength + "d", 0).replace('0', ' '); String[] format = null; if (numLength > denLength) { format = new String[] { " ", padding }; } else if (numLength < denLength) { format = new String[] { padding, " " }; } else { format = new String[] { " ", " " }; } String nl = System.getProperty("line.separator"); String result = format[0] + num + nl + divider + nl + format[1] + den; return result.replace('x', 's'); } private static Polynomial getPolynomialMagnitude(Polynomial polynomial) { double[] num = polynomial.getCoefficients(); Complex[] numjw = evalAtjw(num); return new Polynomial(norm(numjw)); } /*** * Calculates the squared magnitude element wise * @param a * @return [norm0, norm1, .... normn] */ private static double[] norm(Complex[] a) { Complex[] mag = ComplexArrays.conv(a, ComplexArrays.conj(a)); double[] coefs = new double[mag.length]; for (int i = 0; i < mag.length; ++i) { coefs[i] = mag[i].real(); } return coefs; } private static Complex[] evalAtjw(double[] poly) { final int length = poly.length; Complex[] result = new Complex[length]; for(int i = length - 1, j = 0; i >= 0; --i, ++j) { poly[i] *= getComplexSign(j); if(j % 2 == 0) { result[i] = new Complex(poly[i], 0.0); } else { result[i] = new Complex(0.0,poly[i]); } } return result; } private static int getComplexSign(int power) { int result = power - 4 * (power / 4); return result == 2 || result == 3 ? - 1 : 1; } // |Num(s)| // H(s) = -------- = 1 // |Den(s)| // // |Num(s)| - |Den(s)| = 0 // // Find roots of the resultant polynomial public double[] getAllGainCrossoverFrequencies() { Polynomial magPolyNum = getPolynomialMagnitude(_rf.getNumerator()); Polynomial magPolyDen = getPolynomialMagnitude(_rf.getDenominator()); Complex[] solution = magPolyDen.subtract(magPolyNum).getRoots(); double[] wgc = new double[solution.length]; int j = 0; for (int i = 0; i < solution.length; i++) { double real = solution[i].real(); if (solution[i].imag() == 0 && real > 0) { wgc[j] = real; j++; } } wgc = Arrays.copyOfRange(wgc, 0, j); Arrays.sort(wgc); return wgc; } public double getGainCrossoverFrequency() { double[] freqs = this.getAllGainCrossoverFrequencies(); // Get the first one were the magnitude was decreasing for(double f : freqs) { double slope = this.getMagnitudeAt(f) - this.getMagnitudeAt(f + 1e-12); if(slope > 0.0) { return f; } } return Double.POSITIVE_INFINITY; } /*** * Finds all the phase cross over frequencies by solving H(s) = H(-s) * * <pre> * This is equivalent to: * * Num(jw) * Den'(jw) - Num'(jw) * Den'(jw) * H(jw) = ---------------------------------------- * Den(jw) * Den'(jw) * * Where H'(jw) = Conjugate of H(jw). * * After multiplying the denominator with its conjugate, it becomes a real * number and it won't affect the phase, therefore it doesn't have to be taken * into account from this point on. We can also drop Num'(jw) * Den'(jw) since * it's there to zero out the real part of Num(jw) * Den'(jw) - Num'(jw) * Den'(jw), * which can be also accomplished by setting the real part of Num(jw) * Den'(jw) * to zero. * * Let Nump(jw) = Num(jw) * Den'(jw) thus * Nump(jw) = Real(Nump(jw)) + j * Imag(Nump(jw)) * * We can equate the imaginary part of Num'(jw) to 0 and solve for w * * The roots of Imag(Nump(jw)) are the solution vector containing the gain * crossover frequencies. * </pre> * @return Returns an array of values that are the phase crossover * frequencies */ public double[] getAllPhaseCrossoverFrequencies() { Complex[] num = evalAtjw(_rf.getNumerator().getCoefficients()); Complex[] conjDen = ComplexArrays.conj(evalAtjw(_rf.getDenominator().getCoefficients())); Complex[] conv = ComplexArrays.conv(num, conjDen); double[] imag = new double[conv.length]; for(int i = 0; i < conv.length; ++i) { imag[i] = conv[i].imag(); } Complex[] solution = new Polynomial(imag).getRoots(); double[] wpc = new double[solution.length]; int j = 0; for (int i = 0; i < solution.length; i++) { double real = solution[i].real(); if (solution[i].imag() == 0 && real > 0) { wpc[j] = real; j++; } } wpc = Arrays.copyOfRange(wpc, 0, j); Arrays.sort(wpc); return wpc; } public double getMagnitudeAt(double f) { return this.evaluateAt(f).abs(); } public double getPhaseCrossoverFrequency() { double[] freqs = this.getAllPhaseCrossoverFrequencies(); // Get the first one were the magnitude was decreasing for(double f : freqs) { double slope = this.getMagnitudeAt(f) - this.getMagnitudeAt(f + 1e-12); if(slope > 0.0) { return f; } } return Double.POSITIVE_INFINITY; } public Margins getMargins() { double wcg = this.getGainCrossoverFrequency(); double wcp = this.getPhaseCrossoverFrequency(); double pm = wcg; if(wcg != Double.POSITIVE_INFINITY) { double phase = this.getPhaseAt(wcg); pm = 180.0 + phase; } double gm = wcp; if(wcp != Double.POSITIVE_INFINITY) { double mag = this.getMagnitudeAt(wcp); gm = 20 * Math.log10(1.0 / mag); } Margins m = new Margins(); m.GainCrossOverFrequency = wcg; m.PhaseCrossOverFrequency = wcp; m.GainMargin = gm; m.PhaseMargin = pm; return m; } public void substituteInPlace(double d) { _rf.substituteInPlace(d); } /*** * Calculates the phase at of the system a given frequency. </br> * This operation uses the zeros and poles of the system to calculate the phase as: </br> * <pre> * &Sigma; Phase(Zeros) - &Sigma; Phase(Poles) * </pre> * If you need to calculate the magnitude and phase or just the phase for an array of frequencies,</br> * it might be more efficient to use {@link #evaluateAt(double)}, and then <strong>unwrap</strong> the * phase information</br> using {@link #unwrapPhase(double[])}. * @param f * @return the phase of the system in degrees */ public double getPhaseAt(double f) { Complex[] zeros = this.getZeros(); Complex[] poles = this.getPoles(); double phase = calculatePhase(zeros, f); phase -= calculatePhase(poles, f); return Math.toDegrees(phase); } /*** * * @param roots * @param f * @return */ private static double calculatePhase(Complex[] roots, double f) { double phase = 0.0; for(int i = 0; i < roots.length; ++i) { if(roots[i].imag() == 0) { // Single real root double alpha = -roots[i].real(); phase += Math.atan2(f, alpha); } else { // Complex pair of roots double alpha = -roots[i].real(); double beta = roots[i].imag(); double fn = MathETK.hypot(alpha, beta); double zeta = alpha / fn; double ratio = f / fn; phase += Math.atan2(2.0 * zeta * ratio, 1 - ratio * ratio); // Roots are in pairs. Skip the conjugate since it was // already taken into account in the calculation above ++i; } } return phase; } public static void main(String[] args) { TransferFunction tf1 = new TransferFunction(new double[] { 1000, 0 }, new double[] { 1, 25, 100, 9, 4}); System.out.println(tf1); System.out.println(tf1.getMargins()); double phase = tf1.getPhaseAt(70.4); System.out.println(phase); // double[] phase = tf1.getPhaseAt(logspace); // System.out.println(Arrays.toString(phase)); // for(int i = 0; i < phase.length; ++i) { // System.out.printf("%.4f %.4f%n", logspace[i], phase[i]); // } // // System.out.println(); // for (double val : tf1.getAllPhaseCrossoverFrequencies()) { // System.out.print(val + " "); // } // System.out.println(); // TransferFunction tf2 = new TransferFunction(new double[] { 12, 6 }, new double[] { 1, 5, 10 }); // for (double val : tf2.getAllGainCrossoverFrequencies()) { // System.out.print(val + " "); // } // System.out.println(); // for (double val : tf2.getAllPhaseCrossoverFrequencies()) { // System.out.print(val + " "); // } // System.out.println(); // System.out.println(tf1.getMargins()); // TransferFunction tf = new TransferFunction(zeros.toArray(new Complex[zeros.size()]), // poles.toArray(new Complex[poles.size()])); // // double x = tf.getMagnitudeAt(1.0); // double y = tf.getPhaseAt(1.0); // System.out.println(x); // System.out.println(y); // // System.out.println(tf1.toString()); // // double[] freq = ArrayUtils.logspace(-3, 3, 100); // // freq = ArrayUtils.logspace(-3, 3, 10000000); } public void normalize() { this._rf.normalize(); } }
apache-2.0
wangmingle/iyoutianxia
src/test/example/StringLineEncoder.java
471
package test.example; import java.nio.ByteBuffer; import com.firefly.net.Encoder; import com.firefly.net.Session; public class StringLineEncoder implements Encoder { private static final String LINE_LIMITOR = System.getProperty("line.separator"); @Override public void encode(Object message, Session session) throws Throwable { String str = message + LINE_LIMITOR; ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes()); session.write(byteBuffer); } }
apache-2.0
jivesoftware/filer
chunk-store/src/main/java/com/jivesoftware/os/filer/chunk/store/transaction/FPIndex.java
3068
/* * Copyright 2015 Jive Software. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jivesoftware.os.filer.chunk.store.transaction; import com.jivesoftware.os.filer.io.CreateFiler; import com.jivesoftware.os.filer.io.Filer; import com.jivesoftware.os.filer.io.GrowFiler; import com.jivesoftware.os.filer.io.OpenFiler; import com.jivesoftware.os.filer.io.api.ChunkTransaction; import com.jivesoftware.os.filer.io.api.KeyRange; import com.jivesoftware.os.filer.io.api.StackBuffer; import com.jivesoftware.os.filer.io.chunk.ChunkFiler; import com.jivesoftware.os.filer.io.chunk.ChunkStore; import java.io.IOException; import java.util.List; /** * * @author jonathan.colt * @param <K> * @param <I> */ public interface FPIndex<K, I extends FPIndex<K, I>> { long get(K key, StackBuffer stackBuffer) throws IOException, InterruptedException; void set(K key, long fp, StackBuffer stackBuffer) throws IOException, InterruptedException; long getAndSet(K key, long fp, StackBuffer stackBuffer) throws IOException, InterruptedException; boolean acquire(int alwaysRoomForNMoreKeys); int nextGrowSize(int alwaysRoomForNMoreKeys) throws IOException, InterruptedException; void copyTo(Filer curentFiler, FPIndex<K, I> newMonkey, Filer newFiler, StackBuffer stackBuffer) throws IOException, InterruptedException; void release(int alwayRoomForNMoreKeys); boolean stream(List<KeyRange> ranges, KeysStream<K> stream, StackBuffer stackBuffer) throws IOException, InterruptedException; long size(StackBuffer stackBuffer) throws IOException, InterruptedException; <H, M, R> R read( ChunkStore chunkStore, K key, OpenFiler<M, ChunkFiler> opener, ChunkTransaction<M, R> filerTransaction, StackBuffer stackBuffer) throws IOException, InterruptedException; <H, M, R> R writeNewReplace( ChunkStore chunkStore, K key, H hint, CreateFiler<H, M, ChunkFiler> creator, OpenFiler<M, ChunkFiler> opener, GrowFiler<H, M, ChunkFiler> growFiler, ChunkTransaction<M, R> filerTransaction, StackBuffer stackBuffer) throws IOException, InterruptedException; <H, M, R> R readWriteAutoGrow( ChunkStore chunkStore, K key, H hint, CreateFiler<H, M, ChunkFiler> creator, OpenFiler<M, ChunkFiler> opener, GrowFiler<H, M, ChunkFiler> growFiler, ChunkTransaction<M, R> filerTransaction, StackBuffer stackBuffer) throws IOException, InterruptedException; }
apache-2.0
cocoatomo/asakusafw
core-project/asakusa-runtime/src/main/java/com/asakusafw/runtime/directio/hadoop/BlockMap.java
7806
/** * Copyright 2011-2017 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.runtime.directio.hadoop; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import com.asakusafw.runtime.directio.DirectInputFragment; /** * Utilities for file blocks. * @see BlockInfo * @since 0.7.0 */ public final class BlockMap { static final double MIN_LOCALITY = 0.125; static final double PRUNE_REL_LOCALITY = 0.75; private final String path; private final BlockInfo[] blocks; private final long size; private BlockMap(String path, BlockInfo[] blocks) { assert path != null; assert blocks != null; assert blocks.length >= 1; this.path = path; this.blocks = blocks; this.size = blocks[blocks.length - 1].end - blocks[0].start; } /** * Returns the file size. * @return the size */ public long getFileSize() { return size; } /** * Returns the file blocks in this map. * @return the file blocks */ public List<BlockInfo> getBlocks() { return Arrays.asList(blocks); } /** * Returns a list of {@link BlockInfo} for the target file. * @param fs the target file * @param status the target file status * @return the computed information * @throws IOException if failed to compute information */ public static List<BlockInfo> computeBlocks(FileSystem fs, FileStatus status) throws IOException { BlockLocation[] locations = fs.getFileBlockLocations(status, 0, status.getLen()); List<BlockInfo> results = new ArrayList<>(); for (BlockLocation location : locations) { long length = location.getLength(); long start = location.getOffset(); results.add(new BlockInfo(start, start + length, location.getHosts())); } return results; } /** * Create {@link BlockMap}. * @param path the target file path * @param fileSize the target file size * @param blockList the original block list * @param combineBlocks {@code true} to combine consecutive blocks with same owners * @return the built object */ public static BlockMap create( String path, long fileSize, Collection<BlockInfo> blockList, boolean combineBlocks) { assert path != null; assert blockList != null; BlockInfo[] blocks = blockList.toArray(new BlockInfo[blockList.size()]); Arrays.sort(blocks, (o1, o2) -> { int startDiff = Long.compare(o1.start, o2.start); if (startDiff != 0) { return startDiff; } return Integer.compare(o2.hosts.length, o1.hosts.length); }); long lastOffset = 0; List<BlockInfo> results = new ArrayList<>(); for (BlockInfo block : blocks) { // if block is out of bounds, skip it if (block.start >= fileSize) { continue; } // if block is gapped, add a padding block if (lastOffset < block.start) { results.add(new BlockInfo(lastOffset, block.start, null)); } long start = Math.max(lastOffset, block.start); long end = Math.min(fileSize, block.end); // if block is empty, skip it if (start >= end) { continue; } results.add(new BlockInfo(start, end, block.hosts)); lastOffset = end; } assert lastOffset <= fileSize; if (lastOffset < fileSize) { results.add(new BlockInfo(lastOffset, fileSize, null)); } if (results.isEmpty()) { results.add(new BlockInfo(0, fileSize, null)); } if (combineBlocks) { results = combine(results); } return new BlockMap(path, results.toArray(new BlockInfo[results.size()])); } private static List<BlockInfo> combine(List<BlockInfo> blocks) { assert blocks != null; List<BlockInfo> results = new ArrayList<>(blocks.size()); Iterator<BlockInfo> iter = blocks.iterator(); assert iter.hasNext(); BlockInfo last = iter.next(); while (iter.hasNext()) { BlockInfo next = iter.next(); if (last.isSameOwner(next)) { last = new BlockInfo(last.start, next.end, last.hosts); } else { results.add(last); last = next; } } results.add(last); return results; } /** * Returns {@link DirectInputFragment} for the range. * @param start the start offset (inclusive) * @param end the end offset (exclusive) * @return the computed fragment */ public DirectInputFragment get(long start, long end) { List<String> hosts = computeHosts(start, end); return new DirectInputFragment(path, start, end - start, hosts); } private List<String> computeHosts(long start, long end) { assert start <= end; if (start == end) { return Collections.emptyList(); } List<Map.Entry<String, Long>> rank = computeLocalityRank(start, end); if (rank.isEmpty()) { return Collections.emptyList(); } long max = rank.get(0).getValue(); if (max < (end - start) * MIN_LOCALITY) { return Collections.emptyList(); } long threshold = (long) (max * PRUNE_REL_LOCALITY); List<String> results = new ArrayList<>(); for (int i = 0, n = rank.size(); i < n; i++) { Map.Entry<String, Long> block = rank.get(i); if (block.getValue() < threshold) { break; } results.add(block.getKey()); } return results; } private List<Map.Entry<String, Long>> computeLocalityRank(long start, long end) { Map<String, Long> ownBytes = new HashMap<>(); for (BlockInfo block : blocks) { if (block.end < start) { continue; } if (block.start >= end) { break; } long s = Math.max(start, block.start); long e = Math.min(end, block.end); long length = e - s; for (String node : block.getHosts()) { Long bytes = ownBytes.get(node); if (bytes == null) { ownBytes.put(node, length); } else { ownBytes.put(node, bytes + length); } } } if (ownBytes.isEmpty()) { return Collections.emptyList(); } List<Map.Entry<String, Long>> entries = new ArrayList<>(ownBytes.entrySet()); Collections.sort(entries, (o1, o2) -> Long.compare(o2.getValue(), o1.getValue())); return entries; } }
apache-2.0
veyronfei/clouck
src/main/java/com/clouck/comparator/Ec2InstanceComparator.java
13136
package com.clouck.comparator; import java.util.Collection; import java.util.List; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.amazonaws.services.ec2.model.GroupIdentifier; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceNetworkInterface; import com.amazonaws.services.ec2.model.InstancePrivateIpAddress; import com.clouck.model.Event; import com.clouck.model.EventType; import com.clouck.model.aws.ec2.Ec2Instance; @Component public class Ec2InstanceComparator extends AbstractEc2Comparator<Ec2Instance> { private static final Logger log = LoggerFactory.getLogger(Ec2InstanceComparator.class); @Override public Event initialise(Ec2Instance newResource) { return createEvent(null, newResource, EventType.Ec2_Instance_Found); } @Override public Event firstScan() { return createFirstScanEvent(EventType.Ec2_Instance_First_Scan); } @Override public Event add(Ec2Instance newResource) { Instance instance = newResource.getResource(); String state = instance.getState().getName(); switch (state) { case "pending": return createEvent(null, newResource, EventType.Ec2_Instance_Pending); case "shutting-down": return createEvent(null, newResource, EventType.Ec2_Instance_Shutting_Down); case "stopping": return createEvent(null, newResource, EventType.Ec2_Instance_Stopping); case "running": return createEvent(null, newResource, EventType.Ec2_Instance_Launch); case "stopped": return createEvent(null, newResource, EventType.Ec2_Instance_Stop); default: log.error("not handled instance state:{}", state); return createEvent(null, newResource, EventType.Unknown); } } @Override public Event delete(Ec2Instance oldResource) { return createEvent(oldResource, null, EventType.Ec2_Instance_Terminate); } @Override protected void update(List<Event> result, Ec2Instance oldResource, Ec2Instance newResource) { Instance oldInstance = oldResource.getResource(); Instance newInstance = newResource.getResource(); compareInstanceState(result, oldResource, newResource); compareSecurityGroups(result, oldInstance.getSecurityGroups(), newInstance.getSecurityGroups(), oldResource, newResource); if (notEqual(oldInstance.getSourceDestCheck(), newInstance.getSourceDestCheck())) { //during shutting down, before terminated, this source dest check is null which causes NPE if (newInstance.getSourceDestCheck() != null) { result.add(createEvent(oldResource, newResource, newInstance.getSourceDestCheck() ? EventType.Ec2_Instance_Source_Dest_Check_Enabled : EventType.Ec2_Instance_Source_Dest_Check_Disabled)); } else { log.error("not handled null source dst check"); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } compareNetworkInterfaces(result, oldInstance.getNetworkInterfaces(), newInstance.getNetworkInterfaces(), oldResource, newResource); if (notEqual(oldInstance.getMonitoring().getState(), newInstance.getMonitoring().getState())) { if (newInstance.getMonitoring().getState().equals("enabled")) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Monitoring_Enabled)); } else if (newInstance.getMonitoring().getState().equals("disabled")) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Monitoring_Disabled)); } else { log.error("not handled monitoring state:{}", newInstance.getMonitoring().getState()); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } if (notEqual(oldResource.getTerminationProtection(), newResource.getTerminationProtection())) { if (newResource.getTerminationProtection() != null) { result.add(createEvent(oldResource, newResource, newResource.getTerminationProtection() ? EventType.Ec2_Instance_Termination_Protection_Enabled : EventType.Ec2_Instance_Termination_Protection_Disabled)); } else { log.error("not handled null termination protection"); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } if (notEqual(oldResource.getShutdownBehavior(), newResource.getShutdownBehavior())) { if (newResource.getShutdownBehavior().equals("stop")) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Shutdown_Behavior_Stop)); } else if (newResource.getShutdownBehavior().equals("terminate")) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Shutdown_Behavior_Terminate)); } else { log.error("not handled shut down behavior:{}", newResource.getShutdownBehavior()); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } if (notEqual(oldInstance.getInstanceType(), newInstance.getInstanceType())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Instance_Type, oldInstance.getInstanceType(), newInstance.getInstanceType())); } if (notEqual(oldInstance.getEbsOptimized(), newInstance.getEbsOptimized())) { if (newInstance.getEbsOptimized() != null) { result.add(createEvent(oldResource, newResource, newInstance.getEbsOptimized() ? EventType.Ec2_Instance_EBS_Optimized_Enabled : EventType.Ec2_Instance_EBS_Optimized_Disabled)); } else { log.error("not handled null ebs optimized"); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } if (notEqual(oldResource.getUserData(), newResource.getUserData())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_User_Data_Changed)); } compareTags(result, oldInstance.getTags(), newInstance.getTags(), oldResource, newResource); } private void compareNetworkInterfaces(Collection<Event> result, List<InstanceNetworkInterface> oldNetworkInterfaces, List<InstanceNetworkInterface> newNetworkInterfaces, Ec2Instance oldResource, Ec2Instance newResource) { CompareResult<InstanceNetworkInterface> compareResult = resourceUtil.compareNetworkInterfaces(oldNetworkInterfaces, newNetworkInterfaces); for (Pair<InstanceNetworkInterface, InstanceNetworkInterface> pair : compareResult.getUpdate()) { InstanceNetworkInterface oldINI = pair.getLeft(); InstanceNetworkInterface newINI = pair.getRight(); if (notEqual(oldINI.getAssociation(), newINI.getAssociation())) { if (newINI.getAssociation() == null) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Elastic_Ip_Disassociated, oldINI.getAssociation().getPublicIp(), newINI.getNetworkInterfaceId())); } else { log.error("not handled association:{}", newINI.getAssociation()); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } if (notEqual(oldINI.getAttachment().getStatus(), newINI.getAttachment().getStatus())) { generateEvents4Attachment(result, newINI, oldResource, newResource); } CompareResult<InstancePrivateIpAddress> compareResultIPIA = resourceUtil.comparePrivateIpAddresses(oldINI.getPrivateIpAddresses(), newINI.getPrivateIpAddresses()); for (InstancePrivateIpAddress ipi : compareResultIPIA.getAdd()) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Private_Ip_Assigned, ipi.getPrivateIpAddress(), newINI.getNetworkInterfaceId())); } for (InstancePrivateIpAddress ipi : compareResultIPIA.getDelete()) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Private_Ip_Unassigned, ipi.getPrivateIpAddress(), newINI.getNetworkInterfaceId())); } for (Pair<InstancePrivateIpAddress, InstancePrivateIpAddress> p : compareResultIPIA.getUpdate()) { log.error("not handled case"); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } if (equal(oldINI.getAssociation(), newINI.getAssociation()) && equal(oldINI.getAttachment().getStatus(), newINI.getAttachment().getStatus()) && compareResultIPIA.getAdd().size() == 0 && compareResultIPIA.getDelete().size() == 0 && compareResultIPIA.getUpdate().size() == 0) { log.error("not handled case"); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } for (InstanceNetworkInterface ini : compareResult.getAdd()) { generateEvents4Attachment(result, ini, oldResource, newResource); } for (InstanceNetworkInterface ini : compareResult.getDelete()) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Network_Interface_Detached, ini.getNetworkInterfaceId())); } } private void generateEvents4Attachment(Collection<Event> result, InstanceNetworkInterface ini, Ec2Instance oldResource, Ec2Instance newResource) { String status = ini.getAttachment().getStatus(); if (status.equals("attaching")) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Network_Interface_Attaching, ini.getNetworkInterfaceId())); } else if (status.equals("attached")) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Network_Interface_Attached, ini.getNetworkInterfaceId())); } else if (status.equals("detaching")) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Network_Interface_Detaching, ini.getNetworkInterfaceId())); } else { log.error("not handled attachment status:{}", status); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } private void compareSecurityGroups(Collection<Event> result, List<GroupIdentifier> oldSecurityGroups, List<GroupIdentifier> newSecurityGroups, Ec2Instance oldResource, Ec2Instance newResource) { CompareResult<GroupIdentifier> compareResult = resourceUtil.compare(oldSecurityGroups, newSecurityGroups); for (GroupIdentifier gi : compareResult.getAdd()) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Security_Group_Added, gi.getGroupName())); } for (GroupIdentifier gi : compareResult.getDelete()) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Security_Group_Deleted, gi.getGroupName())); } for (Pair<GroupIdentifier, GroupIdentifier> pair : compareResult.getUpdate()) { log.error("not handled case"); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } private void compareInstanceState(Collection<Event> result, Ec2Instance oldResource, Ec2Instance newResource) { Instance newInstance = newResource.getResource(); Instance oldInstance = oldResource.getResource(); String newState = newInstance.getState().getName(); String oldState = oldInstance.getState().getName(); if (notEqual(newState, oldState)) { switch (newState) { case "pending": result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Pending)); break; case "shutting-down": result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Shutting_Down)); break; case "stopping": result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Stopping)); break; case "terminated": result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Terminate)); break; case "running": result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Launch)); break; case "stopped": result.add(createEvent(oldResource, newResource, EventType.Ec2_Instance_Stop)); break; default: log.error("not handled instance state:" + newState); result.add(createEvent(oldResource, newResource, EventType.Unknown)); } } } }
apache-2.0
gilles-stragier/quickmon
src/main/java/be/fgov/caamihziv/services/quickmon/interfaces/api/RootController.java
1023
package be.fgov.caamihziv.services.quickmon.interfaces.api; import be.fgov.caamihziv.services.quickmon.interfaces.api.healthChecks.HealthChecksController; import be.fgov.caamihziv.services.quickmon.interfaces.api.notifiers.NotifiersController; import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.mvc.ControllerLinkBuilder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Created by gs on 16.04.17. */ @RestController @RequestMapping("/api") public class RootController { @RequestMapping(method = RequestMethod.GET) public ResourceSupport root() { ResourceSupport root = new ResourceSupport(); root.add(ControllerLinkBuilder.linkTo(HealthChecksController.class).withRel("healthChecks")); root.add(ControllerLinkBuilder.linkTo(NotifiersController.class).withRel("notifiers")); return root; } }
apache-2.0
skrauchenia/borsch
borsch-web/src/main/java/com/exadel/borsch/web/controllers/PrintController.java
1648
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.exadel.borsch.web.controllers; import com.exadel.borsch.util.PDFCreator; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author Fedor */ @Controller public class PrintController { @Secured("ROLE_PRINT_ORDER") @RequestMapping("/print/pdf") public void loadOrderTablePDF(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException { String src = request.getParameter("src"); File filePdf = new File("table.pdf"); PDFCreator.create(src, filePdf.getName()); InputStream stream = new FileInputStream(filePdf); byte[] data = IOUtils.toByteArray(stream); stream.close(); response.setHeader("Content-type", "application/download"); response.setHeader("Content-length", Integer.toString(data.length)); response.setHeader("Content-transfer-encodig", "binary"); response.setHeader("Content-disposition", "attachment; filename=table.pdf"); response.getOutputStream().write(data); } }
apache-2.0
MosumTree/lightning
app/src/main/java/com/example/mosum/lightning/vitamioVideoView.java
1658
package com.example.mosum.lightning; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import io.vov.vitamio.MediaPlayer; import io.vov.vitamio.Vitamio; import io.vov.vitamio.widget.VideoView; /** * Created by mosum on 2017/6/3. */ public class vitamioVideoView extends Activity { private VideoView mVideoView; private Intent intent; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //必须写这个,初始化加载库文件 Vitamio.isInitialized(this); setContentView(R.layout.file_layout); mVideoView = (VideoView) findViewById(R.id.buffer); /*intent = getIntent(); String movieUrl = intent.getStringExtra("movieUrl");*/ String movieUrl="http://baobab.wdjcdn.com/145076769089714.mp4"; //判断path来自于网络还是本地 if (!movieUrl.isEmpty()) { if (movieUrl.startsWith("http:")) { mVideoView.setVideoURI(Uri.parse(movieUrl)); } else { mVideoView.setVideoPath(movieUrl); } mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_STRETCH, 0);//全屏 mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);//高画质 mVideoView.requestFocus(); mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.setPlaybackSpeed(1.0f); } }); } } }
apache-2.0
hotpads/datarouter
datarouter-filesystem/src/main/java/io/datarouter/filesystem/snapshot/encode/BlockDecoderFactory.java
1262
/* * Copyright © 2009 HotPads (admin@hotpads.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datarouter.filesystem.snapshot.encode; import javax.inject.Inject; import javax.inject.Singleton; import io.datarouter.filesystem.snapshot.block.BlockTypeRegistry; import io.datarouter.filesystem.snapshot.block.root.RootBlock; @Singleton public class BlockDecoderFactory{ @Inject private BlockTypeRegistry blockTypeRegistry; public BlockDecoder create(RootBlock rootBlock){ return new BlockDecoder( rootBlock.getClass(), blockTypeRegistry.getBranchClass(rootBlock.branchBlockType()), blockTypeRegistry.getLeafClass(rootBlock.leafBlockType()), blockTypeRegistry.getValueClass(rootBlock.valueBlockType())); } }
apache-2.0
vlad-mk/spring-randomport
src/main/java/io/github/vladmk/randomport/RefreshContextListener.java
580
package io.github.vladmk.randomport; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; /** * Created by Vlad Mikerin on 7/7/17. */ @Component @Slf4j public class RefreshContextListener { @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { log.debug("Refreshing context"); RandomPortPropertySource.addToEnvironment(event.getApplicationContext().getEnvironment()); } }
apache-2.0
yswift/WeatherForceast
app/src/main/java/cn/edu/uoh/cs/weatherforecast/WeatherInfo.java
1288
package cn.edu.uoh.cs.weatherforecast; import java.util.HashMap; import java.util.Map; public class WeatherInfo { private String desc; private Integer status; private Data data; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * * @return * The desc */ public String getDesc() { return desc; } /** * * @param desc * The desc */ public void setDesc(String desc) { this.desc = desc; } /** * * @return * The status */ public Integer getStatus() { return status; } /** * * @param status * The status */ public void setStatus(Integer status) { this.status = status; } /** * * @return * The data */ public Data getData() { return data; } /** * * @param data * The data */ public void setData(Data data) { this.data = data; } public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
apache-2.0
wburns/radargun
core/src/main/java/org/radargun/stages/cache/background/CheckBackgroundStressorsStage.java
1937
package org.radargun.stages.cache.background; import org.radargun.DistStageAck; import org.radargun.config.Property; import org.radargun.config.Stage; import org.radargun.stages.AbstractDistStage; import org.radargun.stages.DefaultDistStageAck; /** * @author Radim Vansa &lt;rvansa@redhat.com&gt; */ @Stage(doc = "Stage that checks the progress in background stressors and fails if something went wrong.") public class CheckBackgroundStressorsStage extends AbstractDistStage { @Property(doc = "Do not write additional operations until all operations are confirmed. Default is false.") private boolean waitUntilChecked = false; @Property(doc = "Resume writers after we have stopped them in order to let checkers check everything. Default is false.") private boolean resumeAfterChecked = false; @Override public DistStageAck executeOnSlave() { DefaultDistStageAck ack = newDefaultStageAck(); if (slaves != null && !slaves.contains(slaveState.getSlaveIndex())) { return ack; } BackgroundOpsManager manager = BackgroundOpsManager.getInstance(slaveState); if (manager != null) { String error = manager.getError(); if (error != null) { return fail(error); } if (waitUntilChecked && resumeAfterChecked) { return fail("Cannot both wait and resume in the same stage; other node may have not finished checking."); } if (waitUntilChecked) { error = manager.waitUntilChecked(); if (error != null) { return fail(error); } } else if (resumeAfterChecked) { manager.resumeAfterChecked(); } } return ack; } private DistStageAck fail(String error) { DefaultDistStageAck ack = newDefaultStageAck(); log.error(error); ack.setError(true); ack.setErrorMessage(error); return ack; } }
apache-2.0
ahwxl/deep
src/main/java/org/activiti/engine/impl/persistence/entity/ByteArrayRef.java
2505
package org.activiti.engine.impl.persistence.entity; import java.io.Serializable; import org.activiti.engine.impl.context.Context; /** * <p>Encapsulates the logic for transparently working with {@link ByteArrayEntity}.</p> * * <p>Make sure that instance variables (i.e. fields) of this type are always initialized, * and thus <strong>never</strong> null.</p> * * <p>For example:</p> * <pre> * private final ByteArrayRef byteArrayRef = new ByteArrayRef(); * </pre> * * @author Marcus Klimstra (CGI) */ public final class ByteArrayRef implements Serializable { private static final long serialVersionUID = 1L; private String id; private String name; private ByteArrayEntity entity; protected boolean deleted = false; public ByteArrayRef() { } // Only intended to be used by ByteArrayRefTypeHandler public ByteArrayRef(String id) { this.id = id; } public String getId() { return id; } public String getName() { return name; } public byte[] getBytes() { ensureInitialized(); return (entity != null ? entity.getBytes() : null); } public void setValue(String name, byte[] bytes) { this.name = name; setBytes(bytes); } private void setBytes(byte[] bytes) { if (id == null) { if (bytes != null) { entity = ByteArrayEntity.createAndInsert(name, bytes); id = entity.getId(); } } else { ensureInitialized(); entity.setBytes(bytes); } } public ByteArrayEntity getEntity() { ensureInitialized(); return entity; } public void delete() { if (!deleted && id != null) { if (entity != null) { // if the entity has been loaded already, // we might as well use the safer optimistic locking delete. Context.getCommandContext() .getByteArrayEntityManager() .deleteByteArray(entity); } else { Context.getCommandContext() .getByteArrayEntityManager() .deleteByteArrayById(id); } deleted = true; } } private void ensureInitialized() { if (id != null && entity == null) { entity = Context.getCommandContext() .getByteArrayEntityManager() .findById(id); name = entity.getName(); } } public boolean isDeleted() { return deleted; } @Override public String toString() { return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" :"]"); } }
apache-2.0
aparod/jonix
jonix-common/src/main/java/com/tectonica/jonix/struct/JonixProductFormFeature.java
1291
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tectonica.jonix.struct; import java.io.Serializable; import java.util.List; import com.tectonica.jonix.codelist.ProductFormFeatureTypes; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ @SuppressWarnings("serial") public class JonixProductFormFeature implements Serializable { /** * The key of this struct */ public ProductFormFeatureTypes productFormFeatureType; /** * (type: dt.NonEmptyString) */ public List<String> productFormFeatureDescriptions; /** * (type: dt.NonEmptyString) */ public String productFormFeatureValue; }
apache-2.0
kressnerd/JetPDF2CSV
src/main/java/de/kressnerd/jetpdf2csv/JetPDF2CSV.java
6963
/* * Copyright (c) 2016. Daniel Kressner * * This file to under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. * */ package de.kressnerd.jetpdf2csv; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class JetPDF2CSV { private static final String tHead = "Year Month Date Dep Block-Off Arr " + "Block-On Blocktime AcType AcRegId PiC CP RP FO I SIM"; public static void main(String[] args) { PDDocument pdDoc = null; boolean isFlight = false; Flight.iata2icaoInit(); List<Flight> flightList = new ArrayList<Flight>(); try { pdDoc = PDDocument.load(new File(args[0])); PDFTextStripper pdfStripper = new PDFTextStripper(); pdfStripper.setStartPage(1); pdfStripper.setEndPage(pdDoc.getNumberOfPages()); String parsedText = pdfStripper.getText(pdDoc); String[] pages = parsedText.split(tHead); for (int i = 0; i < pages.length; i++) { String page = pages[i].trim(); int year = 4711; try { year = Integer.parseInt(page.substring(0, 4)); // throw away year and month from first column String page_n = page.substring(7, page.length()).trim(); String[] rows = page_n.split(System.getProperty("line.separator")); for (int j = 0; j < rows.length; j++) { Flight curFlight = new Flight(); isFlight = false; String row = rows[j]; String[] cols = row.split(" "); // check for flight entry: length 14 and first is date. if (cols.length == 14 && cols[0].matches("[0123][\\d]\\.[01][0-9]\\.")) { isFlight = true; curFlight.setDepartDate(cols[0] + year); curFlight.setOrigin(cols[1]); curFlight.setDepartTime(cols[2]); curFlight.setDestination(cols[3]); curFlight.setFlightArrivalTime(cols[4]); curFlight.setFlightTime(cols[5]); curFlight.setACType(cols[6]); curFlight.setTailNumber(cols[7]); curFlight.setPIC(cols[12]); if (curFlight.checkFlightOperation(cols[13]) == false) { System.out.println("Block time is not equal flight op time for flight: " + curFlight); } for (int k = 14; k < cols.length; k++) { System.out.println(cols[k]); } curFlight.setIsFlight(true); flightList.add(curFlight); } else if (cols.length == 21 && cols[0].matches("[01-3][\\d]\\.[01][012]\\.")) { isFlight = true; curFlight.setDepartDate(cols[0] + year); curFlight.setDepartTime(cols[2]); curFlight.setFlightArrivalTime(cols[6]); curFlight.setFlightTime(cols[20]); curFlight.setRemark("SIM"); for (int k = 21; k < cols.length; k++) { System.out.println(cols[k]); } curFlight.setIsFlight(true); flightList.add(curFlight); } else if (row.contains("Summary")) { int totalFlightTimeMinutes = 0; int totalSimTimeMinutes = 0; int anzfl = 0; for (Flight fl : flightList) { if (fl.isSim()) { totalSimTimeMinutes += fl.getFlightTimeInMinutes(); } else { totalFlightTimeMinutes += fl.getFlightTimeInMinutes(); } anzfl += 1; } System.out.println(); System.out.println("Summary " + cols[0]); System.out.println("-------"); System.out.println("Number of flights: " + anzfl); System.out.println("Calc. flight hours: " + Flight.flightTimeInHoursMinutes(totalFlightTimeMinutes)); System.out.println("PDF flight hours: " + cols[4]); if (totalSimTimeMinutes > 0 && cols.length > 4) { System.out.println("Calc sim hours: " + Flight.flightTimeInHoursMinutes(totalSimTimeMinutes)); System.out.println("PDF im hours: " + cols[5]); } } isFlight = false; } } catch (NumberFormatException e) { // do nothing, just next page } } PrintWriter csvOut = new PrintWriter(args[0] + ".csv"); csvOut.println("Lfd-Nr.;Datum;Kennzeichen;Muster;PiC;Gast;Von;Nach;Startzeit;Landezeit;Stunden;Minuten;"+ "Landungen;Startart;Bemerkungen;Flugbedingung;Startart;Lizenztyp;block-off;block-on;counter-on;"+ "counter-off"); int i = 1; for (Flight tmpFl : flightList) { csvOut.print(i); csvOut.println(tmpFl); i++; } csvOut.close(); System.out.println(); } catch (FileNotFoundException fnfe) { System.out.println("Please provide a pdf file:"); System.out.println("# java JetPDF2CSV _yourfile.pdf"); } catch (IOException e) { e.printStackTrace(); } } }
apache-2.0
aifargonos/elk-reasoner
elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/saturation/inferences/AbstractDisjointSubsumerInference.java
2633
package org.semanticweb.elk.reasoner.saturation.inferences; /* * #%L * ELK Reasoner * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2011 - 2015 Department of Computer Science, University of Oxford * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.semanticweb.elk.owl.interfaces.ElkAxiom; import org.semanticweb.elk.reasoner.indexing.model.IndexedClassExpressionList; import org.semanticweb.elk.reasoner.indexing.model.IndexedContextRoot; import org.semanticweb.elk.reasoner.saturation.conclusions.classes.DisjointSubsumerImpl; import org.semanticweb.elk.reasoner.saturation.conclusions.model.DisjointSubsumer; import org.semanticweb.elk.reasoner.tracing.TracingInference; import org.semanticweb.elk.reasoner.tracing.TracingInferencePrinter; abstract class AbstractDisjointSubsumerInference extends DisjointSubsumerImpl implements DisjointSubsumerInference { public AbstractDisjointSubsumerInference(IndexedContextRoot root, IndexedClassExpressionList disjoint, int position, ElkAxiom reason) { super(root, disjoint, position, reason); } /** * @param factory * the factory for creating conclusions * * @return the conclusion produced by this inference */ public final DisjointSubsumer getConclusion(DisjointSubsumer.Factory factory) { return factory.getDisjointSubsumer(getDestination(), getDisjointExpressions(), getPosition(), getReason()); } @Override public final int hashCode() { return System.identityHashCode(this); } @Override public final boolean equals(Object o) { return this == o; } @Override public final String toString() { return TracingInferencePrinter.toString(this); } @Override public final <O> O accept(TracingInference.Visitor<O> visitor) { return accept((DisjointSubsumerInference.Visitor<O>) visitor); } @Override public final <O> O accept(SaturationInference.Visitor<O> visitor) { return accept((DisjointSubsumerInference.Visitor<O>) visitor); } @Override public final <O> O accept(ClassInference.Visitor<O> visitor) { return accept((DisjointSubsumerInference.Visitor<O>) visitor); } }
apache-2.0
ltshddx/jaop
gradle-plugin/src/main/groovy/javassist/JaopClassPool.java
428
package javassist; /** * Created by liting06 on 16/1/27. */ public class JaopClassPool extends ClassPool { @Override protected CtClass createCtClass(String classname, boolean useCache) { CtClass ctClass = super.createCtClass(classname, useCache); if (ctClass instanceof CtClassType) { return new JaopCtClass(classname, this); } else { return ctClass; } } }
apache-2.0
evandor/skysail-framework
skysail.server/src/io/skysail/server/utils/SkysailBeanUtilsBean.java
10209
package io.skysail.server.utils; import java.beans.*; import java.lang.reflect.*; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; import org.apache.commons.beanutils.*; import org.apache.commons.beanutils.expression.Resolver; import org.apache.commons.lang3.StringUtils; import io.skysail.domain.Identifiable; import lombok.extern.slf4j.Slf4j; @Slf4j public class SkysailBeanUtilsBean extends BeanUtilsBean { private static final String DATE_PATTERN = "yyyy-MM-dd"; public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); if (target == null) { // the value of a nested property is null return; } name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target // property Class<?> type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the property type if (target instanceof DynaBean) { throw new IllegalStateException("cannot handle DynaBeans"); } else if (target instanceof Map) { type = Object.class; } else if (target != null && target.getClass().isArray() && index >= 0) { type = Array.get(target, index).getClass(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } if (descriptor instanceof MappedPropertyDescriptor) { if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType(); } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) { if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType(); } else if (key != null) { if (descriptor.getReadMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = (value == null) ? Object.class : value.getClass(); } else { if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = descriptor.getPropertyType(); } } // Convert the specified value to the required type Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value == null) { String[] values = new String[1]; values[0] = null; newValue = getConvertUtils().convert(values, type); } else if (value instanceof String) { newValue = getConvertUtils().convert(value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert((String[]) value, type); } else { newValue = convert(value, type); } } else if (type.isArray()) { // Indexed value into array if (value instanceof String || value == null) { newValue = getConvertUtils().convert((String) value, type.getComponentType()); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType()); } else { newValue = convert(value, type.getComponentType()); } } else { // Value into scalar if (value instanceof String && Collection.class.isAssignableFrom(type)) { try { newValue = new ArrayList<Identifiable>(); Class<?> parameterizedType = getParameterizedType(bean, name); createAndSetNewIdentifiables(Arrays.asList((String)value), newValue, parameterizedType); } catch (NoSuchFieldException | SecurityException e) { log.error(e.getMessage(), e); } } else if (value instanceof Collection && Collection.class.isAssignableFrom(type)) { try { newValue = new ArrayList<Identifiable>(); Class<?> parameterizedType = getParameterizedType(bean, name); if (parameterizedType != null) { createAndSetNewIdentifiables((Collection<?>) value, newValue, parameterizedType); } } catch (NoSuchFieldException | SecurityException e) { log.error(e.getMessage(), e); } } else if (value instanceof String) { newValue = getConvertUtils().convert((String) value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type); } else { newValue = convert(value, type); } } // Invoke the setter method try { getPropertyUtils().setProperty(target, name, newValue); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } private void createAndSetNewIdentifiables(Collection<?> values, Object newValue, Class<?> parameterizedType) { if (Identifiable.class.isAssignableFrom(parameterizedType)) { List<String> ids = values.stream().map(v -> v.toString()).collect(Collectors.toList()); for (String id : ids) { createAndSetNewIdentifiable(id, newValue, parameterizedType); } } } private Class<?> getParameterizedType(Object bean, String name) throws NoSuchFieldException { Field declaredField = bean.getClass().getDeclaredField(name); io.skysail.domain.html.Field fieldAnnotation = declaredField.getAnnotation(io.skysail.domain.html.Field.class); if (fieldAnnotation == null) { return null; } throw new IllegalStateException("not expected to reach this code"); // Class<? extends DbRepository> repository = fieldAnnotation.repository(); // return ReflectionUtils.getParameterizedType(repository); } @SuppressWarnings("unchecked") private void createAndSetNewIdentifiable(Object value, Object newValue, Class<?> parameterizedType) { Identifiable newInstance; try { newInstance = (Identifiable) parameterizedType.newInstance(); newInstance.setId((String) value); ((List<Identifiable>) newValue).add(newInstance); } catch (Exception e) { log.error(e.getMessage(), e); } } public SkysailBeanUtilsBean(Object bean, Locale locale) { super(new ConvertUtilsBean() { @SuppressWarnings("unchecked") @Override public Object convert(String value, @SuppressWarnings("rawtypes") Class clazz) { if (clazz.isEnum()) { return Enum.valueOf(clazz, value); } else if (clazz.equals(LocalDate.class)) { if (StringUtils.isEmpty(value)) { return null; } DateTimeFormatter sdf = DateTimeFormatter.ofPattern(DATE_PATTERN, locale); try { return LocalDate.parse(value, sdf); } catch (Exception e) { log.info("could not parse date '{}' with pattern {}", value, DATE_PATTERN); } return null; } else if (clazz.equals(Date.class)) { if (StringUtils.isEmpty(value)) { return null; } SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN, locale); try { return sdf.parse(value); } catch (Exception e) { log.info("could not parse date '{}' with pattern {}", value, DATE_PATTERN); } return null; } else { return super.convert(value, clazz); } } }); } }
apache-2.0
SENA-CEET/1349397-Trimestre-4
java/JSF/mavenproject2/src/main/java/co/edu/sena/mavenproject2/model/entities/Ficha.java
5169
/* * 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 co.edu.sena.mavenproject2.model.entities; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Enrique */ @Entity @Table(name = "ficha") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Ficha.findAll", query = "SELECT f FROM Ficha f") , @NamedQuery(name = "Ficha.findByNumeroFicha", query = "SELECT f FROM Ficha f WHERE f.numeroFicha = :numeroFicha") , @NamedQuery(name = "Ficha.findByEstado", query = "SELECT f FROM Ficha f WHERE f.estado = :estado")}) public class Ficha implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 20) @Column(name = "numero_ficha", nullable = false, length = 20) private String numeroFicha; @Basic(optional = false) @NotNull @Size(min = 1, max = 40) @Column(name = "estado", nullable = false, length = 40) private String estado; @OneToMany(cascade = CascadeType.ALL, mappedBy = "ficha", fetch = FetchType.LAZY) private Collection<GrupoProyecto> grupoProyectoCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "ficha1", fetch = FetchType.LAZY) private Collection<InstructorFicha> instructorFichaCollection; @OneToOne(cascade = CascadeType.ALL, mappedBy = "ficha1", fetch = FetchType.LAZY) private FichaHasLista fichaHasLista; @JoinColumn(name = "jornada_nombre", referencedColumnName = "nombre", nullable = false) @ManyToOne(optional = false, fetch = FetchType.LAZY) private Jornada jornadaNombre; @JoinColumn(name = "programa_codigo_version", referencedColumnName = "codigo_version", nullable = false) @ManyToOne(optional = false, fetch = FetchType.LAZY) private Programa programaCodigoVersion; public Ficha() { } public Ficha(String numeroFicha) { this.numeroFicha = numeroFicha; } public Ficha(String numeroFicha, String estado) { this.numeroFicha = numeroFicha; this.estado = estado; } public String getNumeroFicha() { return numeroFicha; } public void setNumeroFicha(String numeroFicha) { this.numeroFicha = numeroFicha; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } @XmlTransient public Collection<GrupoProyecto> getGrupoProyectoCollection() { return grupoProyectoCollection; } public void setGrupoProyectoCollection(Collection<GrupoProyecto> grupoProyectoCollection) { this.grupoProyectoCollection = grupoProyectoCollection; } @XmlTransient public Collection<InstructorFicha> getInstructorFichaCollection() { return instructorFichaCollection; } public void setInstructorFichaCollection(Collection<InstructorFicha> instructorFichaCollection) { this.instructorFichaCollection = instructorFichaCollection; } public FichaHasLista getFichaHasLista() { return fichaHasLista; } public void setFichaHasLista(FichaHasLista fichaHasLista) { this.fichaHasLista = fichaHasLista; } public Jornada getJornadaNombre() { return jornadaNombre; } public void setJornadaNombre(Jornada jornadaNombre) { this.jornadaNombre = jornadaNombre; } public Programa getProgramaCodigoVersion() { return programaCodigoVersion; } public void setProgramaCodigoVersion(Programa programaCodigoVersion) { this.programaCodigoVersion = programaCodigoVersion; } @Override public int hashCode() { int hash = 0; hash += (numeroFicha != null ? numeroFicha.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Ficha)) { return false; } Ficha other = (Ficha) object; if ((this.numeroFicha == null && other.numeroFicha != null) || (this.numeroFicha != null && !this.numeroFicha.equals(other.numeroFicha))) { return false; } return true; } @Override public String toString() { return "co.edu.sena.mavenproject2.model.entities.Ficha[ numeroFicha=" + numeroFicha + " ]"; } }
apache-2.0
xtien/motogymkhana-server-ui
src/main/java/eu/motogymkhana/server/api/result/TokenResult.java
96
package eu.motogymkhana.server.api.result; public class TokenResult extends GymkhanaResult{ }
apache-2.0
MAXIMUM13/websocket-demo
src/main/java/ru/maximum13/wsdemo/util/DateTimeUtils.java
5002
package ru.maximum13.wsdemo.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.concurrent.TimeUnit; /** * Набор утилитных методов для работы с датой и временем. * * @author MAXIMUM13 */ public final class DateTimeUtils { public static Calendar calendarOf(int year, int month, int day) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day); return calendar; } public static Calendar calendarOf(int year, int month, int day, int hours, int min) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day, hours, min); return calendar; } public static Calendar calendarOf(int year, int month, int day, int hours, int min, int sec) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month, day, hours, min, sec); return calendar; } public static Calendar calendarOf(int year, int month, int day, int hours, int min, int sec, int ms) { Calendar calendar = calendarOf(year, month, day, hours, min, sec); calendar.set(Calendar.MILLISECOND, ms); return calendar; } public static Date dateOf(int year, int month, int day) { return calendarOf(year, month, day).getTime(); } public static Date dateOf(int year, int month, int day, int hours, int min) { return calendarOf(year, month, day, hours, min).getTime(); } public static Date dateOf(int year, int month, int day, int hours, int min, int sec) { return calendarOf(year, month, day, hours, min, sec).getTime(); } public static Date dateOf(int year, int month, int day, int hours, int min, int sec, int ms) { return calendarOf(year, month, day, hours, min, sec, ms).getTime(); } /** * Проверяет, следует ли первая дата за второй или равна ей (great or equals). * * @param firstDate * первая дата * @param secondDate * вторая дата */ public static boolean ge(Date firstDate, Date secondDate) { return firstDate.compareTo(secondDate) >= 0; } /** * Проверяет, предшествует ли первая дата второй или равна ей (less or equals). * * @param firstDate * первая дата * @param secondDate * вторая дата */ public static boolean le(Date firstDate, Date secondDate) { return firstDate.compareTo(secondDate) <= 0; } /** * Возвращает строку с текущей датой, отформатированной по переданному шаблону. * * @param dateFormat * шаблон даты */ public static String formatCurrentDate(final String dateFormat) { return format(new Date(), dateFormat); } /** * Возвращает строку с датой, отформатированной по переданному шаблону. * * @param date * дата * @param dateFormat * шаблон даты */ public static String format(final Date date, final String dateFormat) { return new SimpleDateFormat(dateFormat).format(date); } /** * Обнуляет количество часов, минут, секунд и миллисекунд у переданного календаря. */ public static void resetTime(final Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); } /** * Возвращает строку, содержащую текущее время в миллисекундах. */ public static String currentTimeMillisString() { return Long.toString(System.currentTimeMillis()); } /** * Возвращает новую дату, отличающуюся от переданной на заданное значение. * * @param date * первоначальная дата * @param value * значение единицы времени, на которую нужно изменить дату * @param unit * единица времени, в которой задано изменение */ public static Date changeDate(final Date date, final long value, final TimeUnit unit) { Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(date.getTime() + unit.toMillis(value)); return calendar.getTime(); } private DateTimeUtils() { ErrorUtils.throwPrivateMethodAccessError(this); } }
apache-2.0
gcock/spring-mybatis
729jishi/src/com/spring/pojo/Member.java
1159
package com.spring.pojo; import java.io.Serializable; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; public class Member implements Serializable{ private static final long serialVersionUID = 1L; private Integer id; private String name; private String phone; private Integer level; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date inTime; private String cardNo; public Member() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public Date getInTime() { return inTime; } public void setInTime(Date inTime) { this.inTime = inTime; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-securityhub/src/main/java/com/amazonaws/services/securityhub/model/AwsEc2SecurityGroupPrefixListId.java
4150
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.securityhub.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A prefix list ID. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/AwsEc2SecurityGroupPrefixListId" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AwsEc2SecurityGroupPrefixListId implements Serializable, Cloneable, StructuredPojo { /** * <p> * The ID of the prefix. * </p> */ private String prefixListId; /** * <p> * The ID of the prefix. * </p> * * @param prefixListId * The ID of the prefix. */ public void setPrefixListId(String prefixListId) { this.prefixListId = prefixListId; } /** * <p> * The ID of the prefix. * </p> * * @return The ID of the prefix. */ public String getPrefixListId() { return this.prefixListId; } /** * <p> * The ID of the prefix. * </p> * * @param prefixListId * The ID of the prefix. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2SecurityGroupPrefixListId withPrefixListId(String prefixListId) { setPrefixListId(prefixListId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPrefixListId() != null) sb.append("PrefixListId: ").append(getPrefixListId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AwsEc2SecurityGroupPrefixListId == false) return false; AwsEc2SecurityGroupPrefixListId other = (AwsEc2SecurityGroupPrefixListId) obj; if (other.getPrefixListId() == null ^ this.getPrefixListId() == null) return false; if (other.getPrefixListId() != null && other.getPrefixListId().equals(this.getPrefixListId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPrefixListId() == null) ? 0 : getPrefixListId().hashCode()); return hashCode; } @Override public AwsEc2SecurityGroupPrefixListId clone() { try { return (AwsEc2SecurityGroupPrefixListId) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.securityhub.model.transform.AwsEc2SecurityGroupPrefixListIdMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
opensim-org/opensim-gui
Gui/opensim/modeling/src/org/opensim/modeling/SWIGTYPE_p_SimTK__Matrix_T_SimTK__UnitVecT_double_1_t_t.java
906
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.2 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.opensim.modeling; public class SWIGTYPE_p_SimTK__Matrix_T_SimTK__UnitVecT_double_1_t_t { private transient long swigCPtr; protected SWIGTYPE_p_SimTK__Matrix_T_SimTK__UnitVecT_double_1_t_t(long cPtr, @SuppressWarnings("unused") boolean futureUse) { swigCPtr = cPtr; } protected SWIGTYPE_p_SimTK__Matrix_T_SimTK__UnitVecT_double_1_t_t() { swigCPtr = 0; } protected static long getCPtr(SWIGTYPE_p_SimTK__Matrix_T_SimTK__UnitVecT_double_1_t_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } }
apache-2.0
ArnaudFavier/Chatbot-GrandLyon
native-apps/android/AslanGrandLyon/app/src/main/java/com/alsan_grand_lyon/aslangrandlyon/service/LoadImageTask.java
1639
package com.alsan_grand_lyon.aslangrandlyon.service; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import com.alsan_grand_lyon.aslangrandlyon.dao.UserDAO; import com.alsan_grand_lyon.aslangrandlyon.model.DataSingleton; import com.alsan_grand_lyon.aslangrandlyon.model.User; import com.alsan_grand_lyon.aslangrandlyon.view.chat.TemplateView; import com.alsan_grand_lyon.aslangrandlyon.view.launch.SplashActivity; import java.io.InputStream; /** * Created by Nico on 24/04/2017. */ public class LoadImageTask extends AsyncTask<String, String, Bitmap> { private Context context; private TemplateView templateView; public LoadImageTask(Context context, TemplateView templateView) { this.context = context; this.templateView = templateView; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Bitmap doInBackground(String... params) { String url = params[0]; Bitmap bitmap = FileManager.loadImage(context, url);; try { if(bitmap == null) { // Download Image from URL InputStream input = new java.net.URL(url).openStream(); // Decode Bitmap bitmap = BitmapFactory.decodeStream(input); FileManager.saveBitmap(context, bitmap, url); } } catch (Exception e) { } return bitmap; } @Override protected void onPostExecute(Bitmap result) { templateView.showImage(result); } }
apache-2.0
CODA-Masters/Pong-Tutorial
core/src/com/codamasters/pong/gameobjects/Bounds.java
2548
package com.codamasters.pong.gameobjects; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.ChainShape; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactFilter; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; public class Bounds implements ContactFilter, ContactListener { private Body body; private Fixture fixture; public Bounds(World world) { BodyDef bodyDef = new BodyDef(); FixtureDef fixtureDef = new FixtureDef(); float groundPos = -2.5f; float topPos = 7.5f; // body definition bodyDef.type = BodyType.StaticBody; bodyDef.position.set(0, groundPos); // ground shape ChainShape groundShapeBottom = new ChainShape(); ChainShape groundShapeTop = new ChainShape(); /* groundShape.createChain(new Vector2[] {new Vector2(-10, groundPos), new Vector2(10,groundPos), new Vector2(10, 8.35f), new Vector2(-10,8.35f), new Vector2(-10,groundPos)}); */ groundShapeBottom.createChain(new Vector2[] {new Vector2(-10, groundPos), new Vector2(10,groundPos)}); groundShapeTop.createChain(new Vector2[] {new Vector2(-10, topPos), new Vector2(10,topPos)}); // fixture definition fixtureDef.shape = groundShapeBottom; body = world.createBody(bodyDef); fixture = body.createFixture(fixtureDef); // fixture definition fixtureDef.shape = groundShapeTop; body = world.createBody(bodyDef); fixture = body.createFixture(fixtureDef); groundShapeTop.dispose(); groundShapeBottom.dispose(); } @Override public void beginContact(Contact contact) { // TODO Auto-generated method stub } @Override public void endContact(Contact contact) { // TODO Auto-generated method stub } @Override public void preSolve(Contact contact, Manifold oldManifold) { // TODO Auto-generated method stub } @Override public void postSolve(Contact contact, ContactImpulse impulse) { // TODO Auto-generated method stub } @Override public boolean shouldCollide(Fixture fixtureA, Fixture fixtureB) { // TODO Auto-generated method stub return false; } }
apache-2.0
pomadchin/insta-followz
src/main/java/com/dc/insta/InstagramUtils.java
820
package com.dc.insta; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public final class InstagramUtils { private static final String CONFIG_PROPERTIES = "/config.properties"; public static Properties getConfigProperties() { InputStream input = null; final Properties prop = new Properties(); try { input = InstagramUtils.class.getResourceAsStream(CONFIG_PROPERTIES); prop.load(input); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return prop; } }
apache-2.0
claremontqualitymanagement/TestAutomationFramework
Core/src/test/java/se/claremont/taf/core/reporting/testrunreports/htmlsummaryreport/NewErrorsListTest.java
8375
package se.claremont.taf.core.reporting.testrunreports.htmlsummaryreport; import org.junit.Assert; import org.junit.Test; import se.claremont.taf.core.logging.LogLevel; import se.claremont.taf.core.support.SupportMethods; import se.claremont.taf.core.testcase.TestCase; import se.claremont.taf.core.testset.UnitTestClass; import java.util.ArrayList; import java.util.List; /** * Created by jordam on 2017-04-10. */ public class NewErrorsListTest extends UnitTestClass{ @Test public void emptyNewErrorInfosShouldGenerateEmtpyString() throws Exception { List<NewError> newErrorInfos = new ArrayList<>(); NewErrorsList newErrorsList = new NewErrorsList(newErrorInfos, new ArrayList<>()); Assert.assertTrue(newErrorsList.toString().contentEquals("")); } @Test public void singleSharedNewErrorsShouldBePrinted(){ List<NewError> newErrorInfos = new ArrayList<>(); TestCase testCase1 = new TestCase(); testCase1.log(LogLevel.VERIFICATION_FAILED, "No such data '123' in element Button1. Time duration 321 milliseconds."); newErrorInfos.add(new NewError(testCase1, testCase1.testCaseResult.testCaseLog.onlyErroneousLogPosts())); TestCase testCase2 = new TestCase(); testCase2.log(LogLevel.VERIFICATION_FAILED, "No such data '456' in element Button1. Time duration 987 milliseconds."); newErrorInfos.add(new NewError(testCase2, testCase2.testCaseResult.testCaseLog.onlyErroneousLogPosts())); NewErrorsList newErrorsList = new NewErrorsList(newErrorInfos, new ArrayList<>()); //String regexPattern = ".*Similar log records found in multiple test cases.*"; String regexPattern = ".*Similar log records found in multiple test cases" + ".*Verification failed.*No such data .* in element Button1. Time duration .*milliseconds" + ".*Nameless test case" + ".*Log" + ".*Nameless test case" + ".*Log.*"; Assert.assertTrue("Expected the output to be a match for the regular expression pattern:" + System.lineSeparator() + regexPattern + System.lineSeparator() + "But it was:" + System.lineSeparator() + newErrorsList.toString(), SupportMethods.isRegexMatch(newErrorsList.toString(), regexPattern)); } @Test public void multipleSharedNewErrorsShouldBePrintedInOrder(){ List<NewError> newErrorInfos = new ArrayList<>(); TestCase testCase1 = new TestCase(); testCase1.log(LogLevel.VERIFICATION_FAILED, "No such data '123' in element Button1. Time duration 321 milliseconds."); testCase1.log(LogLevel.VERIFICATION_FAILED, "Next error '123'"); newErrorInfos.add(new NewError(testCase1, testCase1.testCaseResult.testCaseLog.onlyErroneousLogPosts())); TestCase testCase2 = new TestCase(); testCase2.log(LogLevel.VERIFICATION_FAILED, "No such data '456' in element Button1. Time duration 987 milliseconds."); testCase2.log(LogLevel.VERIFICATION_FAILED, "Next error '123'"); newErrorInfos.add(new NewError(testCase2, testCase2.testCaseResult.testCaseLog.onlyErroneousLogPosts())); NewErrorsList newErrorsList = new NewErrorsList(newErrorInfos, new ArrayList<>()); String output = newErrorsList.toString(); System.out.println(output); //String regexPattern = ".*Similar log records found in multiple test cases.*"; String regexPattern = ".*Similar log records found in multiple test cases" + ".*Verification failed.*No such data .* in element Button1. Time duration .*milliseconds" + ".*Next" + ".*Nameless test case.*Log" + ".*Nameless test case.*Log.*"; Assert.assertTrue("Expected the output to be a match for the regular expression pattern:" + System.lineSeparator() + regexPattern + System.lineSeparator() + "But it was:" + System.lineSeparator() + output, SupportMethods.isRegexMatch(output, regexPattern)); Assert.assertFalse(output.contains("Log extracts for test cases with unique problems")); } @Test public void testCasesWithExtraProblemsShouldBePrintedSeparately(){ List<NewError> newErrorInfos = new ArrayList<>(); TestCase testCase1 = new TestCase(null, "Test1"); testCase1.log(LogLevel.VERIFICATION_FAILED, "No such data '123' in element Button1. Time duration 321 milliseconds."); testCase1.log(LogLevel.VERIFICATION_FAILED, "Next error '123'"); testCase1.log(LogLevel.VERIFICATION_FAILED, "My own error"); newErrorInfos.add(new NewError(testCase1, testCase1.testCaseResult.testCaseLog.onlyErroneousLogPosts())); TestCase testCase2 = new TestCase(null, "Test2"); testCase2.log(LogLevel.VERIFICATION_FAILED, "No such data '456' in element Button1. Time duration 987 milliseconds."); testCase2.log(LogLevel.VERIFICATION_FAILED, "Next error '123'"); newErrorInfos.add(new NewError(testCase2, testCase2.testCaseResult.testCaseLog.onlyErroneousLogPosts())); NewErrorsList newErrorsList = new NewErrorsList(newErrorInfos, new ArrayList<>()); String output = newErrorsList.toString(); System.out.println(output); //String regexPattern = ".*Similar log records found in multiple test cases.*"; String regexPattern = ".*Similar log records found in multiple test cases.*No such data .* in element Button1.*Time duration .*milliseconds.*Next error.*Test1.*Test2.*Test case also has problematic log records not part of shared log row.*Log extracts for failed test cases with unique problems.*My own error.*Test1.*"; Assert.assertTrue("Expected the output to be a match for the regular expression pattern:" + System.lineSeparator() + regexPattern + System.lineSeparator() + "But it was:" + System.lineSeparator() + output, SupportMethods.isRegexMatch(output, regexPattern)); } @Test public void testCasesWithExtraProblemsShouldBePrintedSeparatelyWithTotallyUnSharedTestCaseInfo(){ List<NewError> newErrorInfos = new ArrayList<>(); TestCase testCase1 = new TestCase(null, "Test1"); testCase1.log(LogLevel.VERIFICATION_FAILED, "No such data '123' in element Button1. Time duration 321 milliseconds."); testCase1.log(LogLevel.VERIFICATION_FAILED, "Next error '123'"); testCase1.log(LogLevel.VERIFICATION_FAILED, "My own error"); newErrorInfos.add(new NewError(testCase1, testCase1.testCaseResult.testCaseLog.onlyErroneousLogPosts())); TestCase testCase3 = new TestCase(null, "Test3"); testCase3.log(LogLevel.VERIFICATION_FAILED, "Totally unique test case error1"); testCase3.log(LogLevel.VERIFICATION_FAILED, "Totally unique test case error2"); testCase3.log(LogLevel.VERIFICATION_FAILED, "Totally unique test case error3"); newErrorInfos.add(new NewError(testCase3, testCase3.testCaseResult.testCaseLog.onlyErroneousLogPosts())); TestCase testCase2 = new TestCase(null, "Test2"); testCase2.log(LogLevel.VERIFICATION_FAILED, "No such data '456' in element Button1. Time duration 987 milliseconds."); testCase2.log(LogLevel.VERIFICATION_FAILED, "Next error '123'"); newErrorInfos.add(new NewError(testCase2, testCase2.testCaseResult.testCaseLog.onlyErroneousLogPosts())); NewErrorsList newErrorsList = new NewErrorsList(newErrorInfos, new ArrayList<>()); String output = newErrorsList.toString(); System.out.println(output); //String regexPattern = ".*Similar log records found in multiple test cases.*"; String regexPattern = ".*Similar log records found in multiple test cases" + ".*No such data .* in element Button1.*Time duration .*milliseconds" + ".*Next error " + ".*Test1" + ".*Test2" + ".*Test case also has problematic log records not part of shared log row" + ".*Log extracts for failed test cases with unique problems" + ".*My own error" + ".*Test1.*"; Assert.assertTrue("Expected the output to be a match for the regular expression pattern:" + System.lineSeparator() + regexPattern + System.lineSeparator() + "But it was:" + System.lineSeparator() + output, SupportMethods.isRegexMatch(output, regexPattern)); } }
apache-2.0
GaneshSPatil/gocd
server/src/test-integration/java/com/thoughtworks/go/server/dao/PluginSqlMapDaoIntegrationTest.java
6165
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.dao; import com.google.gson.GsonBuilder; import com.thoughtworks.go.domain.NullPlugin; import com.thoughtworks.go.domain.Plugin; import com.thoughtworks.go.server.cache.GoCache; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.hamcrest.MatcherAssert.assertThat; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "classpath:/applicationContext-global.xml", "classpath:/applicationContext-dataLocalAccess.xml", "classpath:/testPropertyConfigurer.xml", "classpath:/spring-all-servlet.xml", }) public class PluginSqlMapDaoIntegrationTest { @Autowired private PluginSqlMapDao pluginSqlMapDao; @Autowired private DatabaseAccessHelper dbHelper; @Autowired private GoCache goCache; @BeforeEach public void setup() throws Exception { dbHelper.onSetUp(); pluginSqlMapDao.deleteAllPlugins(); } @AfterEach public void teardown() throws Exception { pluginSqlMapDao.deleteAllPlugins(); dbHelper.onTearDown(); } @Test public void shouldSavePlugin() { assertThat(pluginSqlMapDao.getAllPlugins().size(), is(0)); Plugin plugin = savePlugin("plugin-id"); assertThat(pluginSqlMapDao.getAllPlugins().size(), is(1)); Plugin pluginInDB = pluginSqlMapDao.getAllPlugins().get(0); assertThat(pluginInDB, is(plugin)); } @Test public void shouldUpdatePlugin() { assertThat(pluginSqlMapDao.getAllPlugins().size(), is(0)); Plugin plugin = savePlugin("plugin-id"); plugin.setConfiguration(getConfigurationJSON("k1", "v1")); pluginSqlMapDao.saveOrUpdate(plugin); Plugin pluginInDB = pluginSqlMapDao.findPlugin("plugin-id"); assertThat(pluginInDB, is(plugin)); } @Test public void shouldReturnCorrectPluginIfPluginIdExists() { Plugin plugin = savePlugin("plugin-id"); assertThat(goCache.get(pluginSqlMapDao.cacheKeyForPluginSettings("plugin-id")), is(nullValue())); Plugin pluginInDB = pluginSqlMapDao.findPlugin("plugin-id"); assertThat(pluginInDB, is(plugin)); assertThat(goCache.get(pluginSqlMapDao.cacheKeyForPluginSettings("plugin-id")), is(pluginInDB)); } @Test public void shouldReturnNullPluginIfPluginIdDoesNotExist() { Plugin pluginInDB = pluginSqlMapDao.findPlugin("non-existing-plugin-id"); assertThat(pluginInDB, is(new NullPlugin())); } @Test public void shouldReturnAllPlugins() { Plugin plugin1 = savePlugin("plugin-id-1"); List<Plugin> plugins = pluginSqlMapDao.getAllPlugins(); assertThat(plugins.size(), is(1)); assertThat(plugins.get(0), is(plugin1)); Plugin plugin2 = savePlugin("plugin-id-2"); plugins = pluginSqlMapDao.getAllPlugins(); assertThat(plugins.size(), is(2)); assertThat(plugins, containsInAnyOrder(plugin1, plugin2)); } @Test public void shouldDoNothingWhenAPluginToDeleteDoesNotExists() { String pluginId = "my.fancy.plugin.id"; assertThat(goCache.get(pluginSqlMapDao.cacheKeyForPluginSettings(pluginId)), is(nullValue())); assertThat(pluginSqlMapDao.getAllPlugins().size(), is(0)); pluginSqlMapDao.deletePluginIfExists(pluginId); assertThat(goCache.get(pluginSqlMapDao.cacheKeyForPluginSettings(pluginId)), is(nullValue())); assertThat(pluginSqlMapDao.getAllPlugins().size(), is(0)); } @Test public void shouldDeleteAPlugin() { String pluginId = "my.fancy.plugin.id"; Plugin plugin = savePlugin(pluginId); Plugin pluginInDB = pluginSqlMapDao.findPlugin(pluginId); assertThat(pluginInDB, is(plugin)); assertThat(goCache.get(pluginSqlMapDao.cacheKeyForPluginSettings(pluginId)), is(plugin)); assertThat(pluginSqlMapDao.getAllPlugins().size(), is(1)); pluginSqlMapDao.deletePluginIfExists(pluginId); assertThat(goCache.get(pluginSqlMapDao.cacheKeyForPluginSettings(pluginId)), is(nullValue())); assertThat(pluginSqlMapDao.getAllPlugins().size(), is(0)); } @Test public void shouldDeleteAllPlugins() { savePlugin("plugin-id-1"); savePlugin("plugin-id-2"); List<Plugin> plugins = pluginSqlMapDao.getAllPlugins(); assertThat(plugins.size(), is(2)); pluginSqlMapDao.deleteAllPlugins(); plugins = pluginSqlMapDao.getAllPlugins(); assertThat(plugins.size(), is(0)); } private Plugin savePlugin(String pluginId) { Plugin plugin = new Plugin(pluginId, getConfigurationJSON("k1", "v1", "k2", "v2")); pluginSqlMapDao.saveOrUpdate(plugin); return plugin; } private String getConfigurationJSON(String... args) { assertThat(args.length % 2, is(0)); Map<String, String> configuration = new HashMap<>(); for (int i = 0; i < args.length - 2; i = i + 2) { configuration.put(args[i], args[i + 1]); } return new GsonBuilder().create().toJson(configuration); } }
apache-2.0
xmydeveloper/MMWeather
app/src/main/java/com/xlw/mmweather/gson/Basic.java
429
package com.xlw.mmweather.gson; import com.google.gson.annotations.SerializedName; /** * Created by xmydeveloper on 2017/9/29/0029. */ public class Basic { @SerializedName("city") public String cityName; @SerializedName("id") public String weatherId; @SerializedName("update") public Update update; public class Update { @SerializedName("loc") public String updateTime; } }
apache-2.0
hugeterry/CoordinatorTabLayout
sample/src/main/java/cn/hugeterry/coordinatortablayoutdemo/MyPagerAdapter.java
922
package cn.hugeterry.coordinatortablayoutdemo; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.ArrayList; /** * Created by hugeterry(http://hugeterry.cn) */ public class MyPagerAdapter extends FragmentPagerAdapter { private ArrayList<Fragment> mFragments = new ArrayList<>(); private final String[] mTitles; public MyPagerAdapter(FragmentManager fm, ArrayList<Fragment> mFragments, String[] mTitles) { super(fm); this.mFragments = mFragments; this.mTitles = mTitles; } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mTitles[position]; } @Override public Fragment getItem(int position) { return mFragments.get(position); } }
apache-2.0
weiwenqiang/GitHub
ListView/MultiTypeRecyclerViewAdapter-master/app/src/main/java/com/crazysunj/multityperecyclerviewadapter/helper/ErrorAndEmptyAdapterHelper.java
5114
package com.crazysunj.multityperecyclerviewadapter.helper; import android.support.v7.util.DiffUtil; import android.util.Log; import com.chad.library.adapter.base.BaseQuickAdapter; import com.crazysunj.multitypeadapter.entity.HandleBase; import com.crazysunj.multitypeadapter.helper.RecyclerViewAdapterHelper; import com.crazysunj.multityperecyclerviewadapter.R; import com.crazysunj.multityperecyclerviewadapter.sticky.StickyItem; import java.util.List; import io.reactivex.Flowable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.LEVEL_FIRST; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.LEVEL_FOURTH; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.LEVEL_SENCOND; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.LEVEL_THIRD; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.TYPE_FOUR; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.TYPE_ONE; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.TYPE_THREE; import static com.crazysunj.multityperecyclerviewadapter.helper.SimpleHelper.TYPE_TWO; /** * description * <p> * Created by sunjian on 2017/5/6. */ public class ErrorAndEmptyAdapterHelper extends RecyclerViewAdapterHelper<StickyItem, BaseQuickAdapter> { public ErrorAndEmptyAdapterHelper() { this(null); } public ErrorAndEmptyAdapterHelper(List<StickyItem> data, @RefreshMode int mode) { super(data, mode); } public ErrorAndEmptyAdapterHelper(List<StickyItem> data) { super(data); } @Override protected void startRefresh(HandleBase<StickyItem> refreshData) { Flowable.just(refreshData) .onBackpressureDrop() .observeOn(Schedulers.computation()) .map(new Function<HandleBase<StickyItem>, DiffUtil.DiffResult>() { @Override public DiffUtil.DiffResult apply(@NonNull HandleBase<StickyItem> handleBase) throws Exception { return handleRefresh(handleBase.getNewData(), handleBase.getNewHeader(), handleBase.getNewFooter(), handleBase.getType(), handleBase.getRefreshType()); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<DiffUtil.DiffResult>() { @Override public void accept(@NonNull DiffUtil.DiffResult diffResult) throws Exception { handleResult(diffResult); } }); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "刷新开始---当前Type:" + getCurrentRefreshType()); } @Override protected void onEnd() { super.onEnd(); Log.d(TAG, "刷新结束"); } @Override protected void registerMoudle() { registerMoudle(TYPE_ONE) .level(LEVEL_FIRST) .layoutResId(R.layout.item_first) .headerResId(R.layout.item_header) .loading() .loadingLayoutResId(R.layout.layout_default_shimmer_view) .loadingHeaderResId(R.layout.layout_default_shimmer_header_view) .register(); registerMoudle(TYPE_FOUR) .level(LEVEL_THIRD) .layoutResId(R.layout.item_third) .headerResId(R.layout.item_header_img) .loading() .loadingLayoutResId(R.layout.layout_default_shimmer_view) .loadingHeaderResId(R.layout.layout_default_shimmer_header_view) .empty() .emptyLayoutResId(R.layout.layout_empty) .register(); registerMoudle(TYPE_TWO) .level(LEVEL_FOURTH) .layoutResId(R.layout.item_fourth) .headerResId(R.layout.item_header_img) .loading() .loadingLayoutResId(R.layout.layout_default_shimmer_view) .loadingHeaderResId(R.layout.layout_default_shimmer_header_view) .error() .errorLayoutResId(R.layout.layout_error_two) .register(); registerMoudle(TYPE_THREE) .level(LEVEL_SENCOND) .layoutResId(R.layout.item_second) .headerResId(R.layout.item_header_img) .loading() .loadingLayoutResId(R.layout.layout_default_shimmer_view) .loadingHeaderResId(R.layout.layout_default_shimmer_header_view) .error() .errorLayoutResId(R.layout.layout_error) .register(); } @Override protected int getPreDataCount() { return mAdapter.getHeaderLayoutCount(); } }
apache-2.0
GenaBitu/OdyMaterialy-app
app/src/main/java/cz/skaut/mlha/odymaterialy/LoadingFragment.java
2033
package cz.skaut.mlha.odymaterialy; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog.Builder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * A fragment which shows a loading wheel. Also displays an error dialog when loading failed for some reason. */ @SuppressWarnings("WeakerAccess") public class LoadingFragment extends Fragment { /** * Creates the root view. */ @Override public final View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_loading, container, false); } /** * Call when loading a lesson failed. Shows an error dialog, than returns to the previous fragment. */ public final void failLesson() { final Builder builder = new Builder(getActivity()); builder.setCancelable(false); builder.setTitle(getString(R.string.lesson_load_fail_title)); builder.setMessage(getString(R.string.lesson_load_fail_message)); builder.setPositiveButton(getString(R.string.lesson_load_fail_ok), new OnClickListener() { @Override public void onClick(final DialogInterface dialogInterface, final int i) { getFragmentManager().popBackStack(); } }); builder.show(); } /** * Call when loading the Lesson list failed. Shows an error dialog. */ public final void failApp() { final Builder builder = new Builder(getActivity()); builder.setCancelable(false); builder.setTitle(getString(R.string.app_load_fail_title)); builder.setMessage(getString(R.string.app_load_fail_message)); builder.setPositiveButton(getString(R.string.app_load_fail_ok), new EmptyOnClickListener()); builder.show(); } private static class EmptyOnClickListener implements OnClickListener { @Override public void onClick(final DialogInterface dialogInterface, final int i) {} } }
apache-2.0
hazendaz/assertj-core
src/main/java/org/assertj/core/error/ShouldBeAssignableFrom.java
1751
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.error; import java.util.Set; /** * Creates an error message indicating that an assertion that verifies that a class is assignable from. * * @author William Delanoue */ public class ShouldBeAssignableFrom extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldBeAssignableFrom}</code>. * * @param actual the actual value in the failed assertion. * @param expectedAssignableFrom the expected assignable. * @param missingAssignableFrom the missing classes. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeAssignableFrom(Class<?> actual, Set<Class<?>> expectedAssignableFrom, Set<Class<?>> missingAssignableFrom) { return new ShouldBeAssignableFrom(actual, expectedAssignableFrom, missingAssignableFrom); } private ShouldBeAssignableFrom(Class<?> actual, Set<Class<?>> expectedAssignableFrom, Set<Class<?>> missingAssignableFrom) { super("%nExpecting%n %s%nto be assignable from:%n %s%nbut was not assignable from:%n %s", actual, expectedAssignableFrom, missingAssignableFrom); } }
apache-2.0
hazendaz/assertj-core
src/test/java/org/assertj/core/internal/urls/Urls_assertHasNoHost_Test.java
2310
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.internal.urls; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.uri.ShouldHaveNoHost.shouldHaveNoHost; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import java.net.MalformedURLException; import java.net.URL; import java.util.stream.Stream; import org.assertj.core.internal.UrlsBaseTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; class Urls_assertHasNoHost_Test extends UrlsBaseTest { @Test void should_fail_if_actual_is_null() { // GIVEN URL actual = null; // WHEN AssertionError assertionError = expectAssertionError(() -> urls.assertHasNoHost(info, actual)); // THEN then(assertionError).hasMessage(actualIsNull()); } @Test void should_fail_if_host_present() throws MalformedURLException { // GIVEN URL actual = new URL("https://example.com"); // WHEN AssertionError assertionError = expectAssertionError(() -> urls.assertHasNoHost(info, actual)); // THEN then(assertionError).hasMessage(shouldHaveNoHost(actual).create()); } @ParameterizedTest @MethodSource("urls_with_no_host") void should_pass_if_host_is_not_present(URL actual) { // WHEN/THEN urls.assertHasNoHost(info, actual); } private static Stream<URL> urls_with_no_host() throws MalformedURLException { return Stream.of(new URL("file:///etc/lsb-release"), new URL("file", "", "/etc/lsb-release"), new URL("file", null, "/etc/lsb-release")); } }
apache-2.0
AdamsTHDev/payroll-project
src/main/java/com/adms/pvcon/service/PvConverterService.java
307
package com.adms.pvcon.service; import java.io.File; import org.apache.poi.ss.usermodel.Sheet; public interface PvConverterService { public StringBuffer doConvert(Sheet sheet) throws Exception; public String writeout(File file, StringBuffer contents, String encodeType) throws Exception; }
apache-2.0
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/interpolate/impl/NearestNeighborPixel_U8.java
2326
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.interpolate.impl; import boofcv.alg.interpolate.InterpolatePixelS; import boofcv.alg.interpolate.NearestNeighborPixelS; import boofcv.struct.border.ImageBorder_S32; import boofcv.struct.image.GrayU8; import boofcv.struct.image.ImageType; import javax.annotation.Generated; /** * <p> * Performs nearest neighbor interpolation to extract values between pixels in an image. * </p> * * * <p>DO NOT MODIFY. Automatically generated code created by GenerateNearestNeighborPixel_SB</p> * * @author Peter Abeles */ @Generated("boofcv.alg.interpolate.impl.GenerateNearestNeighborPixel_SB") public class NearestNeighborPixel_U8 extends NearestNeighborPixelS<GrayU8> { private byte[] data; public NearestNeighborPixel_U8() {} public NearestNeighborPixel_U8(GrayU8 orig) { setImage(orig); } @Override public void setImage(GrayU8 image) { super.setImage(image); this.data = orig.data; } @Override public float get_fast(float x, float y) { return data[ orig.startIndex + ((int)y)*stride + (int)x]& 0xFF; } public float get_border(float x, float y) { return ((ImageBorder_S32)border).get((int)Math.floor(x),(int)Math.floor(y)); } @Override public float get(float x, float y) { if (x < 0 || y < 0 || x > width-1 || y > height-1 ) return get_border(x,y); int xx = (int)x; int yy = (int)y; return data[ orig.startIndex + yy*stride + xx]& 0xFF; } @Override public InterpolatePixelS<GrayU8> copy() { var out = new NearestNeighborPixel_U8(); out.setBorder(border.copy()); return out; } @Override public ImageType<GrayU8> getImageType() { return ImageType.single(GrayU8.class); } }
apache-2.0
CloudScale-Project/StaticSpotter
plugins/org.reclipse.tracer.ui/src/org/reclipse/tracedefinition/editor/actions/FilterTraceDefinitionAction.java
1793
package org.reclipse.tracedefinition.editor.actions; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import org.reclipse.tracedefinition.editor.wizards.SplitTraceDefinitionWizard; /** * @author lowende * @author Last editor: $Author: lowende $ * @version $Revision: 3637 $ $Date: 2007-06-13 16:12:15 +0200 (Mi, 13 Jun 2007) $ */ public class FilterTraceDefinitionAction implements IObjectActionDelegate { private IWorkbenchPart targetPart; private ISelection selection; /** * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, * org.eclipse.ui.IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart targetPart) { this.targetPart = targetPart; } /** * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { SplitTraceDefinitionWizard wizard = new SplitTraceDefinitionWizard(); wizard.init(PlatformUI.getWorkbench(), (IStructuredSelection) this.selection); WizardDialog dialog = new WizardDialog(this.targetPart.getSite() .getShell(), wizard); dialog.open(); } /** * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, * org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IAction action, ISelection selection) { this.selection = selection; } }
apache-2.0
CloudScale-Project/StaticSpotter
plugins/org.reclipse.behavior.specification.ui/src/org/reclipse/behavior/specification/ui/commands/CreateOptionalFragmentCommand.java
855
package org.reclipse.behavior.specification.ui.commands; import org.reclipse.behavior.specification.ui.editparts.BehavioralPatternEditPart; import de.uni_paderborn.basicSequenceDiagram.BasicSequenceDiagramFactory; import de.uni_paderborn.basicSequenceDiagram.CombinedFragment; /** * @author mcp * @author Last editor: $Author$ * @version $Revision$ $Date$ * */ public class CreateOptionalFragmentCommand extends AbstractCreateCombinedFragmentCommand { public CreateOptionalFragmentCommand( BehavioralPatternEditPart diagramEditPart) { super(diagramEditPart); } @Override protected CombinedFragment createCombinedFragment() { CombinedFragment fragment = BasicSequenceDiagramFactory.eINSTANCE .createOptionalFragment(); return fragment; } }
apache-2.0
alancnet/artifactory
web/common/src/main/java/org/artifactory/common/wicket/component/table/columns/AttachColumnListener.java
1018
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory 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 3 of the License, or * (at your option) any later version. * * Artifactory 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 Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.common.wicket.component.table.columns; import org.artifactory.common.wicket.component.table.SortableTable; /** * @author Yoav Aharoni */ public interface AttachColumnListener<T> { void onColumnAttached(SortableTable<T> table); }
apache-2.0
jass2125/cinefilia
Cinefilia/src/main/java/model/interfacesdaoifs/UsuarioDaoIF.java
1023
/* * 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 model.interfacesdaoifs; import java.sql.SQLException; import java.util.List; import model.exceptions.DaoException; import model.values.Usuario; /** * * @author Anderson Souza */ public interface UsuarioDaoIF { public boolean add(Usuario usuario) throws SQLException, ClassNotFoundException, DaoException; public boolean update(Usuario usuario, String email) throws SQLException, ClassNotFoundException; public boolean delete(String email) throws SQLException, ClassNotFoundException; public List<Usuario> buscaUsuarios() throws SQLException, ClassNotFoundException; public List<Usuario> buscaTodosOsUsuarioPorEmail(String email) throws SQLException, ClassNotFoundException; public Usuario buscaUsuarioPorEmail(String email) throws SQLException, ClassNotFoundException; }
apache-2.0
r1305/FoodTracker
ParseStarterProject/build/generated/source/r/debug/com/google/android/gms/R.java
16433
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms; public final class R { public static final class attr { public static final int adSize = 0x7f010026; public static final int adSizes = 0x7f010027; public static final int adUnitId = 0x7f010028; public static final int ambientEnabled = 0x7f01007d; public static final int appTheme = 0x7f01015c; public static final int buyButtonAppearance = 0x7f010163; public static final int buyButtonHeight = 0x7f010160; public static final int buyButtonText = 0x7f010162; public static final int buyButtonWidth = 0x7f010161; public static final int cameraBearing = 0x7f01006e; public static final int cameraTargetLat = 0x7f01006f; public static final int cameraTargetLng = 0x7f010070; public static final int cameraTilt = 0x7f010071; public static final int cameraZoom = 0x7f010072; public static final int circleCrop = 0x7f01006c; public static final int environment = 0x7f01015d; public static final int fragmentMode = 0x7f01015f; public static final int fragmentStyle = 0x7f01015e; public static final int imageAspectRatio = 0x7f01006b; public static final int imageAspectRatioAdjust = 0x7f01006a; public static final int liteMode = 0x7f010073; public static final int mapType = 0x7f01006d; public static final int maskedWalletDetailsBackground = 0x7f010166; public static final int maskedWalletDetailsButtonBackground = 0x7f010168; public static final int maskedWalletDetailsButtonTextAppearance = 0x7f010167; public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f010165; public static final int maskedWalletDetailsLogoImageType = 0x7f01016a; public static final int maskedWalletDetailsLogoTextColor = 0x7f010169; public static final int maskedWalletDetailsTextAppearance = 0x7f010164; public static final int uiCompass = 0x7f010074; public static final int uiMapToolbar = 0x7f01007c; public static final int uiRotateGestures = 0x7f010075; public static final int uiScrollGestures = 0x7f010076; public static final int uiTiltGestures = 0x7f010077; public static final int uiZoomControls = 0x7f010078; public static final int uiZoomGestures = 0x7f010079; public static final int useViewLifecycle = 0x7f01007a; public static final int windowTransitionStyle = 0x7f010058; public static final int zOrderOnTop = 0x7f01007b; } public static final class color { public static final int common_action_bar_splitter = 0x7f0c0023; public static final int common_signin_btn_dark_text_default = 0x7f0c0024; public static final int common_signin_btn_dark_text_disabled = 0x7f0c0025; public static final int common_signin_btn_dark_text_focused = 0x7f0c0026; public static final int common_signin_btn_dark_text_pressed = 0x7f0c0027; public static final int common_signin_btn_default_background = 0x7f0c0028; public static final int common_signin_btn_light_text_default = 0x7f0c0029; public static final int common_signin_btn_light_text_disabled = 0x7f0c002a; public static final int common_signin_btn_light_text_focused = 0x7f0c002b; public static final int common_signin_btn_light_text_pressed = 0x7f0c002c; public static final int common_signin_btn_text_dark = 0x7f0c0081; public static final int common_signin_btn_text_light = 0x7f0c0082; public static final int wallet_bright_foreground_disabled_holo_light = 0x7f0c006a; public static final int wallet_bright_foreground_holo_dark = 0x7f0c006b; public static final int wallet_bright_foreground_holo_light = 0x7f0c006c; public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f0c006d; public static final int wallet_dim_foreground_holo_dark = 0x7f0c006e; public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f0c006f; public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f0c0070; public static final int wallet_highlighted_text_holo_dark = 0x7f0c0071; public static final int wallet_highlighted_text_holo_light = 0x7f0c0072; public static final int wallet_hint_foreground_holo_dark = 0x7f0c0073; public static final int wallet_hint_foreground_holo_light = 0x7f0c0074; public static final int wallet_holo_blue_light = 0x7f0c0075; public static final int wallet_link_text_light = 0x7f0c0076; public static final int wallet_primary_text_holo_light = 0x7f0c0085; public static final int wallet_secondary_text_holo_dark = 0x7f0c0086; } public static final class drawable { public static final int cast_ic_notification_0 = 0x7f020049; public static final int cast_ic_notification_1 = 0x7f02004a; public static final int cast_ic_notification_2 = 0x7f02004b; public static final int cast_ic_notification_connecting = 0x7f02004c; public static final int cast_ic_notification_on = 0x7f02004d; public static final int common_full_open_on_phone = 0x7f020060; public static final int common_ic_googleplayservices = 0x7f020061; public static final int common_signin_btn_icon_dark = 0x7f020062; public static final int common_signin_btn_icon_disabled_dark = 0x7f020063; public static final int common_signin_btn_icon_disabled_focus_dark = 0x7f020064; public static final int common_signin_btn_icon_disabled_focus_light = 0x7f020065; public static final int common_signin_btn_icon_disabled_light = 0x7f020066; public static final int common_signin_btn_icon_focus_dark = 0x7f020067; public static final int common_signin_btn_icon_focus_light = 0x7f020068; public static final int common_signin_btn_icon_light = 0x7f020069; public static final int common_signin_btn_icon_normal_dark = 0x7f02006a; public static final int common_signin_btn_icon_normal_light = 0x7f02006b; public static final int common_signin_btn_icon_pressed_dark = 0x7f02006c; public static final int common_signin_btn_icon_pressed_light = 0x7f02006d; public static final int common_signin_btn_text_dark = 0x7f02006e; public static final int common_signin_btn_text_disabled_dark = 0x7f02006f; public static final int common_signin_btn_text_disabled_focus_dark = 0x7f020070; public static final int common_signin_btn_text_disabled_focus_light = 0x7f020071; public static final int common_signin_btn_text_disabled_light = 0x7f020072; public static final int common_signin_btn_text_focus_dark = 0x7f020073; public static final int common_signin_btn_text_focus_light = 0x7f020074; public static final int common_signin_btn_text_light = 0x7f020075; public static final int common_signin_btn_text_normal_dark = 0x7f020076; public static final int common_signin_btn_text_normal_light = 0x7f020077; public static final int common_signin_btn_text_pressed_dark = 0x7f020078; public static final int common_signin_btn_text_pressed_light = 0x7f020079; public static final int ic_plusone_medium_off_client = 0x7f020098; public static final int ic_plusone_small_off_client = 0x7f020099; public static final int ic_plusone_standard_off_client = 0x7f02009a; public static final int ic_plusone_tall_off_client = 0x7f02009b; public static final int powered_by_google_dark = 0x7f0200c9; public static final int powered_by_google_light = 0x7f0200ca; } public static final class id { public static final int adjust_height = 0x7f0d0055; public static final int adjust_width = 0x7f0d0056; public static final int book_now = 0x7f0d006b; public static final int buyButton = 0x7f0d0068; public static final int buy_now = 0x7f0d006c; public static final int buy_with = 0x7f0d006d; public static final int buy_with_google = 0x7f0d006e; public static final int cast_notification_id = 0x7f0d0004; public static final int classic = 0x7f0d0072; public static final int donate_with = 0x7f0d006f; public static final int donate_with_google = 0x7f0d0070; public static final int google_wallet_classic = 0x7f0d0073; public static final int google_wallet_grayscale = 0x7f0d0074; public static final int google_wallet_monochrome = 0x7f0d0075; public static final int grayscale = 0x7f0d0076; public static final int holo_dark = 0x7f0d0062; public static final int holo_light = 0x7f0d0063; public static final int hybrid = 0x7f0d0057; public static final int logo_only = 0x7f0d0071; public static final int match_parent = 0x7f0d006a; public static final int monochrome = 0x7f0d0077; public static final int none = 0x7f0d0033; public static final int normal = 0x7f0d002f; public static final int production = 0x7f0d0064; public static final int sandbox = 0x7f0d0065; public static final int satellite = 0x7f0d0058; public static final int selectionDetails = 0x7f0d0069; public static final int slide = 0x7f0d0051; public static final int strict_sandbox = 0x7f0d0066; public static final int terrain = 0x7f0d0059; public static final int test = 0x7f0d0067; public static final int wrap_content = 0x7f0d0061; } public static final class integer { public static final int google_play_services_version = 0x7f0b0009; } public static final class raw { public static final int gtm_analytics = 0x7f060000; } public static final class string { public static final int accept = 0x7f07004a; public static final int auth_google_play_services_client_facebook_display_name = 0x7f07004e; public static final int auth_google_play_services_client_google_display_name = 0x7f07004f; public static final int cast_notification_connected_message = 0x7f070050; public static final int cast_notification_connecting_message = 0x7f070051; public static final int cast_notification_disconnect = 0x7f070052; public static final int common_android_wear_notification_needs_update_text = 0x7f070023; public static final int common_android_wear_update_text = 0x7f070024; public static final int common_android_wear_update_title = 0x7f070025; public static final int common_google_play_services_api_unavailable_text = 0x7f070026; public static final int common_google_play_services_enable_button = 0x7f070027; public static final int common_google_play_services_enable_text = 0x7f070028; public static final int common_google_play_services_enable_title = 0x7f070029; public static final int common_google_play_services_error_notification_requested_by_msg = 0x7f07002a; public static final int common_google_play_services_install_button = 0x7f07002b; public static final int common_google_play_services_install_text_phone = 0x7f07002c; public static final int common_google_play_services_install_text_tablet = 0x7f07002d; public static final int common_google_play_services_install_title = 0x7f07002e; public static final int common_google_play_services_invalid_account_text = 0x7f07002f; public static final int common_google_play_services_invalid_account_title = 0x7f070030; public static final int common_google_play_services_needs_enabling_title = 0x7f070031; public static final int common_google_play_services_network_error_text = 0x7f070032; public static final int common_google_play_services_network_error_title = 0x7f070033; public static final int common_google_play_services_notification_needs_update_title = 0x7f070034; public static final int common_google_play_services_notification_ticker = 0x7f070035; public static final int common_google_play_services_sign_in_failed_text = 0x7f070036; public static final int common_google_play_services_sign_in_failed_title = 0x7f070037; public static final int common_google_play_services_unknown_issue = 0x7f070038; public static final int common_google_play_services_unsupported_text = 0x7f070039; public static final int common_google_play_services_unsupported_title = 0x7f07003a; public static final int common_google_play_services_update_button = 0x7f07003b; public static final int common_google_play_services_update_text = 0x7f07003c; public static final int common_google_play_services_update_title = 0x7f07003d; public static final int common_google_play_services_updating_text = 0x7f07003e; public static final int common_google_play_services_updating_title = 0x7f07003f; public static final int common_open_on_phone = 0x7f070040; public static final int common_signin_button_text = 0x7f070054; public static final int common_signin_button_text_long = 0x7f070055; public static final int create_calendar_message = 0x7f070056; public static final int create_calendar_title = 0x7f070057; public static final int decline = 0x7f070058; public static final int store_picture_message = 0x7f07006c; public static final int store_picture_title = 0x7f07006d; public static final int wallet_buy_button_place_holder = 0x7f070049; } public static final class style { public static final int Theme_IAPTheme = 0x7f0a0115; public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f0a011d; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f0a011e; public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f0a011f; public static final int WalletFragmentDefaultStyle = 0x7f0a0120; } public static final class styleable { public static final int[] AdsAttrs = { 0x7f010026, 0x7f010027, 0x7f010028 }; public static final int AdsAttrs_adSize = 0; public static final int AdsAttrs_adSizes = 1; public static final int AdsAttrs_adUnitId = 2; public static final int[] CustomWalletTheme = { 0x7f010058 }; public static final int CustomWalletTheme_windowTransitionStyle = 0; public static final int[] LoadingImageView = { 0x7f01006a, 0x7f01006b, 0x7f01006c }; public static final int LoadingImageView_circleCrop = 2; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 0; public static final int[] MapAttrs = { 0x7f01006d, 0x7f01006e, 0x7f01006f, 0x7f010070, 0x7f010071, 0x7f010072, 0x7f010073, 0x7f010074, 0x7f010075, 0x7f010076, 0x7f010077, 0x7f010078, 0x7f010079, 0x7f01007a, 0x7f01007b, 0x7f01007c, 0x7f01007d }; public static final int MapAttrs_ambientEnabled = 16; public static final int MapAttrs_cameraBearing = 1; public static final int MapAttrs_cameraTargetLat = 2; public static final int MapAttrs_cameraTargetLng = 3; public static final int MapAttrs_cameraTilt = 4; public static final int MapAttrs_cameraZoom = 5; public static final int MapAttrs_liteMode = 6; public static final int MapAttrs_mapType = 0; public static final int MapAttrs_uiCompass = 7; public static final int MapAttrs_uiMapToolbar = 15; public static final int MapAttrs_uiRotateGestures = 8; public static final int MapAttrs_uiScrollGestures = 9; public static final int MapAttrs_uiTiltGestures = 10; public static final int MapAttrs_uiZoomControls = 11; public static final int MapAttrs_uiZoomGestures = 12; public static final int MapAttrs_useViewLifecycle = 13; public static final int MapAttrs_zOrderOnTop = 14; public static final int[] WalletFragmentOptions = { 0x7f01015c, 0x7f01015d, 0x7f01015e, 0x7f01015f }; public static final int WalletFragmentOptions_appTheme = 0; public static final int WalletFragmentOptions_environment = 1; public static final int WalletFragmentOptions_fragmentMode = 3; public static final int WalletFragmentOptions_fragmentStyle = 2; public static final int[] WalletFragmentStyle = { 0x7f010160, 0x7f010161, 0x7f010162, 0x7f010163, 0x7f010164, 0x7f010165, 0x7f010166, 0x7f010167, 0x7f010168, 0x7f010169, 0x7f01016a }; public static final int WalletFragmentStyle_buyButtonAppearance = 3; public static final int WalletFragmentStyle_buyButtonHeight = 0; public static final int WalletFragmentStyle_buyButtonText = 2; public static final int WalletFragmentStyle_buyButtonWidth = 1; public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; } }
apache-2.0
luoyefeiwu/learn_java
ee19_crm/src/com/jerry/crm/classes/domain/CrmClasses.java
3357
package com.jerry.crm.classes.domain; import java.util.Date; import com.jerry.crm.coursetype.domain.CrmCourseType; public class CrmClasses { /* * CREATE TABLE `crm_class` ( `classId` varchar(50) NOT NULL PRIMARY KEY, * `courseTypeId` varchar(255) DEFAULT NULL, * * `name` varchar(50) DEFAULT NULL, `beginTime` datetime DEFAULT NULL, * `endTime` datetime DEFAULT NULL, * * `status` varchar(20) DEFAULT NULL, `totalCount` int(11) DEFAULT NULL, * `upgradeCount` int(11) DEFAULT NULL, * * `changeCount` int(11) DEFAULT NULL, `runoffCount` int(11) DEFAULT NULL, * `remark` varchar(500) DEFAULT NULL, * * `uploadTime` datetime DEFAULT NULL, `uploadPath` varchar(200) DEFAULT * NULL, `uploadFilename` varchar(100) DEFAULT NULL, * * CONSTRAINT FOREIGN KEY (`courseTypeId`) REFERENCES `crm_course_type` * (`courseTypeId`) ) ; */ private String classId; private String name; // ¿Î³ÌÃû³Æ private Date beginTime; // ¿ª°àʱ¼ä private Date endTime; // ½áҵʱ¼ä private String status; // ״̬ private Integer totalCount; // ×ÜÈËÊý private Integer upgradeCount; // Éý¼¶Êý private Integer changeCount; // ת°àÊý private Integer runoffCount; // Á÷ʧÊý private String remark; // ÃèÊö private Date uploadTime; // ÉÏ´«Ê±¼ä private String uploadPath; // ÉÏ´«¿Î±í·¾¶ private String uploadFilename; // ÉÏ´«¿Î±íÃû³Æ // ¶à¶ÔÒ»£º¶à¸ö°à¼¶ ¿ÉÒÔ¶ÔÓ¦ Ò»¸ö¿Î³ÌÀà±ð private CrmCourseType courseType; public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Integer getUpgradeCount() { return upgradeCount; } public void setUpgradeCount(Integer upgradeCount) { this.upgradeCount = upgradeCount; } public Integer getChangeCount() { return changeCount; } public void setChangeCount(Integer changeCount) { this.changeCount = changeCount; } public Integer getRunoffCount() { return runoffCount; } public void setRunoffCount(Integer runoffCount) { this.runoffCount = runoffCount; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getUploadTime() { return uploadTime; } public void setUploadTime(Date uploadTime) { this.uploadTime = uploadTime; } public String getUploadPath() { return uploadPath; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public String getUploadFilename() { return uploadFilename; } public void setUploadFilename(String uploadFilename) { this.uploadFilename = uploadFilename; } public CrmCourseType getCourseType() { return courseType; } public void setCourseType(CrmCourseType courseType) { this.courseType = courseType; } }
apache-2.0
uralmax/jsonrpc4j-swagger-maven-plugin-helper
src/main/java/com/github/uralmax/JsonRpcSwaggerApiReader.java
17914
package com.github.uralmax; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.ArrayUtils; import org.apache.maven.plugin.logging.Log; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.MediaType; import com.github.kongchen.swagger.docgen.GenerateException; import com.github.kongchen.swagger.docgen.reader.AbstractReader; import com.github.kongchen.swagger.docgen.reader.ClassSwaggerReader; import com.github.kongchen.swagger.docgen.spring.SpringResource; import com.googlecode.jsonrpc4j.JsonRpcMethod; import com.googlecode.jsonrpc4j.JsonRpcParam; import com.googlecode.jsonrpc4j.JsonRpcService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Authorization; import io.swagger.annotations.AuthorizationScope; import io.swagger.converter.ModelConverters; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.RefModel; import io.swagger.models.Response; import io.swagger.models.SecurityRequirement; import io.swagger.models.Swagger; import io.swagger.models.Tag; import io.swagger.models.parameters.BodyParameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; /** * Reader for json-rpc * * @author Rozhkov Maksim */ public class JsonRpcSwaggerApiReader extends AbstractReader implements ClassSwaggerReader { public static final String SEPARATOR = "_"; private static final String JsonRPC_WRAPPER_NAME_FORMAT = "JsonRPC %s"; private static final String JsonRPC_PARAMS_NAME_FORMAT = "JsonRPC %s Params(%s)"; private String resourcePath; private String modifiedResourcePath; /** * Content type is constant */ private String[] CONTENT_TYPE = ArrayUtils.toArray(MediaType.APPLICATION_JSON_VALUE); public JsonRpcSwaggerApiReader(Swagger swagger, Log log) { super(swagger, log); } public Swagger read(Set<Class<?>> classes) throws GenerateException { Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>(); for (Class<?> aClass : classes) { resourceMap = analyzeController(aClass, resourceMap, ""); } if (swagger == null) { swagger = new Swagger(); } for (String str : resourceMap.keySet()) { SpringResource resource = resourceMap.get(str); read(resource); } return swagger; } /** * Read resource and fill swagger info * * @param resource * -resource * @return swagger main object */ public Swagger read(SpringResource resource) { List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); Class<?> controller = resource.getControllerClass(); if (controller.isAnnotationPresent(Api.class)) { Api api = AnnotationUtils.findAnnotation(controller, Api.class); if (!canReadApi(false, api)) { return swagger; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); } resourcePath = resource.getControllerMapping(); modifiedResourcePath = resourcePath.replace("/", SEPARATOR); Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods); for (String path : apiMethodMap.keySet()) { for (Method method : apiMethodMap.get(path)) { ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); if (apiOperation == null || apiOperation.hidden()) { continue; } Map<String, String> regexMap = new HashMap<String, String>(); Operation operation = parseMethod(apiOperation, method); updateOperationProtocols(apiOperation, operation); updateTagsForOperation(operation, apiOperation); updateOperation(CONTENT_TYPE, CONTENT_TYPE, tags, resourceSecurities, operation); swagger.path(parseOperationPath(path, regexMap), new Path().post(operation)); } } return swagger; } /** * Get real body param for json rpc * * @param allParams * all find params * @param apiOperation * - swagger annotation fo operation * @param methodName * metho * @return real body for request */ private BodyParameter getBobyParam(List<Property> allParams, ApiOperation apiOperation, String methodName) { String jsonRpcPath = modifiedResourcePath + SEPARATOR + methodName; BodyParameter requestBody = null; if (!allParams.isEmpty()) { ModelImpl jsonRpcModel = new ModelImpl(); jsonRpcModel.setType("object"); Map<String, Property> properties = new HashMap<String, Property>(); if (allParams.size() > 0) { jsonRpcModel.setDescription(apiOperation.value()); ModelImpl paramsWrapperModel = new ModelImpl(); paramsWrapperModel.setType(ModelImpl.OBJECT); String paramNames = ""; for (Property paramProperty : allParams) { paramNames = paramNames + " " + paramProperty.getName(); paramsWrapperModel.addProperty(paramProperty.getName(), paramProperty); } String wrapperOfParamsKey = String.format(JsonRPC_PARAMS_NAME_FORMAT, jsonRpcPath, paramNames); swagger.addDefinition(wrapperOfParamsKey, paramsWrapperModel); properties.put("params", new RefProperty(wrapperOfParamsKey)); } properties.put("jsonrpc", new StringProperty()._enum("2.0").example("2.0").required(true)); properties.put("id", new StringProperty().example("101").required(true)); properties.put("method", new StringProperty()._enum(methodName).example(methodName).required(true)); jsonRpcModel.setProperties(properties); String key = String.format(JsonRPC_WRAPPER_NAME_FORMAT, jsonRpcPath); swagger.addDefinition(key, jsonRpcModel); requestBody = new BodyParameter(); requestBody.setRequired(true); requestBody.setDescription(jsonRpcModel.getDescription()); requestBody.setName("body"); requestBody.setSchema(new RefModel(key)); } return requestBody; } /** * Response wrapper for list type * * @param type * -type * @param property * - swagger property * @return wrapped response */ private Property withResponseContainer(String type, Property property) { if ("list".equalsIgnoreCase(type)) { return new ArrayProperty(property); } if ("set".equalsIgnoreCase(type)) { return new ArrayProperty(property).uniqueItems(); } if ("map".equalsIgnoreCase(type)) { return new MapProperty(property); } return property; } /** * Get swagger operation from method * * @param apiOperation * - swagger operation * @param method * method * @return swagger Operation object */ private Operation parseMethod(ApiOperation apiOperation, Method method) { Operation operation = new Operation(); Type responseClass = null; String responseContainer = null; String operationId = method.getDeclaringClass().getSimpleName() + SEPARATOR + method.getName(); if (apiOperation.hidden()) { return null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } Map<String, Property> defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); Set<Map<String, Object>> customExtensions = parseCustomExtensions(apiOperation.extensions()); for (Map<String, Object> extension : customExtensions) { if (extension == null) { continue; } for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension( map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } if (!apiOperation.response().equals(Void.class)) { responseClass = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } if (responseClass == null) { responseClass = method.getGenericReturnType(); } if (responseClass != null && !responseClass.equals(Void.class)) { if (isPrimitive(responseClass)) { Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { Property responseProperty = withResponseContainer(responseContainer, property); operation.response(apiOperation.code(), new Response().description("") .schema(responseProperty).headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !responseClass.equals(void.class)) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.isEmpty()) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response(apiOperation.code(), new Response().description("") .schema(pp).headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = withResponseContainer(responseContainer, new RefProperty().asDefault(key)); operation.response(apiOperation.code(), new Response().description("") .schema(responseProperty).headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } } Map<String, Model> models = ModelConverters.getInstance().readAll(responseClass); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } operation.operationId(operationId); ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } Deprecated annotation = AnnotationUtils.findAnnotation(method, Deprecated.class); if (annotation != null) { operation.deprecated(true); } Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); List<Property> allParams = new ArrayList<Property>(); for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); if (!getTypesToSkip().contains(type)) { final Property property = ModelConverters.getInstance().readAsProperty(type); if (property != null) { for (Map.Entry<String, Model> entry : ModelConverters.getInstance() .readAll(type).entrySet()) { swagger.addDefinition(entry.getKey(), entry.getValue()); } } if (property != null) { String name = "unknow"; for (Annotation paramAnnotation : annotations) { if (paramAnnotation instanceof JsonRpcParam) { name = ((JsonRpcParam) paramAnnotation).value(); break; } else if (paramAnnotation instanceof ApiParam) { ApiParam apiParamAnnotation = ((ApiParam) paramAnnotation); name = apiParamAnnotation.name(); if (name != null && name.length() > 0) { break; } property.setDescription(apiParamAnnotation.value()); property.setExample(apiParamAnnotation.example()); } } property.setName(name); allParams.add(property); } } } JsonRpcMethod jsonRpcMethod = AnnotationUtils.findAnnotation(method, JsonRpcMethod.class); BodyParameter bobyParam = getBobyParam(allParams, apiOperation, jsonRpcMethod.value()); if (bobyParam != null) { operation.parameter(bobyParam); } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("Success")); } return operation; } /** * Get map of url and methods * * @param methods * analized methods * @return map url-> Methods */ private Map<String, List<Method>> collectApisByRequestMapping(List<Method> methods) { Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); for (Method method : methods) { if (method.isAnnotationPresent(JsonRpcMethod.class)) { JsonRpcMethod jsonRpcMethod = AnnotationUtils.findAnnotation(method, JsonRpcMethod.class); // It is necessary to modify as few methods able to live on the same url in swagger String path = resourcePath + " " + jsonRpcMethod.value(); if (apiMethodMap.containsKey(path)) { apiMethodMap.get(path).add(method); } else { List<Method> ms = new ArrayList<Method>(); ms.add(method); apiMethodMap.put(path, ms); } } } return apiMethodMap; } /** * Analyze controller and search resource * * @param controllerClazz * class * @param resourceMap * map of result * @param description * description * @return return result map */ private Map<String, SpringResource> analyzeController(Class<?> controllerClazz, Map<String, SpringResource> resourceMap, String description) { JsonRpcService serviceAnnotation = AnnotationUtils.findAnnotation(controllerClazz, JsonRpcService.class); if (serviceAnnotation != null) { String requestUrl = serviceAnnotation.value(); for (Method method : controllerClazz.getMethods()) { JsonRpcMethod jsonRpcMethod = AnnotationUtils.findAnnotation(method, JsonRpcMethod.class); if (jsonRpcMethod != null) { // It is necessary to modify as few methods able to live on the same url in // swagger String resourceKey = controllerClazz.getCanonicalName() + requestUrl + ' ' + jsonRpcMethod.value(); if (!resourceMap.containsKey(resourceKey)) { SpringResource springResource = new SpringResource(controllerClazz, requestUrl, resourceKey, description); springResource.setControllerMapping(requestUrl); resourceMap.put(resourceKey, springResource); } resourceMap.get(resourceKey).addMethod(method); } } } return resourceMap; } }
apache-2.0
hnccfr/ccfrweb
basecore/src/com/hundsun/network/gates/wulin/biz/dao/ibatis/funds/CashTradeStatusDAOImpl.java
1048
/* */ package com.hundsun.network.gates.wulin.biz.dao.ibatis.funds; /* */ /* */ import com.hundsun.network.gates.luosi.common.base.BaseDAO; /* */ import com.hundsun.network.gates.wulin.biz.dao.funds.CashTradeStatusDAO; /* */ import com.hundsun.network.gates.wulin.biz.domain.funds.CashTradeStatus; /* */ import org.springframework.orm.ibatis.SqlMapClientTemplate; /* */ import org.springframework.stereotype.Repository; /* */ /* */ @Repository("cashTradeStatusDAO") /* */ public class CashTradeStatusDAOImpl extends BaseDAO /* */ implements CashTradeStatusDAO /* */ { /* */ public Long insertCashStatus(CashTradeStatus cts) /* */ { /* 15 */ return (Long)getSqlMapClientTemplate().insert("CashTradeStatus.insert", cts); /* */ } /* */ } /* Location: E:\__安装归档\linquan-20161112\deploy16\wulin\webroot\WEB-INF\classes\ * Qualified Name: com.hundsun.network.gates.wulin.biz.dao.ibatis.funds.CashTradeStatusDAOImpl * JD-Core Version: 0.6.0 */
apache-2.0
waka401/ZkTest
src/edu/bupt/cameras/CameraThread.java
2656
package edu.bupt.cameras; import java.io.BufferedInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Inet4Address; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class CameraThread extends Thread { private AxisCamera camera; private boolean stopflag=false; private int i = 0; private FileSystem fs =null; private OutputStream out=null; private Configuration conf=null; private FileStatus ft =null; public CameraThread(AxisCamera camera, int i) { this.camera = camera; conf=new Configuration(); this.setI(i); } public int getI() { return i; } public void setI(int i) { this.i = i; } public String getData(String filename, String hdfsfile) throws IOException { String data = ("camera_id:" + camera.getIP() + ";media_name:" + filename + ";media_type:" + getFileType(filename) + ";media_size:" + getFileSize(hdfsfile) + ";"); // System.out.println(data); return data; } public long getFileSize(String hdfsfile) throws IOException { fs = FileSystem.get(URI.create(hdfsfile), conf); ft= fs.getFileStatus(new Path(hdfsfile)); Long filesize = ft.getLen(); return filesize; } public String getFileType(String decodedfile) { String[] str; str = decodedfile.split("[.]"); int n = str.length; return str[n - 1]; } @Override public void run() { try { while (!stopflag) { String hostname=Inet4Address.getLocalHost().getHostName(); String filename = Util.makeFilename(camera.getIP(), this.getI(), "mjpeg"); String hdfsfile = Util.HDFS_PATH_HEADER +hostname+"/"+ filename; BufferedInputStream in = new BufferedInputStream(this.camera.getInputStream()); if (in != null) { System.out.println(hdfsfile + " transfer start "); fs= FileSystem.get(URI.create(hdfsfile), conf); out = fs.create(new Path(hdfsfile)); IOUtils.copyBytes(in, out, 4096, true); System.out.println(hdfsfile + " transfer over "); out.close(); } } } catch (IOException e) { if(Thread.currentThread().isInterrupted()){ stopflag=true; //如果中断设置线程停止 }else{ throw new RuntimeException(); } } } @Override public void interrupt() { try { //关闭流引起IO中断 this.camera.getInputStream().close(); if(fs!=null) fs.close(); if (out!=null) out.close(); } catch (IOException e) { e.printStackTrace(); } super.interrupt(); } }
apache-2.0
millecker/senti-storm
src/at/illecker/sentistorm/components/Tokenizer.java
2047
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.illecker.sentistorm.components; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import at.illecker.sentistorm.commons.Tweet; import at.illecker.sentistorm.commons.util.HtmlUtils; import at.illecker.sentistorm.commons.util.RegexUtils; import at.illecker.sentistorm.commons.util.UnicodeUtils; public class Tokenizer { public static List<List<String>> tokenizeTweets(List<Tweet> tweets) { List<List<String>> tokenizedTweets = new ArrayList<List<String>>(); for (Tweet tweet : tweets) { tokenizedTweets.add(tokenize(tweet.getText())); } return tokenizedTweets; } public static List<String> tokenize(String str) { // Step 1) Trim text str = str.trim(); // Step 2) Replace Unicode symbols \u0000 if (UnicodeUtils.containsUnicode(str)) { str = UnicodeUtils.replaceUnicodeSymbols(str); } // Step 3) Replace HTML symbols &#[0-9]; if (HtmlUtils.containsHtml(str)) { str = HtmlUtils.replaceHtmlSymbols(str); } // Step 4) Tokenize List<String> tokens = new ArrayList<String>(); Matcher m = RegexUtils.TOKENIZER_PATTERN.matcher(str); while (m.find()) { tokens.add(m.group()); } return tokens; } }
apache-2.0
pmuetschard/gwt-debug-panel
src/main/test/com/google/gwt/debugpanel/common/ExceptionDataTest.java
2121
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.gwt.debugpanel.common; /** * Tests the {@link ExceptionData}. */ public class ExceptionDataTest extends AbstractDebugPanelGwtTestCase { public void testConstructionAndGetters() { ExceptionData data = ExceptionData.create("type", "message", "trace", ExceptionData.create("causeType", "causeMessage", "causeTrace", null)); assertNotNull(data); assertEquals("type", data.getType()); assertEquals("message", data.getMessage()); assertEquals("trace", data.getTrace()); data = data.getCause(); assertNotNull(data); assertEquals("causeType", data.getType()); assertEquals("causeMessage", data.getMessage()); assertEquals("causeTrace", data.getTrace()); data = data.getCause(); assertNull(data); } public void testToStringWithUnknownValues() { assertEquals("<unknown type>", ExceptionData.create(null, null, null, null).toString()); } public void testToStringWithOnlyTypeAndMessage() { assertEquals("type: message", ExceptionData.create("type", "message", null, null).toString()); } public void testToStringWithTrace() { assertEquals("type: message\ntrace", ExceptionData.create("type", "message", "trace", null).toString()); } public void testToStringWithCause() { assertEquals("type: message\ntrace\nCaused by: causeType: causeMessage\ncauseTrace", ExceptionData.create("type", "message", "trace", ExceptionData.create("causeType", "causeMessage", "causeTrace", null)).toString()); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-clouddirectory/src/main/java/com/amazonaws/services/clouddirectory/model/DirectoryNotEnabledException.java
1257
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.clouddirectory.model; import javax.annotation.Generated; /** * <p> * Operations are only permitted on enabled directories. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DirectoryNotEnabledException extends com.amazonaws.services.clouddirectory.model.AmazonCloudDirectoryException { private static final long serialVersionUID = 1L; /** * Constructs a new DirectoryNotEnabledException with the specified error message. * * @param message * Describes the error encountered. */ public DirectoryNotEnabledException(String message) { super(message); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/QuietTime.java
8652
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.pinpoint.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Specifies the start and end times that define a time range when messages aren't sent to endpoints. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/QuietTime" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class QuietTime implements Serializable, Cloneable, StructuredPojo { /** * <p> * The specific time when quiet time ends. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> */ private String end; /** * <p> * The specific time when quiet time begins. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> */ private String start; /** * <p> * The specific time when quiet time ends. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> * * @param end * The specific time when quiet time ends. This value has to use 24-hour notation and be in HH:MM format, * where HH is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to * represent 2:30 AM, or 14:30 to represent 2:30 PM. */ public void setEnd(String end) { this.end = end; } /** * <p> * The specific time when quiet time ends. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> * * @return The specific time when quiet time ends. This value has to use 24-hour notation and be in HH:MM format, * where HH is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 * to represent 2:30 AM, or 14:30 to represent 2:30 PM. */ public String getEnd() { return this.end; } /** * <p> * The specific time when quiet time ends. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> * * @param end * The specific time when quiet time ends. This value has to use 24-hour notation and be in HH:MM format, * where HH is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to * represent 2:30 AM, or 14:30 to represent 2:30 PM. * @return Returns a reference to this object so that method calls can be chained together. */ public QuietTime withEnd(String end) { setEnd(end); return this; } /** * <p> * The specific time when quiet time begins. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> * * @param start * The specific time when quiet time begins. This value has to use 24-hour notation and be in HH:MM format, * where HH is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to * represent 2:30 AM, or 14:30 to represent 2:30 PM. */ public void setStart(String start) { this.start = start; } /** * <p> * The specific time when quiet time begins. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> * * @return The specific time when quiet time begins. This value has to use 24-hour notation and be in HH:MM format, * where HH is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 * to represent 2:30 AM, or 14:30 to represent 2:30 PM. */ public String getStart() { return this.start; } /** * <p> * The specific time when quiet time begins. This value has to use 24-hour notation and be in HH:MM format, where HH * is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to represent 2:30 * AM, or 14:30 to represent 2:30 PM. * </p> * * @param start * The specific time when quiet time begins. This value has to use 24-hour notation and be in HH:MM format, * where HH is the hour (with a leading zero, if applicable) and MM is the minutes. For example, use 02:30 to * represent 2:30 AM, or 14:30 to represent 2:30 PM. * @return Returns a reference to this object so that method calls can be chained together. */ public QuietTime withStart(String start) { setStart(start); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEnd() != null) sb.append("End: ").append(getEnd()).append(","); if (getStart() != null) sb.append("Start: ").append(getStart()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof QuietTime == false) return false; QuietTime other = (QuietTime) obj; if (other.getEnd() == null ^ this.getEnd() == null) return false; if (other.getEnd() != null && other.getEnd().equals(this.getEnd()) == false) return false; if (other.getStart() == null ^ this.getStart() == null) return false; if (other.getStart() != null && other.getStart().equals(this.getStart()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEnd() == null) ? 0 : getEnd().hashCode()); hashCode = prime * hashCode + ((getStart() == null) ? 0 : getStart().hashCode()); return hashCode; } @Override public QuietTime clone() { try { return (QuietTime) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.pinpoint.model.transform.QuietTimeMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
zjj7725/exam
app/src/main/java/me/zhujiajie/exam/ChatAdapter.java
2025
package me.zhujiajie.exam; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; public class ChatAdapter extends ArrayAdapter<Chat>{ private int resourceId; public ChatAdapter(Context context, int textViewResourceId, List<Chat> objects) { super(context, textViewResourceId, objects); resourceId = textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { Chat msg = getItem(position); View view; ViewHolder viewHolder; if (convertView == null){ view = LayoutInflater.from(getContext()).inflate(resourceId,null); viewHolder = new ViewHolder(); viewHolder.leftLayout = (LinearLayout) view.findViewById(R.id.left_layout); viewHolder.rightLayout = (LinearLayout) view.findViewById(R.id.right_layout); viewHolder.leftMsg = (TextView) view.findViewById(R.id.left_msg); viewHolder.rightMsg = (TextView) view.findViewById(R.id.right_msg); view.setTag(viewHolder); }else{ view = convertView; viewHolder = (ViewHolder) view.getTag(); } if (msg.getType() == Chat.TYPE_RECEIVED){ viewHolder.leftLayout.setVisibility(View.VISIBLE); viewHolder.rightLayout.setVisibility(View.GONE); viewHolder.leftMsg.setText(msg.getContent()); }else if(msg.getType() == Chat.TYPE_SENT){ viewHolder.rightLayout.setVisibility(View.VISIBLE); viewHolder.leftLayout.setVisibility(View.GONE); viewHolder.rightMsg.setText(msg.getContent()); } return view; } class ViewHolder { LinearLayout leftLayout; LinearLayout rightLayout; TextView leftMsg; TextView rightMsg; } }
apache-2.0
rafamanzo/SIGP
src/sigp/src/Disciplina.java
1980
package sigp.src; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import br.com.caelum.vraptor.Resource; @Entity @Resource @Table(name = "DISCIPLINA") public class Disciplina { @NotEmpty(message = "Discplina precisa ter uma sigla.") private String sigla; @NotEmpty(message = "Discplina precisa ter um nome.") private String nome; @NotEmpty(message = "Discplina precisa ter uma ementa.") private String ementa; private Long idDisciplina; @NotNull(message = "Discplina precisa ser oferecida por um grupo.") private Grupo grupo; @ManyToOne @JoinColumn(name = "GRUPO_ID", nullable = false) public Grupo getGrupo() { return grupo; } public void setGrupo(Grupo grupo) { this.grupo = grupo; } @Column(name = "DISCIPLINA_SIGLA", nullable = false, length = 15) public String getSigla() { return sigla; } public void setSigla(String sigla) { this.sigla = sigla; } @Column(name = "DISICPLINA_NOME", nullable = false, length = 255) public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @Column(name = "DISCIPLINA_EMENTA", nullable = false, length = 510) public String getEmenta() { return ementa; } public void setEmenta(String ementa) { this.ementa = ementa; } @Id @GeneratedValue @Column(name = "DISCIPLINA_ID") public Long getIdDisciplina() { return idDisciplina; } public void setIdDisciplina(Long idDisciplina) { this.idDisciplina = idDisciplina; } @Override public String toString() { return "Disciplina [sigla=" + sigla + ", nome=" + nome + ", ementa=" + ementa + ", idDisciplina=" + idDisciplina + ", grupos=" + "]"; } }
apache-2.0
ebridfighter/GongXianSheng
app/src/main/java/uk/co/ribot/androidboilerplate/view/swipmenu/SwipeMenu.java
888
package uk.co.ribot.androidboilerplate.view.swipmenu; import android.content.Context; import java.util.ArrayList; import java.util.List; /** * * @author baoyz * @date 2014-8-23 * */ public class SwipeMenu { private Context mContext; private List<SwipeMenuItem> mItems; private int mViewType; public SwipeMenu(Context context) { mContext = context; mItems = new ArrayList<SwipeMenuItem>(); } public Context getContext() { return mContext; } public void addMenuItem(SwipeMenuItem item) { mItems.add(item); } public void removeMenuItem(SwipeMenuItem item) { mItems.remove(item); } public List<SwipeMenuItem> getMenuItems() { return mItems; } public SwipeMenuItem getMenuItem(int index) { return mItems.get(index); } public int getViewType() { return mViewType; } public void setViewType(int viewType) { this.mViewType = viewType; } }
apache-2.0
gawkermedia/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/dfp/lib/client/DfpServiceClient.java
2767
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.lib.client; import com.google.api.ads.common.lib.client.AdsServiceClient; import com.google.api.ads.common.lib.client.HeaderHandler; import com.google.api.ads.common.lib.soap.SoapClientHandlerInterface; import com.google.api.ads.common.lib.soap.SoapServiceClient; import com.google.api.ads.common.lib.utils.logging.AdsServiceLoggers; import com.google.inject.assistedinject.Assisted; import javax.inject.Inject; /** * Wrapper of underlying SOAP client which allows access for setting * headers retrieved from the session. */ public class DfpServiceClient extends AdsServiceClient<DfpSession, DfpServiceDescriptor> { /** * Constructor. * * @param soapClient the SOAP client * @param dfpServiceDescriptor the DFP service descriptor * @param dfpSession the DFP session * @param soapClientHandler the SOAP client handler * @param dfpHeaderHandler the DFP header handler * @param adsServiceLoggers the ads service loggers */ @SuppressWarnings("unchecked") /* See comments on soapClientHandler argument. */ @Inject public DfpServiceClient( @Assisted("soapClient") Object soapClient, @Assisted("adsServiceDescriptor") DfpServiceDescriptor dfpServiceDescriptor, @Assisted("adsSession") DfpSession dfpSession, @SuppressWarnings("rawtypes") /* Guice binding for SoapClientHandlerInterface does not include * the type argument T because it is bound in the SOAP * toolkit-agnostic configuration module. Therefore, must use * the raw type here. */ SoapClientHandlerInterface soapClientHandler, HeaderHandler<DfpSession, DfpServiceDescriptor> dfpHeaderHandler, AdsServiceLoggers adsServiceLoggers) { super(soapClient, dfpSession, dfpServiceDescriptor, soapClientHandler, dfpHeaderHandler, adsServiceLoggers); } /** * @see SoapServiceClient#handleException */ @Override protected Throwable handleException(Throwable e) { return super.handleException(e); } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/resources/CustomerUserAccessOrBuilder.java
5138
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/resources/customer_user_access.proto package com.google.ads.googleads.v10.resources; public interface CustomerUserAccessOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.resources.CustomerUserAccess) com.google.protobuf.MessageOrBuilder { /** * <pre> * Immutable. Name of the resource. * Resource names have the form: * `customers/{customer_id}/customerUserAccesses/{user_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Immutable. Name of the resource. * Resource names have the form: * `customers/{customer_id}/customerUserAccesses/{user_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); /** * <pre> * Output only. User id of the user with the customer access. * Read only field * </pre> * * <code>int64 user_id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The userId. */ long getUserId(); /** * <pre> * Output only. Email address of the user. * Read only field * </pre> * * <code>optional string email_address = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the emailAddress field is set. */ boolean hasEmailAddress(); /** * <pre> * Output only. Email address of the user. * Read only field * </pre> * * <code>optional string email_address = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The emailAddress. */ java.lang.String getEmailAddress(); /** * <pre> * Output only. Email address of the user. * Read only field * </pre> * * <code>optional string email_address = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for emailAddress. */ com.google.protobuf.ByteString getEmailAddressBytes(); /** * <pre> * Access role of the user. * </pre> * * <code>.google.ads.googleads.v10.enums.AccessRoleEnum.AccessRole access_role = 4;</code> * @return The enum numeric value on the wire for accessRole. */ int getAccessRoleValue(); /** * <pre> * Access role of the user. * </pre> * * <code>.google.ads.googleads.v10.enums.AccessRoleEnum.AccessRole access_role = 4;</code> * @return The accessRole. */ com.google.ads.googleads.v10.enums.AccessRoleEnum.AccessRole getAccessRole(); /** * <pre> * Output only. The customer user access creation time. * Read only field * The format is "YYYY-MM-DD HH:MM:SS". * Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30" * </pre> * * <code>optional string access_creation_date_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the accessCreationDateTime field is set. */ boolean hasAccessCreationDateTime(); /** * <pre> * Output only. The customer user access creation time. * Read only field * The format is "YYYY-MM-DD HH:MM:SS". * Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30" * </pre> * * <code>optional string access_creation_date_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The accessCreationDateTime. */ java.lang.String getAccessCreationDateTime(); /** * <pre> * Output only. The customer user access creation time. * Read only field * The format is "YYYY-MM-DD HH:MM:SS". * Examples: "2018-03-05 09:15:00" or "2018-02-01 14:34:30" * </pre> * * <code>optional string access_creation_date_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for accessCreationDateTime. */ com.google.protobuf.ByteString getAccessCreationDateTimeBytes(); /** * <pre> * Output only. The email address of the inviter user. * Read only field * </pre> * * <code>optional string inviter_user_email_address = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the inviterUserEmailAddress field is set. */ boolean hasInviterUserEmailAddress(); /** * <pre> * Output only. The email address of the inviter user. * Read only field * </pre> * * <code>optional string inviter_user_email_address = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The inviterUserEmailAddress. */ java.lang.String getInviterUserEmailAddress(); /** * <pre> * Output only. The email address of the inviter user. * Read only field * </pre> * * <code>optional string inviter_user_email_address = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for inviterUserEmailAddress. */ com.google.protobuf.ByteString getInviterUserEmailAddressBytes(); }
apache-2.0
afelisatti/async-http-client
providers/netty4/src/main/java/org/asynchttpclient/providers/netty4/response/LazyNettyResponseBodyPart.java
2231
/* * Copyright (c) 2014 AsyncHttpClient Project. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient.providers.netty4.response; import io.netty.buffer.ByteBuf; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; /** * A callback class used when an HTTP response body is received. */ public class LazyNettyResponseBodyPart extends NettyResponseBodyPart { private static final String ERROR_MESSAGE = "This implementation is intended for one to directly read from the underlying ByteBuf and release after usage. Not for the fainted heart!"; private final ByteBuf buf; public LazyNettyResponseBodyPart(ByteBuf buf, boolean last) { super(last); this.buf = buf; } public ByteBuf getBuf() { return buf; } /** * Return the response body's part bytes received. * * @return the response body's part bytes received. */ @Override public byte[] getBodyPartBytes() { throw new UnsupportedOperationException(ERROR_MESSAGE); } @Override public InputStream readBodyPartBytes() { throw new UnsupportedOperationException(ERROR_MESSAGE); } @Override public int length() { throw new UnsupportedOperationException(ERROR_MESSAGE); } @Override public int writeTo(OutputStream outputStream) throws IOException { throw new UnsupportedOperationException(ERROR_MESSAGE); } @Override public ByteBuffer getBodyByteBuffer() { throw new UnsupportedOperationException(ERROR_MESSAGE); } }
apache-2.0
santanusinha/dropwizard-db-sharding-bundle
src/main/java/io/appform/dropwizard/sharding/caching/LookupCache.java
1881
/* * Copyright 2016 Santanu Sinha <santanu.sinha@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.appform.dropwizard.sharding.caching; import io.appform.dropwizard.sharding.dao.CacheableLookupDao; /** * A simple cache interface which allows plugging in any caching framework or infrastructure to enable * write through caching */ public interface LookupCache<V> { /** * Write through method that will be called if cache enabled {@link io.appform.dropwizard.sharding.dao.CacheableLookupDao#save(Object)} is used * @param key The key that needs to be used to write this element to cache * @param entity Entity that needs to be written into cache */ void put(String key, V entity); /** * Read through exists method that will be called if cache enabled {@link io.appform.dropwizard.sharding.dao.CacheableLookupDao#exists(String)} is used * @param key The key of the entity that needs to be checked * @return whether the entity exists or not. */ boolean exists(String key); /** * Read through method that will be called if a cache enabled {@link io.appform.dropwizard.sharding.dao.CacheableLookupDao#get(String)} is used * @param key The key of the entity that needs to be read * @return entity Entity that was read through the cache */ V get(String key); }
apache-2.0
robgil/Aleph2-contrib
aleph2_analytic_services_hadoop/src/test/java/com/ikanow/aleph2/analytics/hadoop/data_model/BasicHadoopConfigBean.java
5584
/******************************************************************************* * Copyright 2015, The IKANOW Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.ikanow.aleph2.analytics.hadoop.data_model; import java.util.Collections; import java.util.List; import java.util.Map; /** Defines a fairly generic Hadoop job - other beans will contain more complex functionality * CURRENTLY ON ICE WHILE I GET THE SIMPLER ENRICHMENT MODULE BASED SERVICE WORKING * @author alex */ public class BasicHadoopConfigBean { // Some Hadoop configuration fields public final static String CONTEXT_SIGNATURE = "aleph2.job.context_signature"; public final static String CONFIG_STRING_MAPPER = "aleph2.mapper.config_string"; public final static String CONFIG_JSON_MAPPER = "aleph2.mapper.config_json"; public final static String CONFIG_STRING_COMBINER = "aleph2.combiner.config_string"; public final static String CONFIG_JSON_COMBINER = "aleph2.combiner.config_json"; public final static String CONFIG_STRING_REDUCER = "aleph2.reducer.config_string"; public final static String CONFIG_JSON_REDUCER = "aleph2.reducer.config_json"; /** An individual step in the processing chain * @author alex */ public class Step { /** Whether this step is enabled (defaults to true) - note disabling a step might cause the pipeline to fail * if the types then don't match) * @return */ public Boolean enabled() { return enabled; } /** The class of the mapper/combiner/reducer * @return */ public String entry_point() { return entry_point; } /** A string that is available to the mapper/combiner/reducer from the Configuration (get(CONFIG_STRING)) * @return */ public String config_string() { return config_string; } /** A JSON object that is available to the mapper/combiner/reducer in String form from the Configuration (get(CONFIG_JSON)) * @return */ public Map<String, Object> config_json() { return config_json == null ? config_json : Collections.unmodifiableMap(config_json); } /** A map of strings that is copied directly into the Hadoop configuration object propery by property (unlike the others which are each one field) * @return */ public Map<String, String> internal_config() { return internal_config == null ? internal_config : Collections.unmodifiableMap(internal_config); } /** Ignored except for reducers, sets a target number of reducers to use (Default: 1) * @return */ public Long num_tasks() { return num_tasks; } /** Optional, overrides the class of the output key type (defaults to String) * (Obviously needs to match both the output class implementation specified by entry point, and the input * class implementation specified by the next stage) * Other notes: * - It is recommended to use fully qualified class names, though they will be inferred where possible * - Some attempt will be made to convert between types (eg Text <-> JsonNodeWritable <-> MapWritable) * @return */ public String output_key_type() { return output_key_type; } /** Optional, overrides the class of the output value type (defaults to String) * (Obviously needs to match both the output class implementation specified by entry point, and the input * class implementation specified by the next stage) * Other notes: * - It is recommended to use fully qualified class names, though they will be inferred where possible * - Some attempt will be made to convert between types (eg Text <-> JsonNodeWritable <-> MapWritable) * @return */ public String output_value_type() { return output_value_type; } private Boolean enabled; private String config_string; private Map<String, Object> config_json; private Map<String, String> internal_config; private String entry_point; private Long num_tasks; private String output_key_type; private String output_value_type; } /** A list of mappers to run in a pipeline. Must be non-empty * @return */ public List<Step> mappers() { return mappers; } /** The combiner to apply in between the last mapper and then the reducer * Optional - if left blank then no combiner is generated, if an (empty object ({}), ie Step.entry_point is null * then the reducer is used as the combiner * @return */ public Step combiner() { return combiner; } /** The reducer to run. If not specified/disabled then no reduction stage are run (the combiner must also * be not-present/disabled in this case) * @return */ public Step reducer() { return reducer; } /** Optional, Mappers to run after the reducer - if the reducer is not run then these finalizers are appended * to the original mappers * @return */ public List<Step> finalizers() { return finalizers; } private List<Step> mappers; private Step combiner; private Step reducer; private List<Step> finalizers; //TODO (ALEPH-12): Also have a map of data service -> type conversion mapper }
apache-2.0
allotria/intellij-community
plugins/yaml/src/org/jetbrains/yaml/YAMLElementGenerator.java
4641
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.yaml; import com.intellij.lang.ASTNode; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.TokenType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.LocalTimeCounter; import org.jetbrains.annotations.NotNull; import org.jetbrains.yaml.psi.*; import org.jetbrains.yaml.psi.impl.YAMLQuotedTextImpl; import java.util.Collection; import java.util.List; public class YAMLElementGenerator { private final Project myProject; public YAMLElementGenerator(Project project) { myProject = project; } public static YAMLElementGenerator getInstance(Project project) { return ServiceManager.getService(project, YAMLElementGenerator.class); } @NotNull public static String createChainedKey(@NotNull List<String> keyComponents, int indentAddition) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < keyComponents.size(); ++i) { if (i > 0) { sb.append(StringUtil.repeatSymbol(' ', indentAddition + 2 * i)); } sb.append(keyComponents.get(i)).append(":"); if (i + 1 < keyComponents.size()) { sb.append('\n'); } } return sb.toString(); } @NotNull public YAMLKeyValue createYamlKeyValue(@NotNull String keyName, @NotNull String valueText) { final PsiFile tempValueFile = createDummyYamlWithText(valueText); Collection<YAMLValue> values = PsiTreeUtil.collectElementsOfType(tempValueFile, YAMLValue.class); String text; if (!values.isEmpty() && values.iterator().next() instanceof YAMLScalar && !valueText.contains("\n")) { text = keyName + ": " + valueText; } else { text = keyName + ":\n" + YAMLTextUtil.indentText(valueText, 2); } final PsiFile tempFile = createDummyYamlWithText(text); return PsiTreeUtil.collectElementsOfType(tempFile, YAMLKeyValue.class).iterator().next(); } @NotNull public YAMLQuotedTextImpl createYamlDoubleQuotedString() { final YAMLFile tempFile = createDummyYamlWithText("\"foo\""); return PsiTreeUtil.collectElementsOfType(tempFile, YAMLQuotedTextImpl.class).iterator().next(); } @NotNull public YAMLFile createDummyYamlWithText(@NotNull String text) { return (YAMLFile) PsiFileFactory.getInstance(myProject) .createFileFromText("temp." + YAMLFileType.YML.getDefaultExtension(), YAMLFileType.YML, text, LocalTimeCounter.currentTime(), true); } @NotNull public PsiElement createEol() { final YAMLFile file = createDummyYamlWithText("\n"); return PsiTreeUtil.getDeepestFirst(file); } @NotNull public PsiElement createSpace() { final YAMLKeyValue keyValue = createYamlKeyValue("foo", "bar"); final ASTNode whitespaceNode = keyValue.getNode().findChildByType(TokenType.WHITE_SPACE); assert whitespaceNode != null; return whitespaceNode.getPsi(); } @NotNull public PsiElement createIndent(int size) { final YAMLFile file = createDummyYamlWithText(StringUtil.repeatSymbol(' ', size)); return PsiTreeUtil.getDeepestFirst(file); } @NotNull public PsiElement createColon() { final YAMLFile file = createDummyYamlWithText("? foo : bar"); final PsiElement at = file.findElementAt("? foo ".length()); assert at != null && at.getNode().getElementType() == YAMLTokenTypes.COLON; return at; } @NotNull public PsiElement createDocumentMarker() { final YAMLFile file = createDummyYamlWithText("---"); PsiElement at = file.findElementAt(0); assert at != null && at.getNode().getElementType() == YAMLTokenTypes.DOCUMENT_MARKER; return at; } @NotNull public YAMLSequence createEmptySequence() { YAMLSequence sequence = PsiTreeUtil.findChildOfType(createDummyYamlWithText("- dummy"), YAMLSequence.class); assert sequence != null; sequence.deleteChildRange(sequence.getFirstChild(), sequence.getLastChild()); return sequence; } @NotNull public YAMLSequenceItem createEmptySequenceItem() { YAMLSequenceItem sequenceItem = PsiTreeUtil.findChildOfType(createDummyYamlWithText("- dummy"), YAMLSequenceItem.class); assert sequenceItem != null; YAMLValue value = sequenceItem.getValue(); assert value != null; value.deleteChildRange(value.getFirstChild(), value.getLastChild()); return sequenceItem; } }
apache-2.0
olacabs/fabric
fabric-compute-framework/src/test/java/com/olacabs/fabric/compute/pipelined/CountingProcessor.java
3177
/* * Copyright 2016 ANI Technologies Pvt. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.olacabs.fabric.compute.pipelined; import com.google.common.collect.Maps; import com.olacabs.fabric.compute.ProcessingContext; import com.olacabs.fabric.compute.processor.InitializationException; import com.olacabs.fabric.compute.processor.ProcessingException; import com.olacabs.fabric.compute.processor.ScheduledProcessor; import com.olacabs.fabric.model.common.ComponentMetadata; import com.olacabs.fabric.model.common.PropertyConstraint; import com.olacabs.fabric.model.event.Event; import com.olacabs.fabric.model.event.EventSet; import java.util.*; import java.util.stream.Collectors; /** * TODO doc. */ public class CountingProcessor extends ScheduledProcessor { private Map<String, Long> counts = Maps.newHashMap(); @Override protected void consume(ProcessingContext context, EventSet eventSet) throws ProcessingException { eventSet.getEvents().forEach(event -> { TestEvent testEvent = (TestEvent) event; if (!counts.containsKey(testEvent.getMarker())) { counts.put(testEvent.getMarker(), 0L); } try { counts.put(testEvent.getMarker(), counts.get(testEvent.getMarker()) + 1); } catch (Exception e) { e.printStackTrace(); } }); } @Override public void initialize(String instanceId, Properties globalProperties, Properties initializationProperties, ComponentMetadata componentMetadata) throws InitializationException { } @Override public List<Event> timeTriggerHandler(ProcessingContext context) throws ProcessingException { ArrayList<Event> flattenedEvent = counts.entrySet() .stream() .map(stringLongEntry -> Event.builder().data(stringLongEntry).build()) .collect(Collectors.toCollection(ArrayList<Event>::new)); counts = Maps.newHashMap(); return flattenedEvent; } @Override public void destroy() { } // sample only, not used anywhere @Override public List<PropertyConstraint> getPropertyConstraints() { return Collections.singletonList(PropertyConstraint.builder().property("to").dependencyConstraints(Collections .singletonList(PropertyConstraint.DependencyConstraint.builder().property("from") .operator(PropertyConstraint.Operator.GEQ).value("0").build())) .valueConstraint(PropertyConstraint.ValueConstraint.builder().defaultValue("100").build()).build()); } }
apache-2.0
omengye/ws
gcs/src/main/java/io/omengye/gcs/feign/UserInfoService.java
603
package io.omengye.gcs.feign; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import io.omengye.gcs.feign.impl.UserInfoServiceFallbackFactory; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Map; @FeignClient(value="WS-USERINFO", fallbackFactory = UserInfoServiceFallbackFactory.class) public interface UserInfoService { @GetMapping("/visit") Map<String, Boolean> addVisitCount(@RequestParam("userIp") String userIp); }
apache-2.0
sfat/spring-cloud-netflix
spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/EnableZuulProxy.java
1513
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.zuul; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.context.annotation.Import; /** * Sets up a Zuul server endpoint and installs some reverse proxy filters in it, so it can * forward requests to backend servers. The backends can be registered manually through * configuration or via DiscoveryClient. * * @see EnableZuulServer for how to get a Zuul server without any proxying * * @author Spencer Gibb * @author Dave Syer * @author Biju Kunjummen */ @EnableCircuitBreaker @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(ZuulProxyMarkerConfiguration.class) public @interface EnableZuulProxy { }
apache-2.0
CodeSTD/spring-cxf-annotation-support
src/test/java/com/codestd/spring/cxf/ws/HelloServiceImpl.java
1097
/* * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codestd.spring.cxf.ws; import javax.jws.WebService; import com.codestd.spring.cxf.annotation.Endpoint; /** * @author jaune(Wang Chengwei) * @since 1.0.0 */ @Endpoint(address="HelloService", id = "HelloServiceEndpoint") @WebService(endpointInterface="com.codestd.spring.cxf.ws.HelloService") public class HelloServiceImpl implements HelloService{ @Override public String syHi(String name) { return "Hello "+name; } }
apache-2.0
wangdao/x-worker
src/main/java/me/emou/xworker/controller/FileController.java
1584
package me.emou.xworker.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * @author wangdao */ @RestController public class FileController { @RequestMapping("downloader") public void download(String fileName, HttpServletResponse response) throws IOException { String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); path = path + "tmp/"; File file = new File(path + fileName); InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名 response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1")); response.addHeader("Content-Length", "" + file.length()); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Origin", "*"); OutputStream os = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); os.write(buffer);// 输出文件 os.flush(); os.close(); } }
apache-2.0
codehaus-plexus/plexus-archiver
src/main/java/org/codehaus/plexus/archiver/zip/ZipUnArchiver.java
950
/** * * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.plexus.archiver.zip; import java.io.File; /** * @author <a href="mailto:evenisse@codehaus.org">Emmanuel Venisse</a> */ public class ZipUnArchiver extends AbstractZipUnArchiver { public ZipUnArchiver() { } public ZipUnArchiver( File sourceFile ) { super( sourceFile ); } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202102/UnarchiveOrders.java
1471
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202102; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * The action used for unarchiving {@link Order} objects. * * * <p>Java class for UnarchiveOrders complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="UnarchiveOrders"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v202102}OrderAction"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "UnarchiveOrders") public class UnarchiveOrders extends OrderAction { }
apache-2.0
warnerbros/cpe-manifest-android-experience
src/com/wb/nextgenlibrary/parser/md/schema/v2_3/DigitalAssetCardsetType.java
3755
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.02.08 at 03:02:05 PM PST // package com.wb.nextgenlibrary.parser.md.schema.v2_3; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import com.wb.nextgenlibrary.parser.XmlAccessType; import com.wb.nextgenlibrary.parser.XmlAccessorType; import com.wb.nextgenlibrary.parser.XmlElement; import com.wb.nextgenlibrary.parser.XmlSchemaType; import com.wb.nextgenlibrary.parser.XmlType; /** * <p>Java class for DigitalAssetCardset-type complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DigitalAssetCardset-type"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Type" type="{http://www.movielabs.com/schema/md/v2.3/md}string-Cardset-Type" maxOccurs="unbounded"/&gt; * &lt;element name="Description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="Sequence" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DigitalAssetCardset-type", propOrder = { "type", "description", "sequence" }) public class DigitalAssetCardsetType { @XmlElement(name = "Type", required = true) protected List<String> type; @XmlElement(name = "Description") protected String description; @XmlElement(name = "Sequence") @XmlSchemaType(name = "positiveInteger") protected BigInteger sequence; /** * Gets the value of the type property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the type property. * * <p> * For example, to add a new item, do as follows: * <pre> * getType().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getType() { if (type == null) { type = new ArrayList<String>(); } return this.type; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the sequence property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getSequence() { return sequence; } /** * Sets the value of the sequence property. * * @param value * allowed object is * {@link BigInteger } * */ public void setSequence(BigInteger value) { this.sequence = value; } }
apache-2.0
bbilger/jrestless
aws/gateway/jrestless-aws-gateway-handler/src/test/java/com/jrestless/aws/gateway/security/AuthorizerFilterTest.java
3222
package com.jrestless.aws.gateway.security; public abstract class AuthorizerFilterTest { // abstract AuthorizerFilter createCognitoAuthorizerFilter(GatewayRequest gatewayRequest); // // protected final GatewayRequest createRequest(Map<String, Object> authorizerData) { // GatewayRequestContext gatewayRequestContext = mock(GatewayRequestContext.class); // when(gatewayRequestContext.getAuthorizer()).thenReturn(authorizerData); // // GatewayRequest gatewayRequest = mock(GatewayRequest.class); // when(gatewayRequest.getRequestContext()).thenReturn(gatewayRequestContext); // // return gatewayRequest; // } // // @Test // public void noGatewayRequestContextSet_ShouldNotSetSecurityContext() { // GatewayRequest gatewayRequest = mock(GatewayRequest.class); // filterAndVerifyNoSecurityContextSet(gatewayRequest); // } // // @Test // public void noAuthorizerDataSet_ShouldNotSetSecurityContext() { // GatewayRequestContext gatewayRequestContext = mock(GatewayRequestContext.class); // when(gatewayRequestContext.getAuthorizer()).thenReturn(null); // // GatewayRequest gatewayRequest = mock(GatewayRequest.class); // when(gatewayRequest.getRequestContext()).thenReturn(gatewayRequestContext); // // filterAndVerifyNoSecurityContextSet(gatewayRequest); // } // // @Test // public void emptyAuthorizerDataSet_ShouldNotSetSecurityContext() { // GatewayRequestContext gatewayRequestContext = mock(GatewayRequestContext.class); // when(gatewayRequestContext.getAuthorizer()).thenReturn(Collections.emptyMap()); // // GatewayRequest gatewayRequest = mock(GatewayRequest.class); // when(gatewayRequest.getRequestContext()).thenReturn(gatewayRequestContext); // // filterAndVerifyNoSecurityContextSet(gatewayRequest); // } // // protected final SecurityContext filterAndReturnSetSecurityContext(Map<String, Object> authorizerData) { // return filterAndReturnSetSecurityContext(createRequest(authorizerData)); // } // // protected final SecurityContext filterAndReturnSetSecurityContext(GatewayRequest gatewayRequest) { // ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class); // AuthorizerFilter filter = createCognitoAuthorizerFilter(gatewayRequest); // ArgumentCaptor<SecurityContext> securityContextCapture = ArgumentCaptor.forClass(SecurityContext.class); // try { // filter.filter(containerRequestContext); // } catch (IOException e) { // throw new RuntimeException(e); // } // verify(containerRequestContext).setSecurityContext(securityContextCapture.capture()); // return securityContextCapture.getValue(); // } // // protected final void filterAndVerifyNoSecurityContextSet(Map<String, Object> authorizerData) { // filterAndVerifyNoSecurityContextSet(createRequest(authorizerData)); // } // // protected final void filterAndVerifyNoSecurityContextSet(GatewayRequest gatewayRequest) { // ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class); // AuthorizerFilter filter = createCognitoAuthorizerFilter(gatewayRequest); // try { // filter.filter(containerRequestContext); // } catch (IOException e) { // throw new RuntimeException(e); // } // verify(containerRequestContext, times(0)).setSecurityContext(any()); // } }
apache-2.0
joshiste/spring-cloud-netflix
spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/ApplicationContextTests.java
4137
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.eureka.server; import java.util.Collections; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.netflix.eureka.server.ApplicationContextTests.Application; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.application.name=eureka", "server.servlet.context-path=/context", "management.security.enabled=false", "management.endpoints.web.exposure.include=*" }) public class ApplicationContextTests { private static final String BASE_PATH = new WebEndpointProperties().getBasePath(); @LocalServerPort private int port = 0; @Test public void catalogLoads() { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/apps", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void dashboardLoads() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); String body = entity.getBody(); // System.err.println(body); assertThat(body.contains("eureka/js")).isTrue(); assertThat(body.contains("eureka/css")).isTrue(); // The "DS Replicas" assertThat( body.contains("<a href=\"http://localhost:8761/eureka/\">localhost</a>")) .isTrue(); } @Test public void cssAvailable() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/css/wro.css", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void jsAvailable() { ResponseEntity<String> entity = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/context/eureka/js/wro.js", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void adminLoads() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/context" + BASE_PATH + "/env", HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Configuration @EnableAutoConfiguration @EnableEurekaServer protected static class Application { } }
apache-2.0
nasser-munshi/Android
FTFLNavigationDrawer/src/com/ftfl/ftflnavigationdrawer/MainActivity.java
6040
package com.ftfl.ftflnavigationdrawer; import android.app.Fragment; import android.app.FragmentManager; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.ftfl.ftflnavigationdrawer.fragment.GeneralFragment; import com.ftfl.ftflnavigationdrawer.fragment.GrowthFragment; import com.ftfl.ftflnavigationdrawer.fragment.VaccinationFragment; public class MainActivity extends ActionBarActivity { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private String[] mDrawarMenus; Fragment fragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitle = mDrawerTitle = getTitle(); mDrawarMenus =getResources().getStringArray(R.array.drawer_menu_array); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.item_drawer_list, mDrawarMenus)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // enable ActionBar app icon to behave as action to toggle nav drawer // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(R.id.action_settings).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action buttons switch(item.getItemId()) { case R.id.action_settings: return true; default: return super.onOptionsItemSelected(item); } } /* The click listner for ListView in the navigation drawer */ private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } private void selectItem(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getFragmentManager(); switch (position) { case 0: fragment = new GeneralFragment(); break; case 1: fragment = new VaccinationFragment(); break; case 2: fragment = new GrowthFragment(); break; default: break; } fragmentManager.beginTransaction().replace(R.id.container, fragment).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); setTitle(mDrawarMenus[position]); mDrawerLayout.closeDrawer(mDrawerList); } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } }
apache-2.0
SEEG-Oxford/ABRAID-MP
src/Common/test/uk/ac/ox/zoo/seeg/abraid/mp/common/service/workflow/support/runrequest/data/ExtentDataWriterTest.java
5132
package uk.ac.ox.zoo.seeg.abraid.mp.common.service.workflow.support.runrequest.data; import org.apache.commons.io.FileUtils; import org.geotools.coverage.grid.io.GridCoverage2DReader; import org.geotools.factory.Hints; import org.geotools.gce.geotiff.GeoTiffReader; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.AdminUnitDiseaseExtentClass; import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.AdminUnitGlobalOrTropical; import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.DiseaseExtentClass; import java.awt.image.Raster; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.*; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests for ExtentDataWriter. * Copyright (c) 2014 University of Oxford */ public class ExtentDataWriterTest { public static final String SMALL_RASTER = "Common/test/uk/ac/ox/zoo/seeg/abraid/mp/common/service/workflow/support/runrequest/data/testdata/SmallRaster.tif"; public static final String SMALL_RASTER_TRANSFORMED = "Common/test/uk/ac/ox/zoo/seeg/abraid/mp/common/service/workflow/support/runrequest/data/testdata/SmallRaster_transformed.tif"; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); ///CHECKSTYLE:SUPPRESS VisibilityModifier @Test public void writeShouldProduceCorrectOutputAndSetAnyUnknownValuesToNoData() throws Exception { // Arrange File sourceRaster = new File(SMALL_RASTER); File result = Paths.get(testFolder.newFolder().toString(), "foo.tif").toFile(); ExtentDataWriter target = new ExtentDataWriterImpl(); Collection<AdminUnitDiseaseExtentClass> extent = Arrays.asList( createMockAdminUnitDiseaseExtentClass(1, -100), createMockAdminUnitDiseaseExtentClass(2, -50), createMockAdminUnitDiseaseExtentClass(3, 0), createMockAdminUnitDiseaseExtentClass(4, 50), createMockAdminUnitDiseaseExtentClass(5, 100) ); // Act target.write(extent, sourceRaster, result); // Assert GridCoverage2DReader reader = new GeoTiffReader(result, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE)); Raster transformed = reader.read(null).getRenderedImage().getData(); assertThat(transformed.getSample(0, 0, 0)).isEqualTo(-100); assertThat(transformed.getSample(1, 0, 0)).isEqualTo(-50); assertThat(transformed.getSample(2, 0, 0)).isEqualTo(0); assertThat(transformed.getSample(0, 1, 0)).isEqualTo(50); assertThat(transformed.getSample(1, 1, 0)).isEqualTo(100); assertThat(transformed.getSample(2, 1, 0)).isEqualTo(-9999); assertThat(transformed.getSample(0, 2, 0)).isEqualTo(-9999); assertThat(transformed.getSample(1, 2, 0)).isEqualTo(-9999); assertThat(transformed.getSample(2, 2, 0)).isEqualTo(-9999); // Verify the meta data fields assertThat(result).hasContentEqualTo(new File(SMALL_RASTER_TRANSFORMED)); } private AdminUnitDiseaseExtentClass createMockAdminUnitDiseaseExtentClass(int gaul, int weighting) { AdminUnitDiseaseExtentClass obj = mock(AdminUnitDiseaseExtentClass.class); when(obj.getDiseaseExtentClass()).thenReturn(mock(DiseaseExtentClass.class)); when(obj.getDiseaseExtentClass().getWeighting()).thenReturn(weighting); when(obj.getAdminUnitGlobalOrTropical()).thenReturn(mock(AdminUnitGlobalOrTropical.class)); when(obj.getAdminUnitGlobalOrTropical().getGaulCode()).thenReturn(gaul); return obj; } @Test public void writeThrowIfSourceRasterCannotBeRead() throws Exception { // Arrange File sourceRaster = testFolder.newFile(); FileUtils.writeStringToFile(sourceRaster, "nonsense", "UTF-8"); File result = Paths.get(testFolder.newFolder().toString(), "foo.asc").toFile(); ExtentDataWriter target = new ExtentDataWriterImpl(); Collection<AdminUnitDiseaseExtentClass> extent = new ArrayList<>(); // Act catchException(target).write(extent, sourceRaster, result); // Assert assertThat(caughtException()).isInstanceOf(IOException.class); } @Test public void writeThrowIfTargetRasterCannotBeSaved() throws Exception { // Arrange File sourceRaster = testFolder.newFile(); FileUtils.writeStringToFile(sourceRaster, SMALL_RASTER, "UTF-8"); File result = testFolder.newFolder(); // already exists as a directory ExtentDataWriter target = new ExtentDataWriterImpl(); Collection<AdminUnitDiseaseExtentClass> extent = new ArrayList<>(); // Act catchException(target).write(extent, sourceRaster, result); // Assert assertThat(caughtException()).isInstanceOf(IOException.class); } }
apache-2.0
jasonwee/videoOnCloud
src/java/play/learn/java/design/twin/GameItem.java
270
package play.learn.java.design.twin; public abstract class GameItem { /** * Template method, do some common logic before draw */ public void draw() { System.out.println("draw"); doDraw(); } public abstract void doDraw(); public abstract void click(); }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-documentai/v1beta2/1.31.0/com/google/api/services/documentai/v1beta2/model/GoogleCloudDocumentaiV1beta1DocumentPageFormField.java
9758
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.documentai.v1beta2.model; /** * A form field detected on the page. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Document AI API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDocumentaiV1beta1DocumentPageFormField extends com.google.api.client.json.GenericJson { /** * Created for Labeling UI to export key text. If corrections were made to the text identified by * the `field_name.text_anchor`, this field will contain the correction. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String correctedKeyText; /** * Created for Labeling UI to export value text. If corrections were made to the text identified * by the `field_value.text_anchor`, this field will contain the correction. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String correctedValueText; /** * Layout for the FormField name. e.g. `Address`, `Email`, `Grand total`, `Phone number`, etc. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDocumentaiV1beta1DocumentPageLayout fieldName; /** * Layout for the FormField value. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDocumentaiV1beta1DocumentPageLayout fieldValue; /** * A list of detected languages for name together with confidence. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage> nameDetectedLanguages; static { // hack to force ProGuard to consider GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage.class); } /** * The history of this annotation. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDocumentaiV1beta1DocumentProvenance provenance; /** * A list of detected languages for value together with confidence. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage> valueDetectedLanguages; static { // hack to force ProGuard to consider GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage.class); } /** * If the value is non-textual, this field represents the type. Current valid values are: - blank * (this indicates the field_value is normal text) - "unfilled_checkbox" - "filled_checkbox" * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String valueType; /** * Created for Labeling UI to export key text. If corrections were made to the text identified by * the `field_name.text_anchor`, this field will contain the correction. * @return value or {@code null} for none */ public java.lang.String getCorrectedKeyText() { return correctedKeyText; } /** * Created for Labeling UI to export key text. If corrections were made to the text identified by * the `field_name.text_anchor`, this field will contain the correction. * @param correctedKeyText correctedKeyText or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setCorrectedKeyText(java.lang.String correctedKeyText) { this.correctedKeyText = correctedKeyText; return this; } /** * Created for Labeling UI to export value text. If corrections were made to the text identified * by the `field_value.text_anchor`, this field will contain the correction. * @return value or {@code null} for none */ public java.lang.String getCorrectedValueText() { return correctedValueText; } /** * Created for Labeling UI to export value text. If corrections were made to the text identified * by the `field_value.text_anchor`, this field will contain the correction. * @param correctedValueText correctedValueText or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setCorrectedValueText(java.lang.String correctedValueText) { this.correctedValueText = correctedValueText; return this; } /** * Layout for the FormField name. e.g. `Address`, `Email`, `Grand total`, `Phone number`, etc. * @return value or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageLayout getFieldName() { return fieldName; } /** * Layout for the FormField name. e.g. `Address`, `Email`, `Grand total`, `Phone number`, etc. * @param fieldName fieldName or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setFieldName(GoogleCloudDocumentaiV1beta1DocumentPageLayout fieldName) { this.fieldName = fieldName; return this; } /** * Layout for the FormField value. * @return value or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageLayout getFieldValue() { return fieldValue; } /** * Layout for the FormField value. * @param fieldValue fieldValue or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setFieldValue(GoogleCloudDocumentaiV1beta1DocumentPageLayout fieldValue) { this.fieldValue = fieldValue; return this; } /** * A list of detected languages for name together with confidence. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage> getNameDetectedLanguages() { return nameDetectedLanguages; } /** * A list of detected languages for name together with confidence. * @param nameDetectedLanguages nameDetectedLanguages or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setNameDetectedLanguages(java.util.List<GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage> nameDetectedLanguages) { this.nameDetectedLanguages = nameDetectedLanguages; return this; } /** * The history of this annotation. * @return value or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentProvenance getProvenance() { return provenance; } /** * The history of this annotation. * @param provenance provenance or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setProvenance(GoogleCloudDocumentaiV1beta1DocumentProvenance provenance) { this.provenance = provenance; return this; } /** * A list of detected languages for value together with confidence. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage> getValueDetectedLanguages() { return valueDetectedLanguages; } /** * A list of detected languages for value together with confidence. * @param valueDetectedLanguages valueDetectedLanguages or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setValueDetectedLanguages(java.util.List<GoogleCloudDocumentaiV1beta1DocumentPageDetectedLanguage> valueDetectedLanguages) { this.valueDetectedLanguages = valueDetectedLanguages; return this; } /** * If the value is non-textual, this field represents the type. Current valid values are: - blank * (this indicates the field_value is normal text) - "unfilled_checkbox" - "filled_checkbox" * @return value or {@code null} for none */ public java.lang.String getValueType() { return valueType; } /** * If the value is non-textual, this field represents the type. Current valid values are: - blank * (this indicates the field_value is normal text) - "unfilled_checkbox" - "filled_checkbox" * @param valueType valueType or {@code null} for none */ public GoogleCloudDocumentaiV1beta1DocumentPageFormField setValueType(java.lang.String valueType) { this.valueType = valueType; return this; } @Override public GoogleCloudDocumentaiV1beta1DocumentPageFormField set(String fieldName, Object value) { return (GoogleCloudDocumentaiV1beta1DocumentPageFormField) super.set(fieldName, value); } @Override public GoogleCloudDocumentaiV1beta1DocumentPageFormField clone() { return (GoogleCloudDocumentaiV1beta1DocumentPageFormField) super.clone(); } }
apache-2.0
huahin/huahin-core
src/test/java/org/huahinframework/core/lib/input/creator/LabelValueCreatorTest.java
3178
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.huahinframework.core.lib.input.creator; import static org.junit.Assert.assertEquals; import org.huahinframework.core.DataFormatException; import org.huahinframework.core.io.Value; import org.junit.Test; /** * */ public class LabelValueCreatorTest { @Test public void testString() throws DataFormatException { String[] labels = { "AAA", "BBB", "CCC", "DDD" }; ValueCreator valueCreator = new LabelValueCreator(labels, false, "\t", false); Value value = new Value(); String string1 = "a\tb\tc\td"; valueCreator.create(string1, value); assertEquals(value.getPrimitiveValue("AAA"), "a"); assertEquals(value.getPrimitiveValue("BBB"), "b"); assertEquals(value.getPrimitiveValue("CCC"), "c"); assertEquals(value.getPrimitiveValue("DDD"), "d"); assertEquals(value.getPrimitiveValue("EEE"), null); value.clear(); String string2 = "1\t2\t3\t4"; valueCreator.create(string2, value); assertEquals(value.getPrimitiveValue("AAA"), "1"); assertEquals(value.getPrimitiveValue("BBB"), "2"); assertEquals(value.getPrimitiveValue("CCC"), "3"); assertEquals(value.getPrimitiveValue("DDD"), "4"); assertEquals(value.getPrimitiveValue("EEE"), null); } @Test public void testRegex() throws DataFormatException { String[] labels = { "AAA", "BBB", "CCC", "DDD" }; ValueCreator valueCreator = new LabelValueCreator(labels, false, "^(.*)\\t(.*)\\t(.*)\\t(.*)$", true); Value value = new Value(); String string1 = "a\tb\tc\td"; valueCreator.create(string1, value); assertEquals(value.getPrimitiveValue("AAA"), "a"); assertEquals(value.getPrimitiveValue("BBB"), "b"); assertEquals(value.getPrimitiveValue("CCC"), "c"); assertEquals(value.getPrimitiveValue("DDD"), "d"); assertEquals(value.getPrimitiveValue("EEE"), null); value.clear(); String string2 = "1\t2\t3\t4"; valueCreator.create(string2, value); assertEquals(value.getPrimitiveValue("AAA"), "1"); assertEquals(value.getPrimitiveValue("BBB"), "2"); assertEquals(value.getPrimitiveValue("CCC"), "3"); assertEquals(value.getPrimitiveValue("DDD"), "4"); assertEquals(value.getPrimitiveValue("EEE"), null); } }
apache-2.0
kiumars/TheMovie
app/src/main/java/com/kian/themovie/ui/MainActivity.java
1119
package com.kian.themovie.ui; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.kian.themovie.R; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
apache-2.0
btmura/rbb
src/com/btmura/android/reddit/util/ThingIds.java
1202
/* * Copyright (C) 2013 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.util; /** * {@link ThingIds} is a utility class for manipulating thing ids. */ public class ThingIds { /** Add the given tag if the id does not have a tag at all. */ public static String addTag(String id, String tag) { int sepIndex = id.indexOf('_'); if (sepIndex != -1) { return id; } return tag + "_" + id; } /** Remove the tag if the id has one. */ public static String removeTag(String id) { int sepIndex = id.indexOf('_'); if (sepIndex != -1) { return id.substring(sepIndex + 1); } return id; } }
apache-2.0
datazuul/com.datazuul.apps--datazuul-explorer
src/main/java/org/jos/jexplorer/FilterWindow.java
2343
package org.jos.jexplorer; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; class FilterWindow extends JDialog{ private JTextField txtFilter = new JTextField(20); private String selectedFilter; public FilterWindow(JFrame owner, String filter){ super(owner, I18n.getString("FILTER_WINDOW_TITLE"), true); //setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ selectedFilter = ""; dispose(); } }); getContentPane().setLayout(new BorderLayout()); getContentPane().add(createGUI()); txtFilter.setText(filter); //setSize(300, 200); pack(); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(new Point((screen.width - getWidth()) / 2, (screen.height - getHeight()) / 2)); setVisible(true); } public String getSelectedFilter(){ return selectedFilter; } private JPanel createGUI(){ JPanel jp = new JPanel(new BorderLayout()); JPanel jpTxt = new JPanel(new FlowLayout(FlowLayout.LEFT)); jpTxt.add(new JLabel(I18n.getString("FILTER_WINDOW_NAME"))); jpTxt.add(txtFilter); jp.add(jpTxt, BorderLayout.NORTH); JPanel jpButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT)); Action ac = new ButtonAction(false); JButton jb = new JButton((String)ac.getValue(Action.NAME)); jb.addActionListener(ac); jpButtons.add(jb); ac = new ButtonAction(true); jb = new JButton((String)ac.getValue(Action.NAME)); jb.addActionListener(ac); jpButtons.add(jb); jp.add(jpButtons, BorderLayout.SOUTH); jp.add(new JLabel(I18n.getString("FILTER_WINDOW_TIP")), BorderLayout.CENTER); return jp; } /** * Implements the Ok and the Cancel button. */ class ButtonAction extends AbstractAction{ private boolean cancel; public ButtonAction(boolean cancel){ this.cancel = cancel; if (cancel){ putValue(Action.NAME, I18n.getString("CANCEL")); } else { putValue(Action.NAME, I18n.getString("OK")); } } public void actionPerformed(ActionEvent e){ if (!cancel){ //Ok button selectedFilter = txtFilter.getText(); dispose(); } else { //cancel button selectedFilter = ""; dispose(); } } } }
apache-2.0
cuba-platform/cuba
modules/gui/src/com/haulmont/cuba/gui/dynamicattributes/FilteringLookupAction.java
7000
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.haulmont.cuba.gui.dynamicattributes; import com.haulmont.bali.datastruct.Node; import com.haulmont.chile.core.model.MetaClass; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.gui.AppConfig; import com.haulmont.cuba.gui.ComponentsHelper; import com.haulmont.cuba.gui.Notifications; import com.haulmont.cuba.gui.Notifications.NotificationType; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.components.filter.ConditionParamBuilder; import com.haulmont.cuba.gui.components.filter.ConditionsTree; import com.haulmont.cuba.gui.components.filter.FilterParser; import com.haulmont.cuba.gui.components.filter.Param; import com.haulmont.cuba.gui.components.filter.condition.CustomCondition; import com.haulmont.cuba.gui.components.sys.ValuePathHelper; import com.haulmont.cuba.gui.data.impl.DsContextImplementation; import com.haulmont.cuba.security.entity.FilterEntity; import com.haulmont.cuba.security.global.UserSession; import org.apache.commons.lang3.RandomStringUtils; import org.dom4j.DocumentHelper; import org.dom4j.Element; import java.util.Collections; import java.util.Objects; import static com.haulmont.bali.util.Preconditions.checkNotNullArgument; import static com.haulmont.cuba.gui.ComponentsHelper.getScreenContext; /** * Extended PickerField.LookupAction. This action requires "join" and "where" clauses. When the lookup screen is * opened these clauses are used for creating dynamic filter condition in the Filter component. So the data in the * lookup screen is filtered. */ public class FilteringLookupAction extends PickerField.LookupAction { private ExtendedEntities extendedEntities; private String joinClause; private String whereClause; protected Messages messages = AppBeans.get(Messages.NAME); public FilteringLookupAction(PickerField pickerField, String joinClause, String whereClause) { super(pickerField); checkNotNullArgument(pickerField.getMetaClass(), "MetaClass for PickerField is not set"); this.joinClause = joinClause; this.whereClause = whereClause; extendedEntities = AppBeans.get(ExtendedEntities.class); } @Override protected void afterLookupWindowOpened(Window lookupWindow) { boolean found = ComponentsHelper.walkComponents(lookupWindow, screenComponent -> { if (!(screenComponent instanceof Filter)) { return false; } else { MetaClass actualMetaClass = ((FilterImplementation) screenComponent).getEntityMetaClass(); MetaClass propertyMetaClass = extendedEntities.getEffectiveMetaClass(pickerField.getMetaClass()); if (Objects.equals(actualMetaClass, propertyMetaClass)) { applyFilter(((Filter) screenComponent)); return true; } return false; } }); if (!found) { Notifications notifications = getScreenContext(pickerField).getNotifications(); notifications.create(NotificationType.WARNING) .withCaption(messages.getMainMessage("dynamicAttributes.entity.filter.filterNotFound")) .show(); } AbstractWindow controller = (AbstractWindow) (lookupWindow).getFrameOwner(); ((DsContextImplementation) controller.getDsContext()).resumeSuspended(); } protected void applyFilter(Filter filterComponent) { Metadata metadata = AppBeans.get(Metadata.class); FilterEntity filterEntity = metadata.create(FilterEntity.class); filterEntity.setComponentId(ComponentsHelper.getFilterComponentPath(filterComponent)); filterEntity.setName(messages.getMainMessage("dynamicAttributes.entity.filter")); filterEntity.setXml(createFilterXml(filterComponent)); UserSession userSession = AppBeans.get(UserSessionSource.class).getUserSession(); filterEntity.setUser(userSession.getCurrentOrSubstitutedUser()); filterComponent.setFilterEntity(filterEntity); filterComponent.apply(true); } protected String createFilterXml(Filter filterComponent) { ConditionsTree tree = new ConditionsTree(); CustomCondition condition = createCustomCondition(filterComponent); tree.setRootNodes(Collections.singletonList(new Node<>(condition))); return AppBeans.get(FilterParser.class).getXml(tree, Param.ValueProperty.VALUE); } protected CustomCondition createCustomCondition(Filter filterComponent) { CustomCondition condition = new CustomCondition(createConditionXmlElement(), AppConfig.getMessagesPack(), getFilterComponentName(filterComponent), ((FilterImplementation) filterComponent).getEntityMetaClass()); condition.setUnary(true); condition.setHidden(true); condition.setWhere(whereClause.replaceAll("\\?", ":" + condition.getParamName())); condition.setJoin(joinClause); ConditionParamBuilder paramBuilder = AppBeans.get(ConditionParamBuilder.class); Param param = Param.Builder.getInstance().setName(paramBuilder.createParamName(condition)) .setJavaClass(Boolean.class) .setEntityWhere("") .setEntityView("") .setMetaClass(((FilterImplementation) filterComponent).getEntityMetaClass()) .setInExpr(true) .setRequired(true) .build(); param.setValue(true); condition.setParam(param); return condition; } protected Element createConditionXmlElement() { Element conditionElement = DocumentHelper.createDocument().addElement("c"); conditionElement.addAttribute("name", RandomStringUtils.randomAlphabetic(10)); conditionElement.addAttribute("width", "1"); conditionElement.addAttribute("type", "CUSTOM"); conditionElement.addAttribute("locCaption", messages.getMainMessage("dynamicAttributes.filter.conditionName")); return conditionElement; } protected String getFilterComponentName(Filter filterComponent) { String filterComponentPath = ComponentsHelper.getFilterComponentPath(filterComponent); String[] strings = ValuePathHelper.parse(filterComponentPath); return ValuePathHelper.pathSuffix(strings); } }
apache-2.0
anonc187/jCoCoA
src/main/java/org/anon/cocoa/constraints/PreferentialEqualityConstraint.java
2039
/** * File CostMatrixConstraint.java * * This file is part of the jCoCoA project. * * Copyright 2016 Anonymous * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.anon.cocoa.constraints; import org.anon.cocoa.variables.DiscreteVariable; /** * CostMatrixConstraint * * @author Anomymous * @version 0.1 * @since 26 feb. 2016 */ public class PreferentialEqualityConstraint<V> extends CostMatrixConstraint<V> { /** * @param var1 * @param var2 */ public PreferentialEqualityConstraint(DiscreteVariable<V> var1, DiscreteVariable<V> var2, double[] pref1, double[] pref2, double inequalityCost) { super(var1, var2, PreferentialEqualityConstraint.buildCostMatrix(pref1, inequalityCost), PreferentialEqualityConstraint.buildCostMatrix(pref2, inequalityCost)); } /** * @param pref * @param inequalityCost * @return */ private static double[][] buildCostMatrix(double[] pref, double inequalityCost) { int size = pref.length; double[][] costs = new double[size][size]; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { if (x == y) { costs[x][y] = pref[x]; } else { costs[x][y] = inequalityCost; } } } return costs; } }
apache-2.0
SAP/xliff-1-2
com.sap.mlt.xliff12.api/src/main/java/com/sap/mlt/xliff12/api/base/XliffAttribute.java
198
package com.sap.mlt.xliff12.api.base; /** * Basic (tagging) interface extended by all XLIFF attributes. * * @author D049314 */ public interface XliffAttribute extends Attribute { }
apache-2.0
am-gooru/nucleus
nucleus-template/src/main/java/org/gooru/nucleus/entity/MetadataReferenceType.java
542
package org.gooru.nucleus.entity; /** * @author Sachin * * HOlds reference types for metadata */ public enum MetadataReferenceType { educational_use("educational_use "), moments_of_learning("moments_of_learning"), depth_of_knowledge("depth_of_knowledge"), reading_level("reading_level"), audience("audience"), advertisement_level("advertisement_level"), hazard_level("hazard_level"), media_feature("media_feature"), twentyone_century_skill("twentyone_century_skill"); private MetadataReferenceType(String name) { } }
apache-2.0
CenturyLinkCloud/clc-java-sdk
sdk/src/main/java/com/centurylink/cloud/sdk/policy/services/dsl/AutoscalePolicyService.java
8024
/* * (c) 2015 CenturyLink. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.centurylink.cloud.sdk.policy.services.dsl; import com.centurylink.cloud.sdk.policy.services.client.AutoscalePolicyClient; import com.centurylink.cloud.sdk.policy.services.client.domain.autoscale.SetAutoscalePolicyRequest; import com.centurylink.cloud.sdk.policy.services.client.domain.autoscale.AutoscalePolicyMetadata; import com.centurylink.cloud.sdk.policy.services.dsl.domain.autoscale.filter.AutoscalePolicyFilter; import com.centurylink.cloud.sdk.policy.services.dsl.domain.autoscale.refs.AutoscalePolicy; import com.centurylink.cloud.sdk.base.services.dsl.domain.queue.OperationFuture; import com.centurylink.cloud.sdk.base.services.dsl.domain.queue.job.future.JobFuture; import com.centurylink.cloud.sdk.base.services.dsl.domain.queue.job.future.NoWaitingJobFuture; import com.centurylink.cloud.sdk.base.services.dsl.domain.queue.job.future.ParallelJobsFuture; import com.centurylink.cloud.sdk.core.services.QueryService; import com.centurylink.cloud.sdk.server.services.dsl.ServerService; import com.centurylink.cloud.sdk.server.services.dsl.domain.server.filters.ServerFilter; import com.centurylink.cloud.sdk.server.services.dsl.domain.server.refs.Server; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static com.centurylink.cloud.sdk.core.function.Predicates.alwaysTrue; import static com.centurylink.cloud.sdk.core.function.Predicates.combine; import static com.centurylink.cloud.sdk.core.function.Predicates.in; import static com.centurylink.cloud.sdk.core.preconditions.Preconditions.checkNotNull; import static java.util.stream.Collectors.toList; public class AutoscalePolicyService implements QueryService<AutoscalePolicy, AutoscalePolicyFilter, AutoscalePolicyMetadata> { private final AutoscalePolicyClient autoscalePolicyClient; private final ServerService serverService; public AutoscalePolicyService(AutoscalePolicyClient autoscalePolicyClient, ServerService serverService) { this.autoscalePolicyClient = autoscalePolicyClient; this.serverService = serverService; } /** * {@inheritDoc} */ @Override public Stream<AutoscalePolicyMetadata> findLazy(AutoscalePolicyFilter filter) { checkNotNull(filter, "Filter must be not a null"); return autoscalePolicyClient .getAutoscalePolicies() .stream() .filter(filter.getPredicate()) .filter( filter.getIds().size() > 0 ? combine(AutoscalePolicyMetadata::getId, in(filter.getIds())) : alwaysTrue() ); } /** * Set autoscale policy on server * * @param autoscalePolicy autoscale policy * @param server server * @return OperationFuture wrapper for autoscalePolicy */ public OperationFuture<Server> setAutoscalePolicyOnServer(AutoscalePolicy autoscalePolicy, Server server) { autoscalePolicyClient.setAutoscalePolicyOnServer( serverService .findByRef(server) .getId(), new SetAutoscalePolicyRequest() .id( findByRef(autoscalePolicy).getId() ) ); return new OperationFuture<>(server, new NoWaitingJobFuture()); } /** * set autoscale policy on servers * * @param autoscalePolicy autoscale policy * @param serverList server list * @return OperationFuture wrapper for server list */ public OperationFuture<List<Server>> setAutoscalePolicyOnServer( AutoscalePolicy autoscalePolicy, List<Server> serverList ) { List<JobFuture> jobs = serverList .stream() .map(server -> setAutoscalePolicyOnServer(autoscalePolicy, server).jobFuture()) .collect(toList()); return new OperationFuture<>( serverList, new ParallelJobsFuture(jobs) ); } /** * set autoscale policy on servers * * @param autoscalePolicy autoscale policy * @param servers servers * @return OperationFuture wrapper for servers */ public OperationFuture<List<Server>> setAutoscalePolicyOnServer( AutoscalePolicy autoscalePolicy, Server... servers ) { return setAutoscalePolicyOnServer(autoscalePolicy, Arrays.asList(servers)); } /** * set autoscale policy on filtered servers * * @param autoscalePolicy autoscale policy * @param serverFilter server filter * @return OperationFuture wrapper for servers */ public OperationFuture<List<Server>> setAutoscalePolicyOnServer( AutoscalePolicy autoscalePolicy, ServerFilter serverFilter ) { return setAutoscalePolicyOnServer( autoscalePolicy, serverService .findLazy(serverFilter) .map(serverMetadata -> Server.refById(serverMetadata.getId())) .collect(toList()) ); } /** * get autoscale policy on server * * @param server server * @return AutoscalePolicyMetadata */ public AutoscalePolicyMetadata getAutoscalePolicyOnServer(Server server) { return autoscalePolicyClient .getAutoscalePolicyOnServer( serverService .findByRef(server) .getId() ); } /** * remove autoscale policy on server * * @param server server * @return OperationFuture wrapper for server */ public OperationFuture<Server> removeAutoscalePolicyOnServer(Server server) { autoscalePolicyClient .removeAutoscalePolicyOnServer( serverService.findByRef(server).getId() ); return new OperationFuture<>(server, new NoWaitingJobFuture()); } /** * remove autoscale policy on servers * * @param serverList server list * @return OperationFuture wrapper for server list */ public OperationFuture<List<Server>> removeAutoscalePolicyOnServer(List<Server> serverList) { List<JobFuture> jobs = serverList .stream() .map(server -> removeAutoscalePolicyOnServer(server).jobFuture()) .collect(toList()); return new OperationFuture<>( serverList, new ParallelJobsFuture(jobs) ); } /** * remove autoscale policy on servers * * @param servers servers * @return OperationFuture wrapper for servers */ public OperationFuture<List<Server>> removeAutoscalePolicyOnServer(Server... servers) { return removeAutoscalePolicyOnServer(Arrays.asList(servers)); } /** * remove autoscale policy on filtered servers * * @param serverFilter server filter * @return OperationFuture wrapper for servers */ public OperationFuture<List<Server>> removeAutoscalePolicyOnServer(ServerFilter serverFilter) { return removeAutoscalePolicyOnServer( serverService .findLazy(serverFilter) .map(serverMetadata -> Server.refById(serverMetadata.getId())) .collect(toList()) ); } }
apache-2.0
huashengzzz/SmartChart
app/src/main/java/com/smart/smartchart/http/request/PostFormRequest.java
3749
package com.smart.smartchart.http.request; import com.smart.smartchart.http.OkHttpUtils; import com.smart.smartchart.http.builder.PostFormBuilder; import com.smart.smartchart.http.callback.Callback; import java.io.UnsupportedEncodingException; import java.net.FileNameMap; import java.net.URLConnection; import java.net.URLEncoder; import java.util.List; import java.util.Map; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; /** * Created by zhy on 15/12/14. */ public class PostFormRequest extends OkHttpRequest { private List<PostFormBuilder.FileInput> files; public PostFormRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, List<PostFormBuilder.FileInput> files, int id) { super(url, tag, params, headers, id); this.files = files; } @Override protected RequestBody buildRequestBody() { if (files == null || files.isEmpty()) { FormBody.Builder builder = new FormBody.Builder(); addParams(builder); FormBody formBody = builder.build(); return formBody; } else { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); addParams(builder); for (int i = 0; i < files.size(); i++) { PostFormBuilder.FileInput fileInput = files.get(i); RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file); builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody); } return builder.build(); } } @Override protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback) { if (callback == null) return requestBody; CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener() { @Override public void onRequestProgress(final long bytesWritten, final long contentLength) { OkHttpUtils.getInstance().getDelivery().execute(new Runnable() { @Override public void run() { callback.inProgress(bytesWritten * 1.0f / contentLength, contentLength, id); } }); } }); return countingRequestBody; } @Override protected Request buildRequest(RequestBody requestBody) { return builder.post(requestBody).build(); } private String guessMimeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = null; try { contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; } private void addParams(MultipartBody.Builder builder) { if (params != null && !params.isEmpty()) { for (String key : params.keySet()) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""), RequestBody.create(null, params.get(key))); } } } private void addParams(FormBody.Builder builder) { if (params != null) { for (String key : params.keySet()) { builder.add(key, params.get(key)); } } } }
apache-2.0
miklosbarabas/springpolymer
demo-microservice-mainapp/src/test/java/com/example/AppMainTests.java
318
package com.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class AppMainTests { @Test public void contextLoads() { } }
apache-2.0
mattyb149/incubator-drill
exec/java-exec/src/main/java/org/apache/drill/exec/coord/zk/ZKRegistrationHandle.java
1257
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.coord.zk; import org.apache.drill.exec.coord.ClusterCoordinator; import org.apache.drill.exec.coord.ClusterCoordinator.RegistrationHandle; public class ZKRegistrationHandle implements RegistrationHandle { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ZKRegistrationHandle.class); public final String id; public ZKRegistrationHandle(String id) { super(); this.id = id; } }
apache-2.0
dsarlis/datix
datix/src/main/java/ags/utils/dataStructures/trees/thirdGenKD/KdTree.java
4679
package ags.utils.dataStructures.trees.thirdGenKD; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; /** * */ public class KdTree<T> extends KdNode<T> { private static final long serialVersionUID = -4403464702046042517L; public KdTree(int dimensions) { this(dimensions, 24); } public KdTree(int dimensions, int bucketCapacity) { super(dimensions, bucketCapacity); } public KdTree(BufferedReader br) throws IOException { super(br); } public NearestNeighborIterator<T> getNearestNeighborIterator(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { return new NearestNeighborIterator<T>(this, searchPoint, maxPointsReturned, distanceFunction); } public MaxHeap<T> findNearestNeighbors(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { BinaryHeap.Min<KdNode<T>> pendingPaths = new BinaryHeap.Min<KdNode<T>>(); BinaryHeap.Max<T> evaluatedPoints = new BinaryHeap.Max<T>(); int pointsRemaining = Math.min(maxPointsReturned, size()); pendingPaths.offer(0, this); while (pendingPaths.size() > 0 && (evaluatedPoints.size() < pointsRemaining || (pendingPaths.getMinKey() < evaluatedPoints.getMaxKey()))) { nearestNeighborSearchStep(pendingPaths, evaluatedPoints, pointsRemaining, distanceFunction, searchPoint); } return evaluatedPoints; } @SuppressWarnings("unchecked") protected static <T> void nearestNeighborSearchStep ( MinHeap<KdNode<T>> pendingPaths, MaxHeap<T> evaluatedPoints, int desiredPoints, DistanceFunction distanceFunction, double[] searchPoint) { // If there are pending paths possibly closer than the nearest evaluated point, check it out KdNode<T> cursor = pendingPaths.getMin(); pendingPaths.removeMin(); // Descend the tree, recording paths not taken while (!cursor.isLeaf()) { KdNode<T> pathNotTaken; if (searchPoint[cursor.splitDimension] > cursor.splitValue) { pathNotTaken = cursor.left; cursor = cursor.right; } else { pathNotTaken = cursor.right; cursor = cursor.left; } double otherDistance = distanceFunction.distanceToRect(searchPoint, pathNotTaken.minBound, pathNotTaken.maxBound); // Only add a path if we either need more points or it's closer than furthest point on list so far if (evaluatedPoints.size() < desiredPoints || otherDistance <= evaluatedPoints.getMaxKey()) { pendingPaths.offer(otherDistance, pathNotTaken); } } if (cursor.singlePoint) { double nodeDistance = distanceFunction.distance(cursor.points[0], searchPoint); // Only add a point if either need more points or it's closer than furthest on list so far if (evaluatedPoints.size() < desiredPoints || nodeDistance <= evaluatedPoints.getMaxKey()) { for (int i = 0; i < cursor.size(); i++) { T value = (T) cursor.data[i]; // If we don't need any more, replace max if (evaluatedPoints.size() == desiredPoints) { evaluatedPoints.replaceMax(nodeDistance, value); } else { evaluatedPoints.offer(nodeDistance, value); } } } } else { // Add the points at the cursor for (int i = 0; i < cursor.size(); i++) { double[] point = cursor.points[i]; T value = (T) cursor.data[i]; double distance = distanceFunction.distance(point, searchPoint); // Only add a point if either need more points or it's closer than furthest on list so far if (evaluatedPoints.size() < desiredPoints) { evaluatedPoints.offer(distance, value); } else if (distance < evaluatedPoints.getMaxKey()) { evaluatedPoints.replaceMax(distance, value); } } } } public int find(double[] point) { /*System.out.print("Finding point: "); for (int i = 0; i < point.length; i++) { System.out.print(point[i]+" "); } System.out.println();*/ return find1(point); } public void printTree(BufferedWriter writer) throws IOException { writer.write(this.dimensions+" "+this.bucketCapacity+"\n"); this.printTree1(writer); writer.close(); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/DescribeCertificateResultJsonUnmarshaller.java
2912
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iot.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.iot.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeCertificateResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeCertificateResultJsonUnmarshaller implements Unmarshaller<DescribeCertificateResult, JsonUnmarshallerContext> { public DescribeCertificateResult unmarshall(JsonUnmarshallerContext context) throws Exception { DescribeCertificateResult describeCertificateResult = new DescribeCertificateResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return describeCertificateResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("certificateDescription", targetDepth)) { context.nextToken(); describeCertificateResult.setCertificateDescription(CertificateDescriptionJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return describeCertificateResult; } private static DescribeCertificateResultJsonUnmarshaller instance; public static DescribeCertificateResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeCertificateResultJsonUnmarshaller(); return instance; } }
apache-2.0
gennitor/gennitor-annotations
src/main/java/com/gennitor/system/client/annotation/purpose/CollectionRecord.java
667
package com.gennitor.system.client.annotation.purpose; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author Christos Tsakostas - c.tsakostas@gmail.com */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface CollectionRecord { /** * The name of the collection record. ATTENTION: It must be in lowerCamelCase format! * * @return name */ String name(); /** * The related purpose name. * * @return related final cause name */ String relatedPurposeName(); }
apache-2.0
SES-fortiss/SmartGridCoSimulation
projects/previousProjects/memapEtherium/src/main/java/ethereum/components/Building3.java
8629
package ethereum.components; import java.math.BigInteger; import java.util.ArrayList; import ethereum.Simulation; import ethereum.helper.ConsumptionProfiles; import ethereum.helper.Market; import ethereum.helper.SolarRadiation; import ethereum.helper.UnitHelper; public class Building3 extends Building { private BigInteger currentPVProduction = BigInteger.ZERO; private double pvArea = 8.; private BigInteger stateOfCharge = BigInteger.ZERO; private BigInteger maxInOut; //Ws private BigInteger capacity; //Ws private double storageEfficiency = 1.; private BigInteger heatPumpPower = BigInteger.valueOf(20000); public Building3( String name, int rpcport, String privateKey, ConsumptionProfiles consumptionProfiles, int consumerIndex ) { super(name, rpcport, privateKey, consumptionProfiles, consumerIndex); maxInOut = BigInteger.valueOf((long) (5000 * storageEfficiency)) .multiply(Simulation.TIMESTEP_DURATION_IN_SECONDS); // gasboilerPrice = UnitConverter.getCentsPerWsFromCents(5.2); capacity = UnitHelper.getWSfromKWH(100); logger.print(",pv,heatPumpConsumption,heatPumpProduction," + "fromThermalStorage,toThermalStorage,stateOfCharge," + "lackingHeat,excessElectricity,electricityLack,gasUsed,failedPosts,nrOfTransactions"); logger.println(); } @Override public void makeDecision() { super.makeDecision(); logger.print("," + currentPVProduction); BigInteger heatPumpMaxProduction = Simulation.TIMESTEP_DURATION_IN_SECONDS.multiply(heatPumpPower); BigInteger heatToProduce = currentHeatConsumption.add(soldHeat); heatToProduce = heatToProduce.subtract(boughtHeat); //never demand more heat than consumption+soldHeat --> always positive or zero BigInteger fromStorage = heatToProduce.min(stateOfCharge).min(maxInOut); heatToProduce = heatToProduce.subtract(fromStorage); stateOfCharge = stateOfCharge.subtract(fromStorage); BigInteger electricityToProduce = currentElectricityConsumption.add(soldElectricity).subtract(boughtElectricity); BigInteger heatProduction = heatPumpMaxProduction.min(heatToProduce); BigInteger electricityForHeatPump = BigInteger.ZERO; if(isGreaterZero(heatToProduce)) { electricityForHeatPump = electricityForHeatPump.add(heatToElectricityAmount(heatProduction)); electricityToProduce = electricityToProduce.add(electricityForHeatPump); // add electricity needed to produce necessary heating power heatToProduce = heatToProduce.subtract(heatProduction); } BigInteger excessElectricity = BigInteger.ZERO.max(currentPVProduction.subtract(electricityToProduce)); electricityToProduce = electricityToProduce.subtract(currentPVProduction).max(BigInteger.ZERO); BigInteger maxHeatPumpProduction = electricityToHeatAmount(excessElectricity).min(heatPumpMaxProduction.subtract(heatProduction)); BigInteger maxCharge = capacity.subtract(stateOfCharge).min(maxInOut.add(fromStorage)); BigInteger toStorage = maxCharge.min(maxHeatPumpProduction); heatProduction = heatProduction.add(toStorage); if(isGreaterZero(toStorage)) { stateOfCharge = stateOfCharge.add(toStorage); electricityForHeatPump = electricityForHeatPump.add(heatToElectricityAmount(toStorage)); excessElectricity = excessElectricity.subtract( electricityForHeatPump); } logger.print("," + electricityForHeatPump); logger.print("," + heatProduction); logger.print("," + fromStorage); logger.print("," + toStorage); logger.print("," + stateOfCharge); if(isGreaterZero(heatToProduce)) { System.out.println("[" + name + "] Lacking heat : " + UnitHelper.printAmount(heatToProduce)); timestepInfo.heatWithdrawal = heatToProduce; } logger.print("," + heatToProduce); if(isGreaterZero(excessElectricity)) { System.out.println("[" + name + "] Excess electricity: " + UnitHelper.printAmount(excessElectricity)); timestepInfo.electricityFeedIn = excessElectricity; } logger.print("," + excessElectricity); if(isGreaterZero(electricityToProduce)) { System.out.println("[" + name + "] Lacking electricity : " + UnitHelper.printAmount(electricityToProduce)); timestepInfo.electricityWithdrawal = electricityToProduce; } logger.print("," + electricityToProduce); BigInteger nextHeatConsumption = consumptionProfiles.getHeatConsumption( consumerIndex, this.actor.getCurrentTimeStep() ); BigInteger nextPVProduction = BigInteger.valueOf( (long) (SolarRadiation.getRadiation(this.actor.getCurrentTimeStep()) * pvArea*1000000000) //kW * 1000000000 ).multiply(BigInteger.valueOf(1000)) //W * 1000000000 .multiply(Simulation.TIMESTEP_DURATION_IN_SECONDS).divide(BigInteger.valueOf(1000000000)); //Ws BigInteger nextElectricityConsumption = consumptionProfiles.getElectricityConsumption( consumerIndex, this.actor.getCurrentTimeStep() ); System.out.println("[" + name + "] Expected heat consumption for next step: " + UnitHelper.printAmount(nextHeatConsumption)); System.out.println("[" + name + "] Expected electricity consumption for next step: " + UnitHelper.printAmount(nextElectricityConsumption)); System.out.println("[" + name + "] Expected PV production for next step: " + UnitHelper.printAmount(nextPVProduction)); electricityToProduce = nextElectricityConsumption.subtract(nextPVProduction).max(BigInteger.ZERO); excessElectricity = nextPVProduction.subtract(nextElectricityConsumption).max(BigInteger.ZERO); maxCharge = capacity.subtract(stateOfCharge).min(maxInOut); heatProduction = electricityToHeatAmount(excessElectricity).min(heatPumpMaxProduction).min(nextHeatConsumption.add(maxCharge)); BigInteger heatNeeded = nextHeatConsumption.subtract(heatProduction).max(BigInteger.ZERO); excessElectricity = excessElectricity.subtract(heatToElectricityAmount(heatProduction)); fromStorage = stateOfCharge.min(maxInOut); toStorage = capacity.subtract(stateOfCharge).min(maxInOut); ArrayList<BigInteger> heatDemandPrices = new ArrayList<BigInteger>(); ArrayList<BigInteger> heatDemandAmounts = new ArrayList<BigInteger>(); BigInteger heatPrice1 = findUniqueDemandPrice(electricityToHeatPrice(UnitHelper.getEtherPerWsFromCents(Simulation.ELECTRICITY_MIN_PRICE)), Market.HEAT); BigInteger heatAmount1 = fromStorage.min(toStorage); // demand amount that could be as well taken from storage but only as much as could be added to storage in case other demand is also fulfilled if(isGreaterZero(heatAmount1)) { logDemand(heatAmount1, UnitHelper.getCentsPerKwhFromWeiPerWs(heatPrice1), Market.HEAT); heatDemandAmounts.add(heatAmount1); heatDemandPrices.add(heatPrice1); } heatDemandAmounts.add(heatNeeded); BigInteger heatPrice2 = findUniqueDemandPrice(electricityToHeatPrice(UnitHelper.getEtherPerWsFromCents(Simulation.ELECTRICITY_MAX_PRICE)), Market.HEAT); heatDemandPrices.add(heatPrice2); logDemand(heatNeeded, UnitHelper.getCentsPerKwhFromWeiPerWs(heatPrice2), Market.HEAT); postDemand(heatDemandPrices, heatDemandAmounts, Market.HEAT); BigInteger heatToOffer = fromStorage.add(heatPumpMaxProduction); if(isGreaterZero(heatToOffer)) { postAndLogOfferSplit(heatPrice2, heatToOffer, Market.HEAT); } ArrayList<BigInteger> electricityDemandPrices = new ArrayList<BigInteger>(); ArrayList<BigInteger> electricityDemandAmounts = new ArrayList<BigInteger>(); if(isGreaterZero(electricityToProduce)) { electricityDemandPrices.add(UnitHelper.getEtherPerWsFromCents(Simulation.ELECTRICITY_MAX_PRICE)); electricityDemandAmounts.add(electricityToProduce); logDemand(electricityToProduce, Simulation.ELECTRICITY_MAX_PRICE, Market.ELECTRICITY); postDemand(electricityDemandPrices, electricityDemandAmounts, Market.ELECTRICITY); } if(isGreaterZero(excessElectricity)) { postAndLogOfferSplit(UnitHelper.getEtherPerWsFromCents(Simulation.ELECTRICITY_MIN_PRICE), excessElectricity, Market.ELECTRICITY); } currentElectricityConsumption = nextElectricityConsumption; currentHeatConsumption = nextHeatConsumption; currentPVProduction = nextPVProduction; logger.print("," + gasUsed + "," + failedPosts + "," + nrOfTransactions); logger.println(); } private BigInteger electricityToHeatPrice(BigInteger centsPerWs) { return centsPerWs.multiply(BigInteger.TEN).divide(BigInteger.valueOf(38)); } private BigInteger electricityToHeatAmount(BigInteger electricityAmount) { return electricityAmount.multiply(BigInteger.valueOf(38)).divide(BigInteger.TEN); } private BigInteger heatToElectricityAmount(BigInteger heatAmount) { return heatAmount.multiply(BigInteger.TEN).divide(BigInteger.valueOf(38)); } }
apache-2.0
Mithrandir0x/JNRPE-LIB
src/it/jnrpe/server/config/CPluginDir.java
955
/* * Copyright (c) 2008 Massimiliano Ziccardi * * 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 it.jnrpe.server.config; /** * Container class for plugin directory configuration * @author Massimiliano Ziccardi * */ public class CPluginDir { private String m_sPath = null; public CPluginDir() { } public void setPath(String sPath) { m_sPath = sPath; } public String getPath() { return m_sPath; } }
apache-2.0
pramoth/light-admin
lightadmin-core/src/main/java/org/lightadmin/core/view/preparer/ListViewPreparer.java
2787
package org.lightadmin.core.view.preparer; import com.google.common.collect.Collections2; import org.apache.tiles.AttributeContext; import org.apache.tiles.context.TilesRequestContext; import org.lightadmin.api.config.utils.ScopeMetadataUtils; import org.lightadmin.core.config.domain.DomainTypeAdministrationConfiguration; import org.lightadmin.core.config.domain.scope.ScopeMetadata; import org.lightadmin.core.persistence.repository.DynamicJpaRepository; import org.lightadmin.core.util.Pair; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import static com.google.common.collect.Lists.newLinkedList; import static org.lightadmin.api.config.utils.ScopeMetadataUtils.*; public class ListViewPreparer extends ConfigurationAwareViewPreparer { @Override protected void execute(final TilesRequestContext tilesContext, final AttributeContext attributeContext, final DomainTypeAdministrationConfiguration configuration) { super.execute(tilesContext, attributeContext, configuration); addAttribute(attributeContext, "fields", configuration.getListViewFragment().getFields()); addAttribute(attributeContext, "scopes", scopes(configuration)); addAttribute(attributeContext, "filters", configuration.getFilters()); } private List<Pair<? extends ScopeMetadata, Long>> scopes(DomainTypeAdministrationConfiguration configuration) { final List<Pair<? extends ScopeMetadata, Long>> result = newLinkedList(); final Iterable<ScopeMetadata> scopes = configuration.getScopes(); final DynamicJpaRepository<?, ?> repository = configuration.getRepository(); for (ScopeMetadata scope : scopes) { if (isPredicateScope(scope)) { result.add(scopeWithRecordsCount((PredicateScopeMetadata) scope, repository)); } else if (isSpecificationScope(scope)) { result.add(scopeWithRecordsCount((ScopeMetadataUtils.SpecificationScopeMetadata) scope, repository)); } else { result.add(Pair.create(scope, repository.count())); } } return result; } @SuppressWarnings("unchecked") private Pair<? extends ScopeMetadata, Long> scopeWithRecordsCount(final ScopeMetadataUtils.SpecificationScopeMetadata scope, final DynamicJpaRepository<?, ?> repository) { return Pair.create(scope, repository.count(scope.specification())); } @SuppressWarnings("unchecked") private Pair<? extends ScopeMetadata, Long> scopeWithRecordsCount(final PredicateScopeMetadata scope, final JpaRepository<?, ?> repository) { long recordsCount = Collections2.filter(repository.findAll(), scope.predicate()).size(); return Pair.create(scope, recordsCount); } }
apache-2.0
Flipkart/foxtrot
foxtrot-common/src/main/java/com/flipkart/foxtrot/common/query/datetime/TimeWindow.java
370
package com.flipkart.foxtrot.common.query.datetime; import lombok.Builder; import lombok.Data; @Data public class TimeWindow { private long startTime = 0L; private long endTime = 0L; public TimeWindow() { } @Builder public TimeWindow(long startTime, long endTime) { this.startTime = startTime; this.endTime = endTime; } }
apache-2.0