repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
nathancassano/PlayFabJavaAndroidSDK
PlayFabClientSDK/src/com/playfab/LinkGameCenterAccountRequest.java
249
package com.playfab; import java.util.HashMap; import java.util.Date; public class LinkGameCenterAccountRequest { /// <summary> /// Game Center identifier for the player account to be linked /// </summary> public String GameCenterId; }
apache-2.0
wangyusheng/NewBook3
src/com/example/newbook4/bean/InfoBean.java
918
package com.example.newbook4.bean; import java.util.Comparator; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class InfoBean { public int info_id; public int user_id; public String bookname; public String price; //public String time; public String address; public int concern_num; public int accusation_num; public String generate_time; public InfoBean() { } public String getRealAddress() { try { JSONObject jsonObject = new JSONObject(address); return jsonObject.getString("address1"); } catch (JSONException e) { Log.d("InfoBean", e.toString()); } return ""; // {"contact":"ÁªÏµÈË","address":"¼ªÁÖÊ¡³¤´ºÊÐÊÐÏ½ÇøÏêϸµØÖ·","phone":"18940997430"} } public static Comparator<InfoBean> Comparator = new Comparator<InfoBean>() { public int compare(InfoBean s1, InfoBean s2) { return s2.info_id - s1.info_id; } }; }
apache-2.0
GavinCT/SimpleLeakCanary
library/src/main/java/com/czt/simpleleakcanary/library/GcTrigger.java
1776
/* * Copyright (C) 2011 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.czt.simpleleakcanary.library; /** * Called when a watched reference is expected to be weakly reachable, but hasn't been enqueued * in the reference queue yet. This gives the application a hook to run the GC before the {@link * RefWatcher} checks the reference queue again, to avoid taking a heap dump if possible. */ public interface GcTrigger { GcTrigger DEFAULT = new GcTrigger() { @Override public void runGc() { // Code taken from AOSP FinalizationTest: // https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/ // java/lang/ref/FinalizationTester.java // System.gc() does not garbage collect every time. Runtime.gc() is // more likely to perfom a gc. Runtime.getRuntime().gc(); enqueueReferences(); System.runFinalization(); } private void enqueueReferences() { // Hack. We don't have a programmatic way to wait for the reference queue daemon to move // references to the appropriate queues. try { Thread.sleep(100); } catch (InterruptedException e) { throw new AssertionError(); } } }; void runGc(); }
apache-2.0
Silvermedia/unitils
unitils-core/src/main/java/org/unitils/core/junit/AfterTestTearDownStatement.java
1320
/* * Copyright 2013, Unitils.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 org.unitils.core.junit; import org.junit.runners.model.Statement; import org.unitils.core.engine.UnitilsTestListener; /** * @author Tim Ducheyne */ public class AfterTestTearDownStatement extends Statement { protected UnitilsTestListener unitilsTestListener; protected Statement nextStatement; public AfterTestTearDownStatement(UnitilsTestListener unitilsTestListener, Statement nextStatement) { this.unitilsTestListener = unitilsTestListener; this.nextStatement = nextStatement; } @Override public void evaluate() throws Throwable { nextStatement.evaluate(); unitilsTestListener.afterTestTearDown(); } }
apache-2.0
China-ls/wechat4java
src/main/java/weixin/popular/bean/datacube/getcardbizuininfo/BizuinInfoResultInfo.java
4198
package weixin.popular.bean.datacube.getcardbizuininfo; import com.google.gson.annotations.SerializedName; /** * 拉取卡券概况数据接口-响应参数-日期数据 * * @author Moyq5 */ public class BizuinInfoResultInfo { /** * 日期信息 */ @SerializedName("ref_date") private String refDate; /** * 浏览次数 */ @SerializedName("view_cnt") private Integer viewCnt; /** * 浏览人数 */ @SerializedName("view_user") private Integer viewUser; /** * 领取次数 */ @SerializedName("receive_cnt") private Integer receiveCnt; /** * 领取人数 */ @SerializedName("receive_user") private Integer receiveUser; /** * 使用次数 */ @SerializedName("verify_cnt") private Integer verifyCnt; /** * 使用人数 */ @SerializedName("verify_user") private Integer verifyUser; /** * 转赠次数 */ @SerializedName("given_cnt") private Integer givenCnt; /** * 转赠人数 */ @SerializedName("given_user") private Integer givenUser; /** * 过期次数 */ @SerializedName("expire_cnt") private Integer expireCnt; /** * 过期人数 */ @SerializedName("expire_user") private Integer expireUser; /** * @return 日期信息 */ public String getRefDate() { return refDate; } /** * @param refDate 日期信息 */ public void setRefDate(String refDate) { this.refDate = refDate; } /** * @return 浏览次数 */ public Integer getViewCnt() { return viewCnt; } /** * @param viewCnt 浏览次数 */ public void setViewCnt(Integer viewCnt) { this.viewCnt = viewCnt; } /** * @return 浏览人数 */ public Integer getViewUser() { return viewUser; } /** * @param viewUser 浏览人数 */ public void setViewUser(Integer viewUser) { this.viewUser = viewUser; } /** * @return 领取次数 */ public Integer getReceiveCnt() { return receiveCnt; } /** * @param receiveCnt 领取次数 */ public void setReceiveCnt(Integer receiveCnt) { this.receiveCnt = receiveCnt; } /** * @return 领取人数 */ public Integer getReceiveUser() { return receiveUser; } /** * @param receiveUser 领取人数 */ public void setReceiveUser(Integer receiveUser) { this.receiveUser = receiveUser; } /** * @return 使用次数 */ public Integer getVerifyCnt() { return verifyCnt; } /** * @param verifyCnt 使用次数 */ public void setVerifyCnt(Integer verifyCnt) { this.verifyCnt = verifyCnt; } /** * @return 使用人数 */ public Integer getVerifyUser() { return verifyUser; } /** * @param verifyUser 使用人数 */ public void setVerifyUser(Integer verifyUser) { this.verifyUser = verifyUser; } /** * @return 转赠次数 */ public Integer getGivenCnt() { return givenCnt; } /** * @param givenCnt 转赠次数 */ public void setGivenCnt(Integer givenCnt) { this.givenCnt = givenCnt; } /** * @return 转赠人数 */ public Integer getGivenUser() { return givenUser; } /** * @param givenUser 转赠人数 */ public void setGivenUser(Integer givenUser) { this.givenUser = givenUser; } /** * @return 过期次数 */ public Integer getExpireCnt() { return expireCnt; } /** * @param expireCnt 过期次数 */ public void setExpireCnt(Integer expireCnt) { this.expireCnt = expireCnt; } /** * @return 过期人数 */ public Integer getExpireUser() { return expireUser; } /** * @param expireUser 过期人数 */ public void setExpireUser(Integer expireUser) { this.expireUser = expireUser; } }
apache-2.0
consulo/consulo-rust
gen/vektah/rust/psi/RustExprClosure.java
343
// This is a generated file. Not intended for manual editing. package vektah.rust.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface RustExprClosure extends RustExpr { @NotNull RustClosureBody getClosureBody(); @NotNull RustClosureExprArgs getClosureExprArgs(); }
apache-2.0
Frostman/webjavin
webjavin-indigo/src/main/java/ru/frostman/web/indigo/openid/OpenId.java
1963
/****************************************************************************** * WebJavin - Java Web Framework. * * * * Copyright (c) 2011 - Sergey "Frosman" Lukjanov, me@frostman.ru * * * * 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 ru.frostman.web.indigo.openid; import ru.frostman.web.controller.Controllers; /** * @author slukjanov aka Frostman */ public class OpenId { public static String getAuthUrl(String openIdProvider, String targetUrl) { return Controllers.url(OpenIdController.AUTH_REDIRECT_URL) + "?" + OpenIdController.PARAM_PROVIDER + "=" + openIdProvider + "&" + OpenIdController.PARAM_TARGET + "=" + targetUrl; } public static String getGoogleAuthUrl(String targetUrl) { return getAuthUrl(OpenIdController.GOOGLE_ENDPOINT, targetUrl); } }
apache-2.0
florentw/bench
cluster-jms/src/main/java/io/amaze/bench/cluster/jms/JMSLeaderClusterClientFactory.java
4603
/* * Copyright 2016-2017 Florent Weber <florent.weber@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.amaze.bench.cluster.jms; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.typesafe.config.Config; import io.amaze.bench.cluster.actor.ActorSender; import io.amaze.bench.cluster.leader.LeaderClusterClientFactory; import io.amaze.bench.cluster.leader.ResourceManagerClusterClient; import io.amaze.bench.cluster.metric.MetricsRepository; import io.amaze.bench.cluster.metric.MetricsRepositoryClusterClient; import io.amaze.bench.cluster.registry.ActorRegistry; import io.amaze.bench.cluster.registry.ActorRegistryClusterClient; import io.amaze.bench.cluster.registry.AgentRegistry; import io.amaze.bench.cluster.registry.AgentRegistryClusterClient; import io.amaze.bench.shared.jms.*; import javax.validation.constraints.NotNull; import static com.google.common.base.Throwables.propagate; import static java.util.Objects.requireNonNull; /** * Created on 10/23/16. */ public final class JMSLeaderClusterClientFactory implements LeaderClusterClientFactory { private final JMSServer server; private final JMSEndpoint serverEndpoint; private final ActorRegistry actorRegistry; private volatile JMSClient senderJmsClient; public JMSLeaderClusterClientFactory(@NotNull final Config factoryConfig, @NotNull final ActorRegistry actorRegistry) { this.actorRegistry = requireNonNull(actorRegistry); try { this.serverEndpoint = new JMSEndpoint(factoryConfig); this.server = new FFMQServer(serverEndpoint); } catch (JMSException e) { throw propagate(e); } } @VisibleForTesting public JMSLeaderClusterClientFactory(@NotNull final JMSServer server, @NotNull final JMSEndpoint serverEndpoint, @NotNull final ActorRegistry actorRegistry) { this.actorRegistry = requireNonNull(actorRegistry); this.serverEndpoint = requireNonNull(serverEndpoint); this.server = requireNonNull(server); } @Override public ActorSender actorSender() { senderJmsClient = createJmsClient(); return new JMSActorSender(senderJmsClient); } @Override public ResourceManagerClusterClient createForResourceManager() { return new JMSResourceManagerClusterClient(server, serverEndpoint); } @Override public MetricsRepositoryClusterClient createForMetricsRepository(@NotNull final MetricsRepository metricsRepository) { requireNonNull(metricsRepository); MetricsRepositoryClusterClient clusterClient = new JMSMetricsRepositoryClusterClient(serverEndpoint); clusterClient.startMetricsListener(metricsRepository.createClusterListener()); return clusterClient; } @Override public ActorRegistryClusterClient createForActorRegistry() { ActorRegistryClusterClient registryClusterClient = new JMSActorRegistryClusterClient(serverEndpoint); registryClusterClient.startRegistryListener(actorRegistry.createClusterListener()); return registryClusterClient; } @Override public AgentRegistryClusterClient createForAgentRegistry(@NotNull final AgentRegistry agentRegistry) { requireNonNull(agentRegistry); AgentRegistryClusterClient agentRegistryClient = new JMSAgentRegistryClusterClient(serverEndpoint); agentRegistryClient.startRegistryListener(agentRegistry.createClusterListener()); return agentRegistryClient; } @Override public void close() { if (senderJmsClient != null) { senderJmsClient.close(); } server.close(); } private JMSClient createJmsClient() { JMSClient client; try { client = new FFMQClient(serverEndpoint); } catch (JMSException e) { throw Throwables.propagate(e); } return client; } }
apache-2.0
Overruler/gerrit
gerrit-httpd/src/main/java/com/google/gerrit/httpd/restapi/RestApiServlet.java
37717
// Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.httpd.restapi; import static com.google.common.base.Preconditions.checkNotNull; import static java.math.RoundingMode.CEILING; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.UTF_8; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; import static javax.servlet.http.HttpServletResponse.SC_CREATED; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.common.io.BaseEncoding; import com.google.common.math.IntMath; import com.google.common.net.HttpHeaders; import com.google.gerrit.audit.AuditService; import com.google.gerrit.audit.HttpAuditEvent; import com.google.gerrit.common.Nullable; import com.google.gerrit.common.TimeUtil; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.extensions.registration.DynamicMap; import com.google.gerrit.extensions.restapi.AcceptsCreate; import com.google.gerrit.extensions.restapi.AcceptsDelete; import com.google.gerrit.extensions.restapi.AcceptsPost; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.BinaryResult; import com.google.gerrit.extensions.restapi.CacheControl; import com.google.gerrit.extensions.restapi.DefaultInput; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.MethodNotAllowedException; import com.google.gerrit.extensions.restapi.PreconditionFailedException; import com.google.gerrit.extensions.restapi.RawInput; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.Response; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.extensions.restapi.RestCollection; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.extensions.restapi.RestResource; import com.google.gerrit.extensions.restapi.RestView; import com.google.gerrit.extensions.restapi.TopLevelResource; import com.google.gerrit.extensions.restapi.UnprocessableEntityException; import com.google.gerrit.httpd.WebSession; import com.google.gerrit.server.AccessPath; import com.google.gerrit.server.AnonymousUser; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.OptionUtil; import com.google.gerrit.server.OutputFormat; import com.google.gerrit.server.account.CapabilityUtils; import com.google.gerrit.util.http.RequestUtil; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; import com.google.gwtexpui.server.CacheHeaders; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.util.Providers; import org.eclipse.jgit.util.TemporaryBuffer; import org.eclipse.jgit.util.TemporaryBuffer.Heap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.Timestamp; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RestApiServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory .getLogger(RestApiServlet.class); /** MIME type used for a JSON response body. */ private static final String JSON_TYPE = "application/json"; private static final String FORM_TYPE = "application/x-www-form-urlencoded"; /** * Garbage prefix inserted before JSON output to prevent XSSI. * <p> * This prefix is ")]}'\n" and is designed to prevent a web browser from * executing the response body if the resource URI were to be referenced using * a &lt;script src="...&gt; HTML tag from another web site. Clients using the * HTTP interface will need to always strip the first line of response data to * remove this magic header. */ public static final byte[] JSON_MAGIC; static { JSON_MAGIC = ")]}'\n".getBytes(UTF_8); } public static class Globals { final Provider<CurrentUser> currentUser; final DynamicItem<WebSession> webSession; final Provider<ParameterParser> paramParser; final AuditService auditService; @Inject Globals(Provider<CurrentUser> currentUser, DynamicItem<WebSession> webSession, Provider<ParameterParser> paramParser, AuditService auditService) { this.currentUser = currentUser; this.webSession = webSession; this.paramParser = paramParser; this.auditService = auditService; } } private final Globals globals; private final Provider<RestCollection<RestResource, RestResource>> members; public RestApiServlet(Globals globals, RestCollection<? extends RestResource, ? extends RestResource> members) { this(globals, Providers.of(members)); } public RestApiServlet(Globals globals, Provider<? extends RestCollection<? extends RestResource, ? extends RestResource>> members) { @SuppressWarnings("unchecked") Provider<RestCollection<RestResource, RestResource>> n = (Provider<RestCollection<RestResource, RestResource>>) checkNotNull((Object) members); this.globals = globals; this.members = n; } @Override protected final void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long auditStartTs = TimeUtil.nowMs(); res.setHeader("Content-Disposition", "attachment"); res.setHeader("X-Content-Type-Options", "nosniff"); int status = SC_OK; Object result = null; Multimap<String, String> params = LinkedHashMultimap.create(); Object inputRequestBody = null; try { checkUserSession(req); List<IdString> path = splitPath(req); RestCollection<RestResource, RestResource> rc = members.get(); CapabilityUtils.checkRequiresCapability(globals.currentUser, null, rc.getClass()); RestResource rsrc = TopLevelResource.INSTANCE; ViewData viewData = new ViewData(null, null); if (path.isEmpty()) { if (isGetOrHead(req)) { viewData = new ViewData(null, rc.list()); } else if (rc instanceof AcceptsPost && "POST".equals(req.getMethod())) { @SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) rc; viewData = new ViewData(null, ac.post(rsrc)); } else { throw new MethodNotAllowedException(); } } else { IdString id = path.remove(0); try { rsrc = rc.parse(rsrc, id); if (path.isEmpty()) { checkPreconditions(req); } } catch (ResourceNotFoundException e) { if (rc instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) { @SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) rc; viewData = new ViewData(null, ac.create(rsrc, id)); status = SC_CREATED; } else { throw e; } } if (viewData.view == null) { viewData = view(rsrc, rc, req.getMethod(), path); } } checkRequiresCapability(viewData); while (viewData.view instanceof RestCollection<?,?>) { @SuppressWarnings("unchecked") RestCollection<RestResource, RestResource> c = (RestCollection<RestResource, RestResource>) viewData.view; if (path.isEmpty()) { if (isGetOrHead(req)) { viewData = new ViewData(null, c.list()); } else if (c instanceof AcceptsPost && "POST".equals(req.getMethod())) { @SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) c; viewData = new ViewData(null, ac.post(rsrc)); } else if (c instanceof AcceptsDelete && "DELETE".equals(req.getMethod())) { @SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c; viewData = new ViewData(null, ac.delete(rsrc, null)); } else { throw new MethodNotAllowedException(); } break; } else { IdString id = path.remove(0); try { rsrc = c.parse(rsrc, id); checkPreconditions(req); viewData = new ViewData(null, null); } catch (ResourceNotFoundException e) { if (c instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) { @SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) c; viewData = new ViewData(viewData.pluginName, ac.create(rsrc, id)); status = SC_CREATED; } else if (c instanceof AcceptsDelete && path.isEmpty() && "DELETE".equals(req.getMethod())) { @SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c; viewData = new ViewData(viewData.pluginName, ac.delete(rsrc, id)); status = SC_NO_CONTENT; } else { throw e; } } if (viewData.view == null) { viewData = view(rsrc, c, req.getMethod(), path); } } checkRequiresCapability(viewData); } if (notModified(req, rsrc)) { res.sendError(SC_NOT_MODIFIED); return; } Multimap<String, String> config = LinkedHashMultimap.create(); ParameterParser.splitQueryString(req.getQueryString(), config, params); if (!globals.paramParser.get().parse(viewData.view, params, req, res)) { return; } if (viewData.view instanceof RestModifyView<?, ?>) { @SuppressWarnings("unchecked") RestModifyView<RestResource, Object> m = (RestModifyView<RestResource, Object>) viewData.view; inputRequestBody = parseRequest(req, inputType(m)); result = m.apply(rsrc, inputRequestBody); } else if (viewData.view instanceof RestReadView<?>) { result = ((RestReadView<RestResource>) viewData.view).apply(rsrc); } else { throw new ResourceNotFoundException(); } if (result instanceof Response) { @SuppressWarnings("rawtypes") Response<?> r = (Response) result; status = r.statusCode(); configureCaching(req, res, rsrc, r.caching()); } else if (result instanceof Response.Redirect) { CacheHeaders.setNotCacheable(res); res.sendRedirect(((Response.Redirect) result).location()); return; } else { CacheHeaders.setNotCacheable(res); } res.setStatus(status); if (result != Response.none()) { result = Response.unwrap(result); if (result instanceof BinaryResult) { replyBinaryResult(req, res, (BinaryResult) result); } else { replyJson(req, res, config, result); } } } catch (MalformedJsonException e) { replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e); } catch (JsonParseException e) { replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e); } catch (BadRequestException e) { replyError(req, res, status = SC_BAD_REQUEST, messageOr(e, "Bad Request"), e.caching(), e); } catch (AuthException e) { replyError(req, res, status = SC_FORBIDDEN, messageOr(e, "Forbidden"), e.caching(), e); } catch (AmbiguousViewException e) { replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Ambiguous"), e); } catch (ResourceNotFoundException e) { replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Not Found"), e.caching(), e); } catch (MethodNotAllowedException e) { replyError(req, res, status = SC_METHOD_NOT_ALLOWED, messageOr(e, "Method Not Allowed"), e.caching(), e); } catch (ResourceConflictException e) { replyError(req, res, status = SC_CONFLICT, messageOr(e, "Conflict"), e.caching(), e); } catch (PreconditionFailedException e) { replyError(req, res, status = SC_PRECONDITION_FAILED, messageOr(e, "Precondition Failed"), e.caching(), e); } catch (UnprocessableEntityException e) { replyError(req, res, status = 422, messageOr(e, "Unprocessable Entity"), e.caching(), e); } catch (Exception e) { status = SC_INTERNAL_SERVER_ERROR; handleException(e, req, res); } finally { globals.auditService.dispatch(new HttpAuditEvent(globals.webSession.get() .getSessionId(), globals.currentUser.get(), req.getRequestURI(), auditStartTs, params, req.getMethod(), inputRequestBody, status, result)); } } private static String messageOr(Throwable t, String defaultMessage) { if (!Strings.isNullOrEmpty(t.getMessage())) { return t.getMessage(); } return defaultMessage; } private static boolean notModified(HttpServletRequest req, RestResource rsrc) { if (!isGetOrHead(req)) { return false; } if (rsrc instanceof RestResource.HasETag) { String have = req.getHeader(HttpHeaders.IF_NONE_MATCH); if (have != null) { return have.equals(((RestResource.HasETag) rsrc).getETag()); } } if (rsrc instanceof RestResource.HasLastModified) { Timestamp m = ((RestResource.HasLastModified) rsrc).getLastModified(); long d = req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); // HTTP times are in seconds, database may have millisecond precision. return d / 1000L == m.getTime() / 1000L; } return false; } private static <T> void configureCaching(HttpServletRequest req, HttpServletResponse res, RestResource rsrc, CacheControl c) { if (isGetOrHead(req)) { switch (c.getType()) { case NONE: default: CacheHeaders.setNotCacheable(res); break; case PRIVATE: addResourceStateHeaders(res, rsrc); CacheHeaders.setCacheablePrivate(res, c.getAge(), c.getUnit(), c.isMustRevalidate()); break; case PUBLIC: addResourceStateHeaders(res, rsrc); CacheHeaders.setCacheable(req, res, c.getAge(), c.getUnit(), c.isMustRevalidate()); break; } } else { CacheHeaders.setNotCacheable(res); } } private static void addResourceStateHeaders( HttpServletResponse res, RestResource rsrc) { if (rsrc instanceof RestResource.HasETag) { res.setHeader( HttpHeaders.ETAG, ((RestResource.HasETag) rsrc).getETag()); } if (rsrc instanceof RestResource.HasLastModified) { res.setDateHeader( HttpHeaders.LAST_MODIFIED, ((RestResource.HasLastModified) rsrc).getLastModified().getTime()); } } private void checkPreconditions(HttpServletRequest req) throws PreconditionFailedException { if ("*".equals(req.getHeader("If-None-Match"))) { throw new PreconditionFailedException("Resource already exists"); } } private static Type inputType(RestModifyView<RestResource, Object> m) { Type inputType = extractInputType(m.getClass()); if (inputType == null) { throw new IllegalStateException(String.format( "View %s does not correctly implement %s", m.getClass(), RestModifyView.class.getSimpleName())); } return inputType; } @SuppressWarnings("rawtypes") private static Type extractInputType(Class clazz) { for (Type t : clazz.getGenericInterfaces()) { if (t instanceof ParameterizedType && ((ParameterizedType) t).getRawType() == RestModifyView.class) { return ((ParameterizedType) t).getActualTypeArguments()[1]; } } if (clazz.getSuperclass() != null) { Type i = extractInputType(clazz.getSuperclass()); if (i != null) { return i; } } for (Class t : clazz.getInterfaces()) { Type i = extractInputType(t); if (i != null) { return i; } } return null; } private Object parseRequest(HttpServletRequest req, Type type) throws IOException, BadRequestException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, MethodNotAllowedException { if (isType(JSON_TYPE, req.getContentType())) { BufferedReader br = req.getReader(); try { JsonReader json = new JsonReader(br); json.setLenient(true); JsonToken first; try { first = json.peek(); } catch (EOFException e) { throw new BadRequestException("Expected JSON object"); } if (first == JsonToken.STRING) { return parseString(json.nextString(), type); } return OutputFormat.JSON.newGson().fromJson(json, type); } finally { br.close(); } } else if (("PUT".equals(req.getMethod()) || "POST".equals(req.getMethod())) && acceptsRawInput(type)) { return parseRawInput(req, type); } else if ("DELETE".equals(req.getMethod()) && hasNoBody(req)) { return null; } else if (hasNoBody(req)) { return createInstance(type); } else if (isType("text/plain", req.getContentType())) { BufferedReader br = req.getReader(); try { char[] tmp = new char[256]; StringBuilder sb = new StringBuilder(); int n; while (0 < (n = br.read(tmp))) { sb.append(tmp, 0, n); } return parseString(sb.toString(), type); } finally { br.close(); } } else if ("POST".equals(req.getMethod()) && isType(FORM_TYPE, req.getContentType())) { return OutputFormat.JSON.newGson().fromJson( ParameterParser.formToJson(req), type); } else { throw new BadRequestException("Expected Content-Type: " + JSON_TYPE); } } private static boolean hasNoBody(HttpServletRequest req) { int len = req.getContentLength(); String type = req.getContentType(); return (len <= 0 && type == null) || (len == 0 && isType(FORM_TYPE, type)); } @SuppressWarnings("rawtypes") private static boolean acceptsRawInput(Type type) { if (type instanceof Class) { for (Field f : ((Class) type).getDeclaredFields()) { if (f.getType() == RawInput.class) { return true; } } } return false; } private Object parseRawInput(final HttpServletRequest req, Type type) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, MethodNotAllowedException { Object obj = createInstance(type); for (Field f : obj.getClass().getDeclaredFields()) { if (f.getType() == RawInput.class) { f.setAccessible(true); f.set(obj, new RawInput() { @Override public String getContentType() { return req.getContentType(); } @Override public long getContentLength() { return req.getContentLength(); } @Override public InputStream getInputStream() throws IOException { return req.getInputStream(); } }); return obj; } } throw new MethodNotAllowedException(); } private Object parseString(String value, Type type) throws BadRequestException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { if (type == String.class) { return value; } Object obj = createInstance(type); Field[] fields = obj.getClass().getDeclaredFields(); if (fields.length == 0 && Strings.isNullOrEmpty(value)) { return obj; } for (Field f : fields) { if (f.getAnnotation(DefaultInput.class) != null && f.getType() == String.class) { f.setAccessible(true); f.set(obj, value); return obj; } } throw new BadRequestException("Expected JSON object"); } private static Object createInstance(Type type) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { if (type instanceof Class) { @SuppressWarnings("unchecked") Class<Object> clazz = (Class<Object>) type; Constructor<Object> c = clazz.getDeclaredConstructor(); c.setAccessible(true); return c.newInstance(); } throw new InstantiationException("Cannot make " + type); } public static void replyJson(@Nullable HttpServletRequest req, HttpServletResponse res, Multimap<String, String> config, Object result) throws IOException { TemporaryBuffer.Heap buf = heap(Integer.MAX_VALUE); buf.write(JSON_MAGIC); Writer w = new BufferedWriter(new OutputStreamWriter(buf, UTF_8)); Gson gson = newGson(config, req); if (result instanceof JsonElement) { gson.toJson((JsonElement) result, w); } else { gson.toJson(result, w); } w.write('\n'); w.flush(); replyBinaryResult(req, res, asBinaryResult(buf) .setContentType(JSON_TYPE) .setCharacterEncoding(UTF_8.name())); } private static Gson newGson(Multimap<String, String> config, @Nullable HttpServletRequest req) { GsonBuilder gb = OutputFormat.JSON_COMPACT.newGsonBuilder(); enablePrettyPrint(gb, config, req); enablePartialGetFields(gb, config); return gb.create(); } private static void enablePrettyPrint(GsonBuilder gb, Multimap<String, String> config, @Nullable HttpServletRequest req) { String pp = Iterables.getFirst(config.get("pp"), null); if (pp == null) { pp = Iterables.getFirst(config.get("prettyPrint"), null); if (pp == null && req != null) { pp = acceptsJson(req) ? "0" : "1"; } } if ("1".equals(pp) || "true".equals(pp)) { gb.setPrettyPrinting(); } } private static void enablePartialGetFields(GsonBuilder gb, Multimap<String, String> config) { final Set<String> want = Sets.newHashSet(); for (String p : config.get("fields")) { Iterables.addAll(want, OptionUtil.splitOptionValue(p)); } if (!want.isEmpty()) { gb.addSerializationExclusionStrategy(new ExclusionStrategy() { private final Map<String, String> names = Maps.newHashMap(); @Override public boolean shouldSkipField(FieldAttributes field) { String name = names.get(field.getName()); if (name == null) { // Names are supplied by Gson in terms of Java source. // Translate and cache the JSON lower_case_style used. try { name = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES.translateName(// field.getDeclaringClass().getDeclaredField(field.getName())); names.put(field.getName(), name); } catch (SecurityException e) { return true; } catch (NoSuchFieldException e) { return true; } } return !want.contains(name); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); } } static void replyBinaryResult( @Nullable HttpServletRequest req, HttpServletResponse res, BinaryResult bin) throws IOException { final BinaryResult appResult = bin; try { if (bin.getAttachmentName() != null) { res.setHeader( "Content-Disposition", "attachment; filename=\"" + bin.getAttachmentName() + "\""); } if (bin.isBase64()) { bin = stackBase64(res, bin); } if (bin.canGzip() && acceptsGzip(req)) { bin = stackGzip(res, bin); } res.setContentType(bin.getContentType()); long len = bin.getContentLength(); if (0 <= len && len < Integer.MAX_VALUE) { res.setContentLength((int) len); } else if (0 <= len) { res.setHeader("Content-Length", Long.toString(len)); } if (req == null || !"HEAD".equals(req.getMethod())) { OutputStream dst = res.getOutputStream(); try { bin.writeTo(dst); } finally { dst.close(); } } } finally { appResult.close(); } } private static BinaryResult stackBase64(HttpServletResponse res, final BinaryResult src) throws IOException { BinaryResult b64; long len = src.getContentLength(); if (0 <= len && len <= (7 << 20)) { b64 = base64(src); } else { b64 = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { OutputStream e = BaseEncoding.base64().encodingStream( new OutputStreamWriter(out, ISO_8859_1)); src.writeTo(e); e.flush(); } }; } res.setHeader("X-FYI-Content-Encoding", "base64"); res.setHeader("X-FYI-Content-Type", src.getContentType()); return b64.setContentType("text/plain").setCharacterEncoding("ISO-8859-1"); } private static BinaryResult stackGzip(HttpServletResponse res, final BinaryResult src) throws IOException { BinaryResult gz; long len = src.getContentLength(); if (256 <= len && len <= (10 << 20)) { gz = compress(src); if (len <= gz.getContentLength()) { return src; } } else { gz = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { GZIPOutputStream gz = new GZIPOutputStream(out); src.writeTo(gz); gz.finish(); gz.flush(); } }; } res.setHeader("Content-Encoding", "gzip"); return gz.setContentType(src.getContentType()); } private ViewData view( RestResource rsrc, RestCollection<RestResource, RestResource> rc, String method, List<IdString> path) throws AmbiguousViewException, RestApiException { DynamicMap<RestView<RestResource>> views = rc.views(); final IdString projection = path.isEmpty() ? IdString.fromUrl("/") : path.remove(0); if (!path.isEmpty()) { // If there are path components still remaining after this projection // is chosen, look for the projection based upon GET as the method as // the client thinks it is a nested collection. method = "GET"; } else if ("HEAD".equals(method)) { method = "GET"; } List<String> p = splitProjection(projection); if (p.size() == 2) { String viewname = p.get(1); if (Strings.isNullOrEmpty(viewname)) { viewname = "/"; } RestView<RestResource> view = views.get(p.get(0), method + "." + viewname); if (view != null) { return new ViewData(p.get(0), view); } view = views.get(p.get(0), "GET." + viewname); if (view != null) { if (view instanceof AcceptsPost && "POST".equals(method)) { @SuppressWarnings("unchecked") AcceptsPost<RestResource> ap = (AcceptsPost<RestResource>) view; return new ViewData(p.get(0), ap.post(rsrc)); } } throw new ResourceNotFoundException(projection); } String name = method + "." + p.get(0); RestView<RestResource> core = views.get("gerrit", name); if (core != null) { return new ViewData(null, core); } else { core = views.get("gerrit", "GET." + p.get(0)); if (core instanceof AcceptsPost && "POST".equals(method)) { @SuppressWarnings("unchecked") AcceptsPost<RestResource> ap = (AcceptsPost<RestResource>) core; return new ViewData(null, ap.post(rsrc)); } } Map<String, RestView<RestResource>> r = Maps.newTreeMap(); for (String plugin : views.plugins()) { RestView<RestResource> action = views.get(plugin, name); if (action != null) { r.put(plugin, action); } } if (r.size() == 1) { Map.Entry<String, RestView<RestResource>> entry = Iterables.getOnlyElement(r.entrySet()); return new ViewData(entry.getKey(), entry.getValue()); } else if (r.isEmpty()) { throw new ResourceNotFoundException(projection); } else { throw new AmbiguousViewException(String.format( "Projection %s is ambiguous: %s", name, Joiner.on(", ").join( Iterables.transform(r.keySet(), new Function<String, String>() { @Override public String apply(String in) { return in + "~" + projection; } })))); } } private static List<IdString> splitPath(HttpServletRequest req) { String path = RequestUtil.getEncodedPathInfo(req); if (Strings.isNullOrEmpty(path)) { return Collections.emptyList(); } List<IdString> out = Lists.newArrayList(); for (String p : Splitter.on('/').split(path)) { out.add(IdString.fromUrl(p)); } if (out.size() > 0 && out.get(out.size() - 1).isEmpty()) { out.remove(out.size() - 1); } return out; } private static List<String> splitProjection(IdString projection) { List<String> p = Lists.newArrayListWithCapacity(2); Iterables.addAll(p, Splitter.on('~').limit(2).split(projection.get())); return p; } private void checkUserSession(HttpServletRequest req) throws AuthException { CurrentUser user = globals.currentUser.get(); if (isStateChange(req)) { if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if (!globals.webSession.get().isAccessPathOk(AccessPath.REST_API)) { throw new AuthException("Invalid authentication method. In order to authenticate, prefix the REST endpoint URL with /a/ (e.g. http://example.com/a/projects/)."); } } user.setAccessPath(AccessPath.REST_API); } private static boolean isGetOrHead(HttpServletRequest req) { return "GET".equals(req.getMethod()) || "HEAD".equals(req.getMethod()); } private static boolean isStateChange(HttpServletRequest req) { return !isGetOrHead(req); } private void checkRequiresCapability(ViewData viewData) throws AuthException { CapabilityUtils.checkRequiresCapability(globals.currentUser, viewData.pluginName, viewData.view.getClass()); } private static void handleException(Throwable err, HttpServletRequest req, HttpServletResponse res) throws IOException { String uri = req.getRequestURI(); if (!Strings.isNullOrEmpty(req.getQueryString())) { uri += "?" + req.getQueryString(); } log.error(String.format("Error in %s %s", req.getMethod(), uri), err); if (!res.isCommitted()) { res.reset(); replyError(req, res, SC_INTERNAL_SERVER_ERROR, "Internal server error", err); } } public static void replyError(HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, @Nullable Throwable err) throws IOException { replyError(req, res, statusCode, msg, CacheControl.NONE, err); } public static void replyError(HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, CacheControl c, @Nullable Throwable err) throws IOException { if (err != null) { RequestUtil.setErrorTraceAttribute(req, err); } configureCaching(req, res, null, c); res.setStatus(statusCode); replyText(req, res, msg); } static void replyText(@Nullable HttpServletRequest req, HttpServletResponse res, String text) throws IOException { if ((req == null || isGetOrHead(req)) && isMaybeHTML(text)) { replyJson(req, res, ImmutableMultimap.of("pp", "0"), new JsonPrimitive(text)); } else { if (!text.endsWith("\n")) { text += "\n"; } replyBinaryResult(req, res, BinaryResult.create(text).setContentType("text/plain")); } } private static final Pattern IS_HTML = Pattern.compile("[<&]"); private static boolean isMaybeHTML(String text) { return IS_HTML.matcher(text).find(); } private static boolean acceptsJson(HttpServletRequest req) { return req != null && isType(JSON_TYPE, req.getHeader(HttpHeaders.ACCEPT)); } private static boolean acceptsGzip(HttpServletRequest req) { if (req != null) { String accepts = req.getHeader(HttpHeaders.ACCEPT_ENCODING); return accepts != null && accepts.contains("gzip"); } return false; } private static boolean isType(String expect, String given) { if (given == null) { return false; } else if (expect.equals(given)) { return true; } else if (given.startsWith(expect + ",")) { return true; } for (String p : given.split("[ ,;][ ,;]*")) { if (expect.equals(p)) { return true; } } return false; } private static BinaryResult base64(BinaryResult bin) throws IOException { int max = 4 * IntMath.divide((int) bin.getContentLength(), 3, CEILING); TemporaryBuffer.Heap buf = heap(max); OutputStream encoded = BaseEncoding.base64().encodingStream( new OutputStreamWriter(buf, ISO_8859_1)); bin.writeTo(encoded); encoded.close(); return asBinaryResult(buf); } private static BinaryResult compress(BinaryResult bin) throws IOException { TemporaryBuffer.Heap buf = heap(20 << 20); GZIPOutputStream gz = new GZIPOutputStream(buf); bin.writeTo(gz); gz.close(); return asBinaryResult(buf).setContentType(bin.getContentType()); } @SuppressWarnings("resource") private static BinaryResult asBinaryResult(final TemporaryBuffer.Heap buf) { return new BinaryResult() { @Override public void writeTo(OutputStream os) throws IOException { buf.writeTo(os, null); } }.setContentLength(buf.length()); } private static Heap heap(int max) { return new TemporaryBuffer.Heap(max); } @SuppressWarnings("serial") private static class AmbiguousViewException extends Exception { AmbiguousViewException(String message) { super(message); } } private static class ViewData { String pluginName; RestView<RestResource> view; ViewData(String pluginName, RestView<RestResource> view) { this.pluginName = pluginName; this.view = view; } } }
apache-2.0
justinsb/cloudata
cloudata-client/src/main/java/com/cloudata/clients/keyvalue/PrefixKeyValueStore.java
3663
package com.cloudata.clients.keyvalue; import java.io.IOException; import java.util.Iterator; import java.util.List; import com.google.common.base.Function; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.ByteString; public class PrefixKeyValueStore implements KeyValueStore { final KeyValueStore inner; final ByteString prefix; private PrefixKeyValueStore(KeyValueStore inner, ByteString prefix) { this.inner = inner; this.prefix = prefix; } public static PrefixKeyValueStore create(KeyValueStore inner, ByteString prefix) { if (inner instanceof PrefixKeyValueStore) { PrefixKeyValueStore innerPrefixKeyValueStore = (PrefixKeyValueStore) inner; ByteString combinedPrefix = innerPrefixKeyValueStore.prefix.concat(prefix); return PrefixKeyValueStore.create(innerPrefixKeyValueStore.inner, combinedPrefix); } else { return new PrefixKeyValueStore(inner, prefix); } } @Override public Iterator<ByteString> listKeysWithPrefix(int space, ByteString filter) { ByteString filterWithPrefix = this.prefix.concat(filter); Iterator<ByteString> keys = inner.listKeysWithPrefix(space, filterWithPrefix); return Iterators.transform(keys, new Function<ByteString, ByteString>() { @Override public ByteString apply(ByteString withPrefix) { assert withPrefix.substring(0, prefix.size()) == prefix; return withPrefix.substring(prefix.size()); } }); } @Override public Iterator<KeyValueEntry> listEntriesWithPrefix(int space, ByteString filter) { ByteString filterWithPrefix = this.prefix.concat(filter); Iterator<KeyValueEntry> entries = inner.listEntriesWithPrefix(space, filterWithPrefix); return Iterators.transform(entries, new Function<KeyValueEntry, KeyValueEntry>() { @Override public KeyValueEntry apply(KeyValueEntry entry) { ByteString key = entry.getKey(); assert key.substring(0, prefix.size()) == prefix; return new KeyValueEntry(key.substring(prefix.size()), entry.getValue()); } }); } @Override public ByteString read(int space, ByteString key) throws IOException { ByteString keyWithPrefix = prefix.concat(key); return inner.read(space, keyWithPrefix); } @Override public boolean delete(int space, ByteString key, Modifier... modifiers) throws IOException { ByteString keyWithPrefix = prefix.concat(key); return inner.delete(space, keyWithPrefix, modifiers); } @Override public boolean putSync(int space, ByteString key, ByteString value, Modifier... modifiers) throws IOException { ByteString keyWithPrefix = prefix.concat(key); return inner.putSync(space, keyWithPrefix, value, modifiers); } @Override public ListenableFuture<Boolean> putAsync(int space, ByteString key, ByteString value, Modifier... modifiers) { ByteString keyWithPrefix = prefix.concat(key); return inner.putAsync(space, keyWithPrefix, value, modifiers); } @Override public ListenableFuture<Integer> delete(int keyspaceId, List<ByteString> keys) { List<ByteString> keysWithPrefix = Lists.newArrayList(); for (ByteString key : keys) { keysWithPrefix.add(prefix.concat(key)); } return inner.delete(keyspaceId, keysWithPrefix); } }
apache-2.0
MythTV-Clients/MythTV-Service-API
src/main/java/org/mythtv/services/api/v027/beans/TitleInfo.java
1693
/* * Copyright (c) 2014 TIKINOU 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 org.mythtv.services.api.v027.beans; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * <b>Auto-generated file, do not modify manually !!!!</b> * * @author Sebastien Astie */ @JsonIgnoreProperties( ignoreUnknown = true ) public class TitleInfo { @JsonProperty( "Title" ) private String title; @JsonProperty( "Inetref" ) private String inetref; /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle( String title ) { this.title = title; } /** * @return the inetref */ public String getInetref() { return inetref; } /** * @param inetref the inetref to set */ public void setInetref( String inetref ) { this.inetref = inetref; } }
apache-2.0
ubikloadpack/jmeter
src/components/org/apache/jmeter/visualizers/backend/graphite/AbstractGraphiteMetricsSender.java
2633
/* * 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.jmeter.visualizers.backend.graphite; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.impl.GenericKeyedObjectPool; import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig; /** * Base class for {@link GraphiteMetricsSender} * @since 2.13 */ abstract class AbstractGraphiteMetricsSender implements GraphiteMetricsSender { /** * Create a new keyed pool of {@link SocketOutputStream}s using a * {@link SocketOutputStreamPoolFactory}. The keys for the pool are * {@link SocketConnectionInfos} instances. * * @return GenericKeyedObjectPool the newly generated pool */ protected GenericKeyedObjectPool<SocketConnectionInfos, SocketOutputStream> createSocketOutputStreamPool() { GenericKeyedObjectPoolConfig<SocketOutputStream> config = new GenericKeyedObjectPoolConfig<>(); config.setTestOnBorrow(true); config.setTestWhileIdle(true); config.setMaxTotalPerKey(-1); config.setMaxTotal(-1); config.setMaxIdlePerKey(-1); config.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(3)); config.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES.toMillis(3)); return new GenericKeyedObjectPool<>( new SocketOutputStreamPoolFactory(SOCKET_CONNECT_TIMEOUT_MS, SOCKET_TIMEOUT), config); } /** * Replaces Graphite reserved chars: * <ul> * <li>' ' by '-'</li> * <li>'\\' by '-'</li> * <li>'.' by '_'</li> * </ul> * * @param s * text to be sanitized * @return the sanitized text */ static String sanitizeString(String s) { // String#replace uses regexp return StringUtils.replaceChars(s, "\\ .", "--_"); } }
apache-2.0
wenzhucjy/tomcat_source
tomcat-8.0.9-sourcecode/java/org/apache/tomcat/websocket/Util.java
21751
/* * 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.tomcat.websocket; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import javax.websocket.CloseReason.CloseCode; import javax.websocket.CloseReason.CloseCodes; import javax.websocket.Decoder; import javax.websocket.Decoder.Binary; import javax.websocket.Decoder.BinaryStream; import javax.websocket.Decoder.Text; import javax.websocket.Decoder.TextStream; import javax.websocket.DeploymentException; import javax.websocket.Encoder; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.PongMessage; import javax.websocket.Session; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBinary; import org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeText; /** * Utility class for internal use only within the * {@link org.apache.tomcat.websocket} package. */ public class Util { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final Queue<SecureRandom> randoms = new ConcurrentLinkedQueue<>(); private Util() { // Hide default constructor } static boolean isControl(byte opCode) { return (opCode & 0x08) > 0; } static boolean isText(byte opCode) { return opCode == Constants.OPCODE_TEXT; } static CloseCode getCloseCode(int code) { if (code > 2999 && code < 5000) { return CloseCodes.NORMAL_CLOSURE; } switch (code) { case 1000: return CloseCodes.NORMAL_CLOSURE; case 1001: return CloseCodes.GOING_AWAY; case 1002: return CloseCodes.PROTOCOL_ERROR; case 1003: return CloseCodes.CANNOT_ACCEPT; case 1004: // Should not be used in a close frame // return CloseCodes.RESERVED; return CloseCodes.PROTOCOL_ERROR; case 1005: // Should not be used in a close frame // return CloseCodes.NO_STATUS_CODE; return CloseCodes.PROTOCOL_ERROR; case 1006: // Should not be used in a close frame // return CloseCodes.CLOSED_ABNORMALLY; return CloseCodes.PROTOCOL_ERROR; case 1007: return CloseCodes.NOT_CONSISTENT; case 1008: return CloseCodes.VIOLATED_POLICY; case 1009: return CloseCodes.TOO_BIG; case 1010: return CloseCodes.NO_EXTENSION; case 1011: return CloseCodes.UNEXPECTED_CONDITION; case 1012: // Not in RFC6455 // return CloseCodes.SERVICE_RESTART; return CloseCodes.PROTOCOL_ERROR; case 1013: // Not in RFC6455 // return CloseCodes.TRY_AGAIN_LATER; return CloseCodes.PROTOCOL_ERROR; case 1015: // Should not be used in a close frame // return CloseCodes.TLS_HANDSHAKE_FAILURE; return CloseCodes.PROTOCOL_ERROR; default: return CloseCodes.PROTOCOL_ERROR; } } static byte[] generateMask() { // SecureRandom is not thread-safe so need to make sure only one thread // uses it at a time. In theory, the pool could grow to the same size // as the number of request processing threads. In reality it will be // a lot smaller. // Get a SecureRandom from the pool SecureRandom sr = randoms.poll(); // If one isn't available, generate a new one if (sr == null) { try { sr = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { // Fall back to platform default sr = new SecureRandom(); } } // Generate the mask byte[] result = new byte[4]; sr.nextBytes(result); // Put the SecureRandom back in the poll randoms.add(sr); return result; } static Class<?> getMessageType(MessageHandler listener) { return Util.getGenericType(MessageHandler.class, listener.getClass()).getClazz(); } public static Class<?> getDecoderType(Class<? extends Decoder> decoder) { return Util.getGenericType(Decoder.class, decoder).getClazz(); } static Class<?> getEncoderType(Class<? extends Encoder> encoder) { return Util.getGenericType(Encoder.class, encoder).getClazz(); } private static <T> TypeResult getGenericType(Class<T> type, Class<? extends T> clazz) { // Look to see if this class implements the interface of interest // Get all the interfaces Type[] interfaces = clazz.getGenericInterfaces(); for (Type iface : interfaces) { // Only need to check interfaces that use generics if (iface instanceof ParameterizedType) { ParameterizedType pi = (ParameterizedType) iface; // Look for the interface of interest if (pi.getRawType() instanceof Class) { if (type.isAssignableFrom((Class<?>) pi.getRawType())) { return getTypeParameter( clazz, pi.getActualTypeArguments()[0]); } } } } // Interface not found on this class. Look at the superclass. @SuppressWarnings("unchecked") Class<? extends T> superClazz = (Class<? extends T>) clazz.getSuperclass(); TypeResult superClassTypeResult = getGenericType(type, superClazz); int dimension = superClassTypeResult.getDimension(); if (superClassTypeResult.getIndex() == -1 && dimension == 0) { // Superclass implements interface and defines explicit type for // the interface of interest return superClassTypeResult; } if (superClassTypeResult.getIndex() > -1) { // Superclass implements interface and defines unknown type for // the interface of interest // Map that unknown type to the generic types defined in this class ParameterizedType superClassType = (ParameterizedType) clazz.getGenericSuperclass(); TypeResult result = getTypeParameter(clazz, superClassType.getActualTypeArguments()[ superClassTypeResult.getIndex()]); result.incrementDimension(superClassTypeResult.getDimension()); if (result.getClazz() != null && result.getDimension() > 0) { superClassTypeResult = result; } else { return result; } } if (superClassTypeResult.getDimension() > 0) { StringBuilder className = new StringBuilder(); for (int i = 0; i < dimension; i++) { className.append('['); } className.append('L'); className.append(superClassTypeResult.getClazz().getCanonicalName()); className.append(';'); Class<?> arrayClazz; try { arrayClazz = Class.forName(className.toString()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } return new TypeResult(arrayClazz, -1, 0); } // Error will be logged further up the call stack return null; } /* * For a generic parameter, return either the Class used or if the type * is unknown, the index for the type in definition of the class */ private static TypeResult getTypeParameter(Class<?> clazz, Type argType) { if (argType instanceof Class<?>) { return new TypeResult((Class<?>) argType, -1, 0); } else if (argType instanceof ParameterizedType) { return new TypeResult((Class<?>)((ParameterizedType) argType).getRawType(), -1, 0); } else if (argType instanceof GenericArrayType) { Type arrayElementType = ((GenericArrayType) argType).getGenericComponentType(); TypeResult result = getTypeParameter(clazz, arrayElementType); result.incrementDimension(1); return result; } else { TypeVariable<?>[] tvs = clazz.getTypeParameters(); for (int i = 0; i < tvs.length; i++) { if (tvs[i].equals(argType)) { return new TypeResult(null, i, 0); } } return null; } } public static boolean isPrimitive(Class<?> clazz) { if (clazz.isPrimitive()) { return true; } else if(clazz.equals(Boolean.class) || clazz.equals(Byte.class) || clazz.equals(Character.class) || clazz.equals(Double.class) || clazz.equals(Float.class) || clazz.equals(Integer.class) || clazz.equals(Long.class) || clazz.equals(Short.class)) { return true; } return false; } public static Object coerceToType(Class<?> type, String value) { if (type.equals(String.class)) { return value; } else if (type.equals(boolean.class) || type.equals(Boolean.class)) { return Boolean.valueOf(value); } else if (type.equals(byte.class) || type.equals(Byte.class)) { return Byte.valueOf(value); } else if (value.length() == 1 && (type.equals(char.class) || type.equals(Character.class))) { return Character.valueOf(value.charAt(0)); } else if (type.equals(double.class) || type.equals(Double.class)) { return Double.valueOf(value); } else if (type.equals(float.class) || type.equals(Float.class)) { return Float.valueOf(value); } else if (type.equals(int.class) || type.equals(Integer.class)) { return Integer.valueOf(value); } else if (type.equals(long.class) || type.equals(Long.class)) { return Long.valueOf(value); } else if (type.equals(short.class) || type.equals(Short.class)) { return Short.valueOf(value); } else { throw new IllegalArgumentException(sm.getString( "util.invalidType", value, type.getName())); } } public static List<DecoderEntry> getDecoders( Class<? extends Decoder>[] decoderClazzes) throws DeploymentException{ List<DecoderEntry> result = new ArrayList<>(); for (Class<? extends Decoder> decoderClazz : decoderClazzes) { // Need to instantiate decoder to ensure it is valid and that // deployment can be failed if it is not @SuppressWarnings("unused") Decoder instance; try { instance = decoderClazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException( sm.getString("pojoMethodMapping.invalidDecoder", decoderClazz.getName()), e); } DecoderEntry entry = new DecoderEntry( Util.getDecoderType(decoderClazz), decoderClazz); result.add(entry); } return result; } public static Set<MessageHandlerResult> getMessageHandlers( MessageHandler listener, EndpointConfig endpointConfig, Session session) { Class<?> target = Util.getMessageType(listener); // Will never be more than 2 types Set<MessageHandlerResult> results = new HashSet<>(2); // Simple cases - handlers already accepts one of the types expected by // the frame handling code if (String.class.isAssignableFrom(target)) { MessageHandlerResult result = new MessageHandlerResult(listener, MessageHandlerResultType.TEXT); results.add(result); } else if (ByteBuffer.class.isAssignableFrom(target)) { MessageHandlerResult result = new MessageHandlerResult(listener, MessageHandlerResultType.BINARY); results.add(result); } else if (PongMessage.class.isAssignableFrom(target)) { MessageHandlerResult result = new MessageHandlerResult(listener, MessageHandlerResultType.PONG); results.add(result); // Relatively simple cases - handler needs wrapping but no decoder to // convert it to one of the types expected by the frame handling code } else if (byte[].class.isAssignableFrom(target)) { MessageHandlerResult result = new MessageHandlerResult( new PojoMessageHandlerWholeBinary(listener, getOnMessageMethod(listener), session, endpointConfig, null, new Object[1], 0, true, -1, false, -1), MessageHandlerResultType.BINARY); results.add(result); } else if (InputStream.class.isAssignableFrom(target)) { MessageHandlerResult result = new MessageHandlerResult( new PojoMessageHandlerWholeBinary(listener, getOnMessageMethod(listener), session, endpointConfig, null, new Object[1], 0, true, -1, true, -1), MessageHandlerResultType.BINARY); results.add(result); } else if (Reader.class.isAssignableFrom(target)) { MessageHandlerResult result = new MessageHandlerResult( new PojoMessageHandlerWholeText(listener, getOnMessageMethod(listener), session, endpointConfig, null, new Object[1], 0, true, -1, -1), MessageHandlerResultType.TEXT); results.add(result); } else { // More complex case - listener that requires a decoder DecoderMatch decoderMatch; try { List<Class<? extends Decoder>> decoders = endpointConfig.getDecoders(); @SuppressWarnings("unchecked") List<DecoderEntry> decoderEntries = getDecoders( decoders.toArray(new Class[decoders.size()])); decoderMatch = new DecoderMatch(target, decoderEntries); } catch (DeploymentException e) { throw new IllegalArgumentException(e); } Method m = getOnMessageMethod(listener); if (decoderMatch.getBinaryDecoders().size() > 0) { MessageHandlerResult result = new MessageHandlerResult( new PojoMessageHandlerWholeBinary(listener, m, session, endpointConfig, decoderMatch.getBinaryDecoders(), new Object[1], 0, false, -1, false, -1), MessageHandlerResultType.BINARY); results.add(result); } if (decoderMatch.getTextDecoders().size() > 0) { MessageHandlerResult result = new MessageHandlerResult( new PojoMessageHandlerWholeText(listener, m, session, endpointConfig, decoderMatch.getTextDecoders(), new Object[1], 0, false, -1, -1), MessageHandlerResultType.TEXT); results.add(result); } } if (results.size() == 0) { throw new IllegalArgumentException( sm.getString("wsSession.unknownHandler", listener, target)); } return results; } private static Method getOnMessageMethod(MessageHandler listener) { try { return listener.getClass().getMethod("onMessage", Object.class); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException( sm.getString("util.invalidMessageHandler"), e); } } public static class DecoderMatch { private final List<Class<? extends Decoder>> textDecoders = new ArrayList<>(); private final List<Class<? extends Decoder>> binaryDecoders = new ArrayList<>(); public DecoderMatch(Class<?> target, List<DecoderEntry> decoderEntries) { for (DecoderEntry decoderEntry : decoderEntries) { if (decoderEntry.getClazz().isAssignableFrom(target)) { if (Binary.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (BinaryStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { binaryDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else if (Text.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // willDecode() method means this decoder may or may not // decode a message so need to carry on checking for // other matches } else if (TextStream.class.isAssignableFrom( decoderEntry.getDecoderClazz())) { textDecoders.add(decoderEntry.getDecoderClazz()); // Stream decoders have to process the message so no // more decoders can be matched break; } else { throw new IllegalArgumentException( sm.getString("util.unknownDecoderType")); } } } } public List<Class<? extends Decoder>> getTextDecoders() { return textDecoders; } public List<Class<? extends Decoder>> getBinaryDecoders() { return binaryDecoders; } public boolean hasMatches() { return (textDecoders.size() > 0) || (binaryDecoders.size() > 0); } } private static class TypeResult { private final Class<?> clazz; private final int index; private int dimension; public TypeResult(Class<?> clazz, int index, int dimension) { this.clazz= clazz; this.index = index; this.dimension = dimension; } public Class<?> getClazz() { return clazz; } public int getIndex() { return index; } public int getDimension() { return dimension; } public void incrementDimension(int inc) { dimension += inc; } } }
apache-2.0
SiphonSquirrel/jepperscore
scrapers/scraper-common/src/main/java/jepperscore/scraper/common/rcon/RconClient.java
518
package jepperscore.scraper.common.rcon; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * This interface provides the functions for talking to a game's RCON server. * @author Chuck * */ public interface RconClient { /** * Sends a command to the RCON server. * @param command The command to send. * @return The response from the command. */ @CheckForNull String[] sendCommand(@Nonnull String command); /** * Disconnects any open RCON session. */ void disconnect(); }
apache-2.0
blackcathacker/kc.preclean
coeus-code/src/main/java/org/kuali/coeus/common/budget/framework/period/SaveBudgetPeriodRule.java
1082
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.kuali.coeus.common.budget.framework.period; import org.kuali.rice.krad.rules.rule.BusinessRule; public interface SaveBudgetPeriodRule extends BusinessRule { /** * Rule invoked upon adding a budget period * <code>{@link org.kuali.coeus.common.budget.framework.core.BudgetDocument}</code> * * @return boolean */ public boolean processSaveBudgetPeriodBusinessRules(SaveBudgetPeriodEvent saveBudgetPeriodEvent); }
apache-2.0
rcarlosdasilva/weixin
src/main/java/io/github/rcarlosdasilva/weixin/model/request/media/MediaGetTemporaryWithHqAudioRequest.java
721
package io.github.rcarlosdasilva.weixin.model.request.media; import io.github.rcarlosdasilva.weixin.common.ApiAddress; import io.github.rcarlosdasilva.weixin.model.request.base.BasicWeixinRequest; public class MediaGetTemporaryWithHqAudioRequest extends BasicWeixinRequest { private String mediaId; public MediaGetTemporaryWithHqAudioRequest() { this.path = ApiAddress.URL_MEDIA_TEMPORARY_GET_HQ_AUDIO; } public void setMediaId(String mediaId) { this.mediaId = mediaId; } @Override public String toString() { return new StringBuilder(this.path).append("?access_token=").append(this.accessToken) .append("&media_id=").append(this.mediaId).toString(); } }
apache-2.0
inbloom/secure-data-service
sli/dashboard/src/test/java/org/slc/sli/dashboard/web/unit/interceptor/SessionCheckInterceptorTest.java
3264
/* * Copyright 2012-2013 inBloom, Inc. and its affiliates. * * 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.slc.sli.dashboard.web.unit.interceptor; import static org.junit.Assert.assertEquals; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.slc.sli.dashboard.client.RESTClient; import org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint; import org.slc.sli.dashboard.util.SecurityUtil; import org.slc.sli.dashboard.web.interceptor.SessionCheckInterceptor; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.context.ContextConfiguration; import com.google.gson.JsonObject; /** * * @author svankina * */ @RunWith(PowerMockRunner.class) @PrepareForTest({ SecurityUtil.class }) @ContextConfiguration(locations = { "/application-context.xml" }) public class SessionCheckInterceptorTest { @Test public void testPreHandle() throws Exception { SessionCheckInterceptor scInterceptor = new SessionCheckInterceptor(); PowerMockito.mockStatic(SecurityUtil.class); PowerMockito.when(SecurityUtil.getToken()).thenReturn("sravan"); MockHttpServletRequest request = new MockHttpServletRequest() { public HttpSession getSession() { return new MockHttpSession(); } public Cookie[] getCookies() { Cookie c = new Cookie(SLIAuthenticationEntryPoint.DASHBOARD_COOKIE, "fake"); return new Cookie[]{c}; } public String getRequestURI() { return "fake_uri"; } }; MockHttpServletResponse response = new MockHttpServletResponse() { public void sendRedirect(String url) { assertEquals(url, "fake_uri"); } }; RESTClient restClient = new RESTClient() { public JsonObject sessionCheck(String token) { JsonObject json = new JsonObject(); json.addProperty("authenticated", false); return json; } }; scInterceptor.setRestClient(restClient); assertEquals(scInterceptor.preHandle(request, response, null), false); } }
apache-2.0
real-logic/Agrona
agrona/src/test/java/org/agrona/collections/IntArrayQueueTest.java
4747
/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.agrona.collections; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class IntArrayQueueTest { @Test public void shouldDefaultInitialise() { final IntArrayQueue queue = new IntArrayQueue(); assertTrue(queue.isEmpty()); assertEquals(0, queue.size()); assertEquals(IntArrayQueue.MIN_CAPACITY, queue.capacity()); } @Test public void shouldOfferThenPoll() { final IntArrayQueue queue = new IntArrayQueue(); final Integer element = 7; queue.offer(7); assertEquals(1, queue.size()); assertEquals(element, queue.poll()); assertNull(queue.poll()); } @Test public void shouldForEachWithoutBoxing() { final IntArrayQueue queue = new IntArrayQueue(); final IntArrayList expected = new IntArrayList(); for (int i = 0; i < 20; i++) { queue.offerInt(i); expected.addInt(i); } final IntArrayList actual = new IntArrayList(); queue.forEachInt(actual::addInt); assertEquals(expected, actual); } @Test public void shouldClear() { final IntArrayQueue queue = new IntArrayQueue(); for (int i = 0; i < 7; i++) { queue.offerInt(i); } queue.removeInt(); queue.clear(); assertEquals(0, queue.size()); } @Test public void shouldOfferThenPollWithoutBoxing() { final IntArrayQueue queue = new IntArrayQueue(); final int count = 20; for (int i = 0; i < count; i++) { queue.offerInt(i); } assertFalse(queue.isEmpty()); assertEquals(count, queue.size()); for (int i = 0; i < count; i++) { assertEquals(i, queue.pollInt()); } assertTrue(queue.isEmpty()); assertEquals(0, queue.size()); } @Test public void shouldPeek() { final int nullValue = -1; final IntArrayQueue queue = new IntArrayQueue(nullValue); assertEquals(nullValue, queue.nullValue()); assertNull(queue.peek()); final Integer element = 7; queue.offer(element); assertEquals(element, queue.peek()); } @Test public void shouldPeekWithoutBoxing() { final int nullValue = -1; final IntArrayQueue queue = new IntArrayQueue(nullValue); assertEquals(nullValue, queue.peekInt()); final int element = 7; queue.offerInt(element); assertEquals(element, queue.peekInt()); } @Test public void shouldIterate() { final IntArrayQueue queue = new IntArrayQueue(); final int count = 20; for (int i = 0; i < count; i++) { queue.offerInt(i); } final IntArrayQueue.IntIterator iterator = queue.iterator(); for (int i = 0; i < count; i++) { assertTrue(iterator.hasNext()); assertEquals(Integer.valueOf(i), iterator.next()); } assertFalse(iterator.hasNext()); } @Test public void shouldIterateWithoutBoxing() { final IntArrayQueue queue = new IntArrayQueue(); final int count = 20; for (int i = 0; i < count; i++) { queue.offerInt(i); } final IntArrayQueue.IntIterator iterator = queue.iterator(); for (int i = 0; i < count; i++) { assertTrue(iterator.hasNext()); assertEquals(i, iterator.nextValue()); } assertFalse(iterator.hasNext()); } @Test public void shouldIterateEmptyQueue() { final IntArrayQueue queue = new IntArrayQueue(); for (final int ignore : queue) { fail("Should be empty"); } final int count = 20; for (int i = 0; i < count; i++) { queue.offerInt(i); queue.removeInt(); } for (final int ignore : queue) { fail("Should be empty"); } } }
apache-2.0
lorban/ehcache3
impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java
22169
/* * Copyright Terracotta, 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.ehcache.impl.internal.store.disk; import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePool; import org.ehcache.config.ResourceType; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.service.CacheManagerProviderService; import org.ehcache.core.statistics.DefaultStatisticsService; import org.ehcache.core.store.StoreConfigurationImpl; import org.ehcache.spi.resilience.StoreAccessException; import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome; import org.ehcache.CachePersistenceException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration; import org.ehcache.impl.internal.store.offheap.portability.AssertingOffHeapValueHolderPortability; import org.ehcache.impl.internal.store.offheap.portability.OffHeapValueHolderPortability; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.executor.OnDemandExecutionService; import org.ehcache.impl.internal.persistence.TestDiskResourceService; import org.ehcache.impl.internal.store.offheap.AbstractOffHeapStore; import org.ehcache.impl.internal.store.offheap.AbstractOffHeapStoreTest; import org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider; import org.ehcache.core.spi.time.SystemTimeSource; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.ServiceLocator; import org.ehcache.core.spi.store.Store; import org.ehcache.impl.internal.util.UnmatchedResourceType; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.ehcache.spi.serialization.SerializationProvider; import org.ehcache.spi.serialization.Serializer; import org.ehcache.spi.serialization.UnsupportedTypeException; import org.ehcache.core.spi.service.FileBasedPersistenceContext; import org.ehcache.spi.persistence.PersistableResourceService.PersistenceSpaceIdentifier; import org.ehcache.test.MockitoUtil; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Answers; import org.mockito.Mockito; import org.terracotta.context.query.Matcher; import org.terracotta.context.query.Query; import org.terracotta.context.query.QueryBuilder; import org.terracotta.statistics.OperationStatistic; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static java.util.Collections.EMPTY_LIST; import static java.util.Collections.singleton; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.persistence; import static org.ehcache.config.builders.ExpiryPolicyBuilder.noExpiration; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.ehcache.config.units.MemoryUnit.MB; import static org.ehcache.core.spi.ServiceLocator.dependencySet; import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_DISK_SEGMENTS; import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_WRITER_CONCURRENCY; import static org.ehcache.impl.internal.spi.TestServiceProvider.providerContaining; import static org.ehcache.test.MockitoUtil.mock; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.terracotta.context.ContextManager.nodeFor; import static org.terracotta.context.query.Matchers.attributes; import static org.terracotta.context.query.Matchers.context; import static org.terracotta.context.query.Matchers.hasAttribute; public class OffHeapDiskStoreTest extends AbstractOffHeapStoreTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public final TestDiskResourceService diskResourceService = new TestDiskResourceService(); @Test public void testRecovery() throws StoreAccessException, IOException { OffHeapDiskStore<String, String> offHeapDiskStore = createAndInitStore(SystemTimeSource.INSTANCE, noExpiration()); try { offHeapDiskStore.put("key1", "value1"); assertThat(offHeapDiskStore.get("key1"), notNullValue()); OffHeapDiskStore.Provider.close(offHeapDiskStore); OffHeapDiskStore.Provider.init(offHeapDiskStore); assertThat(offHeapDiskStore.get("key1"), notNullValue()); } finally { destroyStore(offHeapDiskStore); } } @Test public void testRecoveryFailureWhenValueTypeChangesToIncompatibleClass() throws Exception { OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider(); ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider) .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build(); serviceLocator.startAllServices(); CacheConfiguration<Long, String> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class); when(cacheConfiguration.getResourcePools()).thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build()); PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache", cacheConfiguration); { @SuppressWarnings("unchecked") Store.Configuration<Long, String> storeConfig1 = MockitoUtil.mock(Store.Configuration.class); when(storeConfig1.getKeyType()).thenReturn(Long.class); when(storeConfig1.getValueType()).thenReturn(String.class); when(storeConfig1.getResourcePools()).thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder() .disk(10, MB) .build()); when(storeConfig1.getDispatcherConcurrency()).thenReturn(1); OffHeapDiskStore<Long, String> offHeapDiskStore1 = provider.createStore(storeConfig1, space); provider.initStore(offHeapDiskStore1); destroyStore(offHeapDiskStore1); } { @SuppressWarnings("unchecked") Store.Configuration<Long, Serializable> storeConfig2 = MockitoUtil.mock(Store.Configuration.class); when(storeConfig2.getKeyType()).thenReturn(Long.class); when(storeConfig2.getValueType()).thenReturn(Serializable.class); when(storeConfig2.getResourcePools()).thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder() .disk(10, MB) .build()); when(storeConfig2.getDispatcherConcurrency()).thenReturn(1); when(storeConfig2.getClassLoader()).thenReturn(ClassLoader.getSystemClassLoader()); OffHeapDiskStore<Long, Serializable> offHeapDiskStore2 = provider.createStore(storeConfig2, space); try { provider.initStore(offHeapDiskStore2); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } destroyStore(offHeapDiskStore2); } } @Test public void testRecoveryWithArrayType() throws Exception { OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider(); ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider) .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build(); serviceLocator.startAllServices(); CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class); when(cacheConfiguration.getResourcePools()).thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build()); PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache", cacheConfiguration); { @SuppressWarnings("unchecked") Store.Configuration<Long, Object[]> storeConfig1 = MockitoUtil.mock(Store.Configuration.class); when(storeConfig1.getKeyType()).thenReturn(Long.class); when(storeConfig1.getValueType()).thenReturn(Object[].class); when(storeConfig1.getResourcePools()).thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder() .disk(10, MB) .build()); when(storeConfig1.getDispatcherConcurrency()).thenReturn(1); OffHeapDiskStore<Long, Object[]> offHeapDiskStore1 = provider.createStore(storeConfig1, space); provider.initStore(offHeapDiskStore1); destroyStore(offHeapDiskStore1); } { @SuppressWarnings("unchecked") Store.Configuration<Long, Object[]> storeConfig2 = MockitoUtil.mock(Store.Configuration.class); when(storeConfig2.getKeyType()).thenReturn(Long.class); when(storeConfig2.getValueType()).thenReturn(Object[].class); when(storeConfig2.getResourcePools()).thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder() .disk(10, MB) .build()); when(storeConfig2.getDispatcherConcurrency()).thenReturn(1); when(storeConfig2.getClassLoader()).thenReturn(ClassLoader.getSystemClassLoader()); OffHeapDiskStore<Long, Object[]> offHeapDiskStore2 = provider.createStore(storeConfig2, space); provider.initStore(offHeapDiskStore2); destroyStore(offHeapDiskStore2); } } @Test public void testProvidingOffHeapDiskStoreConfiguration() throws Exception { OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider(); ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider) .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build(); serviceLocator.startAllServices(); CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class); when(cacheConfiguration.getResourcePools()).thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build()); PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache", cacheConfiguration); @SuppressWarnings("unchecked") Store.Configuration<Long, Object[]> storeConfig1 = MockitoUtil.mock(Store.Configuration.class); when(storeConfig1.getKeyType()).thenReturn(Long.class); when(storeConfig1.getValueType()).thenReturn(Object[].class); when(storeConfig1.getResourcePools()).thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder() .disk(10, MB) .build()); when(storeConfig1.getDispatcherConcurrency()).thenReturn(1); OffHeapDiskStore<Long, Object[]> offHeapDiskStore1 = provider.createStore( storeConfig1, space, new OffHeapDiskStoreConfiguration("pool", 2, 4)); assertThat(offHeapDiskStore1.getThreadPoolAlias(), is("pool")); assertThat(offHeapDiskStore1.getWriterConcurrency(), is(2)); assertThat(offHeapDiskStore1.getDiskSegments(), is(4)); } @Override protected OffHeapDiskStore<String, String> createAndInitStore(final TimeSource timeSource, final ExpiryPolicy<? super String, ? super String> expiry) { try { SerializationProvider serializationProvider = new DefaultSerializationProvider(null); serializationProvider.start(providerContaining(diskResourceService)); ClassLoader classLoader = getClass().getClassLoader(); Serializer<String> keySerializer = serializationProvider.createKeySerializer(String.class, classLoader); Serializer<String> valueSerializer = serializationProvider.createValueSerializer(String.class, classLoader); StoreConfigurationImpl<String, String> storeConfiguration = new StoreConfigurationImpl<>(String.class, String.class, null, classLoader, expiry, null, 0, true, keySerializer, valueSerializer, null, false); OffHeapDiskStore<String, String> offHeapStore = new OffHeapDiskStore<String, String>( getPersistenceContext(), new OnDemandExecutionService(), null, DEFAULT_WRITER_CONCURRENCY, DEFAULT_DISK_SEGMENTS, storeConfiguration, timeSource, new TestStoreEventDispatcher<>(), MB.toBytes(1), new DefaultStatisticsService()) { @Override protected OffHeapValueHolderPortability<String> createValuePortability(Serializer<String> serializer) { return new AssertingOffHeapValueHolderPortability<>(serializer); } }; OffHeapDiskStore.Provider.init(offHeapStore); return offHeapStore; } catch (UnsupportedTypeException e) { throw new AssertionError(e); } } @Override protected OffHeapDiskStore<String, byte[]> createAndInitStore(TimeSource timeSource, ExpiryPolicy<? super String, ? super byte[]> expiry, EvictionAdvisor<? super String, ? super byte[]> evictionAdvisor) { try { SerializationProvider serializationProvider = new DefaultSerializationProvider(null); serializationProvider.start(providerContaining(diskResourceService)); ClassLoader classLoader = getClass().getClassLoader(); Serializer<String> keySerializer = serializationProvider.createKeySerializer(String.class, classLoader); Serializer<byte[]> valueSerializer = serializationProvider.createValueSerializer(byte[].class, classLoader); StoreConfigurationImpl<String, byte[]> storeConfiguration = new StoreConfigurationImpl<>(String.class, byte[].class, evictionAdvisor, getClass().getClassLoader(), expiry, null, 0, true, keySerializer, valueSerializer, null, false); OffHeapDiskStore<String, byte[]> offHeapStore = new OffHeapDiskStore<String, byte[]>( getPersistenceContext(), new OnDemandExecutionService(), null, DEFAULT_WRITER_CONCURRENCY, DEFAULT_DISK_SEGMENTS, storeConfiguration, timeSource, new TestStoreEventDispatcher<>(), MB.toBytes(1), new DefaultStatisticsService()) { @Override protected OffHeapValueHolderPortability<byte[]> createValuePortability(Serializer<byte[]> serializer) { return new AssertingOffHeapValueHolderPortability<>(serializer); } }; OffHeapDiskStore.Provider.init(offHeapStore); return offHeapStore; } catch (UnsupportedTypeException e) { throw new AssertionError(e); } } @Override protected void destroyStore(AbstractOffHeapStore<?, ?> store) { try { OffHeapDiskStore.Provider.close((OffHeapDiskStore<?, ?>) store); } catch (IOException e) { throw new AssertionError(e); } } @Test public void testStoreInitFailsWithoutLocalPersistenceService() throws Exception { OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider(); try { dependencySet().with(provider).build(); fail("IllegalStateException expected"); } catch (IllegalStateException e) { assertThat(e.getMessage(), containsString("Failed to find provider with satisfied dependency set for interface" + " org.ehcache.core.spi.service.DiskResourceService")); } } @Test @SuppressWarnings("unchecked") public void testAuthoritativeRank() throws Exception { OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider(); assertThat(provider.rankAuthority(ResourceType.Core.DISK, EMPTY_LIST), is(1)); assertThat(provider.rankAuthority(new UnmatchedResourceType(), EMPTY_LIST), is(0)); } @Test public void testRank() throws Exception { OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider(); assertRank(provider, 1, ResourceType.Core.DISK); assertRank(provider, 0, ResourceType.Core.HEAP); assertRank(provider, 0, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP); assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.HEAP); assertRank(provider, 0, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); assertRank(provider, 0, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP); assertRank(provider, 0, (ResourceType<ResourcePool>) new UnmatchedResourceType()); assertRank(provider, 0, ResourceType.Core.DISK, new UnmatchedResourceType()); } private void assertRank(final Store.Provider provider, final int expectedRank, final ResourceType<?>... resources) { assertThat(provider.rank( new HashSet<>(Arrays.asList(resources)), Collections.emptyList()), is(expectedRank)); } private FileBasedPersistenceContext getPersistenceContext() { try { CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class); when(cacheConfiguration.getResourcePools()).thenReturn(newResourcePoolsBuilder().disk(1, MB, false).build()); PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache", cacheConfiguration); return diskResourceService.createPersistenceContextWithin(space, "store"); } catch (CachePersistenceException e) { throw new AssertionError(e); } } @Test public void diskStoreShrinkingTest() throws Exception { try (CacheManager manager = newCacheManagerBuilder() .with(persistence(temporaryFolder.newFolder("disk-stores").getAbsolutePath())) .build(true)) { CacheConfigurationBuilder<Long, CacheValue> cacheConfigurationBuilder = newCacheConfigurationBuilder(Long.class, CacheValue.class, heap(1000).offheap(10, MB).disk(20, MB)) .withLoaderWriter(new CacheLoaderWriter<Long, CacheValue>() { @Override public CacheValue load(Long key) { return null; } @Override public Map<Long, CacheValue> loadAll(Iterable<? extends Long> keys) { return Collections.emptyMap(); } @Override public void write(Long key, CacheValue value) { } @Override public void writeAll(Iterable<? extends Map.Entry<? extends Long, ? extends CacheValue>> entries) { } @Override public void delete(Long key) { } @Override public void deleteAll(Iterable<? extends Long> keys) { } }); Cache<Long, CacheValue> cache = manager.createCache("test", cacheConfigurationBuilder); for (long i = 0; i < 100000; i++) { cache.put(i, new CacheValue((int) i)); } Callable<Void> task = () -> { Random rndm = new Random(); long start = System.nanoTime(); while (System.nanoTime() < start + TimeUnit.SECONDS.toNanos(5)) { Long k = key(rndm); switch (rndm.nextInt(4)) { case 0: { CacheValue v = value(rndm); cache.putIfAbsent(k, v); break; } case 1: { CacheValue nv = value(rndm); CacheValue ov = value(rndm); cache.put(k, ov); cache.replace(k, nv); break; } case 2: { CacheValue nv = value(rndm); CacheValue ov = value(rndm); cache.put(k, ov); cache.replace(k, ov, nv); break; } case 3: { CacheValue v = value(rndm); cache.put(k, v); cache.remove(k, v); break; } } } return null; }; ExecutorService executor = Executors.newCachedThreadPool(); try { executor.invokeAll(Collections.nCopies(4, task)); } finally { executor.shutdown(); } Query invalidateAllQuery = QueryBuilder.queryBuilder() .descendants() .filter(context(attributes(hasAttribute("tags", new Matcher<Set<String>>() { @Override protected boolean matchesSafely(Set<String> object) { return object.contains("OffHeap"); } })))) .filter(context(attributes(hasAttribute("name", "invalidateAll")))) .ensureUnique() .build(); @SuppressWarnings("unchecked") OperationStatistic<LowerCachingTierOperationsOutcome.InvalidateAllOutcome> invalidateAll = (OperationStatistic<LowerCachingTierOperationsOutcome.InvalidateAllOutcome>) invalidateAllQuery .execute(singleton(nodeFor(cache))) .iterator() .next() .getContext() .attributes() .get("this"); assertThat(invalidateAll.sum(), is(0L)); } } private Long key(Random rndm) { return (long) rndm.nextInt(100000); } private CacheValue value(Random rndm) { return new CacheValue(rndm.nextInt(100000)); } public static class CacheValue implements Serializable { private static final long serialVersionUID = 1L; private final int value; private final byte[] padding; public CacheValue(int value) { this.value = value; this.padding = new byte[800]; } @Override public int hashCode() { return value; } public boolean equals(Object o) { if (o instanceof CacheValue) { return value == ((CacheValue) o).value; } else { return false; } } } }
apache-2.0
gaorx/Roboq
Roboq/src/me/code4fun/roboq/PostRunnableCallback.java
611
package me.code4fun.roboq; import android.os.Handler; /** * @since 0.1 */ public abstract class PostRunnableCallback extends HandlerCallback { public PostRunnableCallback(Handler handler) { super(handler); } @Override public void onResponse(Request req, Response resp, Exception error) { Runnable r = createRunnable(req, resp, error); if (r != null) processRunnable(r); } protected abstract Runnable createRunnable(Request req, Response resp, Exception error); protected void processRunnable(Runnable r) { handler.post(r); } }
apache-2.0
OpenVnmrJ/OpenVnmrJ
src/vnmrj/src/vnmr/bo/StatementHistory.java
27390
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ package vnmr.bo; import java.util.*; import java.io.*; import vnmr.util.*; import vnmr.ui.*; import vnmr.ui.shuf.*; /** * There is one StatementHistory object per objType. The StatementHistory * object maintains a buffer of statements. Each "statement" is simply * represented by a hashtable. * * <p>StatementHistory has one additional responsibility, and that is, * remembering the last statement of a particular statement type. * * @author Mark Cao */ public class StatementHistory implements Serializable { // ==== static variables /** maximum buffer length */ private static final int MAXLEN = 20; // ==== instance variables /** shuffler service */ private ShufflerService shufflerService; /** History buffer. Place latest statements at end. */ private Vector buffer=null; /** Buffer pointer. The buffer pointer points at the statement * currently being displayed. If the buffer is empty, the pointer * has value -1. */ private int bufPointer=-1; /** The last buffer that was appended. */ private int lastAppendedBuf; /** Most previous active bufPointer when append occured */ private int prevBufPointer; /** statement listeners */ private Vector listeners; /** previous statements, keyed by type */ private Hashtable prevStatements; /** object type this StatementHistory is used for. */ private String objectType; /** * constructor * @param shufflerService */ public StatementHistory(ShufflerService shufflerService, String objType, Vector buf, int bufPointer){ this.shufflerService = shufflerService; objectType = objType; this.buffer = buf; this.bufPointer = bufPointer; if(buffer == null) buffer = new Vector(MAXLEN); listeners = new Vector(); prevStatements = new Hashtable(); } // StatementHistory() /** * Add a statement listener. Such listeners are notified of new * statements. * @param listener listener */ public void addStatementListener(StatementListener listener) { listeners.addElement(listener); } // addStatementListener /** * Append a statement to buffer. Note that append automatically * resets the buffer pointer to the end. * @param statement statement */ public void append(Hashtable statement) { if(statement == null) return; // prior to appending, delete a statement if necessary while (buffer.size() >= MAXLEN) { buffer.removeElementAt(0); } buffer.addElement(statement.clone()); bufPointer = buffer.size() - 1; String statementType = (String)statement.get("Statement_type"); prevStatements.put(statementType, statement); for (Enumeration en = listeners.elements(); en.hasMoreElements(); ) { StatementListener listener = (StatementListener)en.nextElement(); listener.newStatement(statement); listener.backMovabilityChanged(canGoBack()); listener.forwardMovabilityChanged(canGoForward()); } } // append() /** * Take a copy of the current statement, modify it with the given * key/value pair, and append the new (modified) statement to the * history buffer. * @param key key * @param value value */ public void append(String key, Object value) { String str1, str2, str3; String val; Hashtable statement = getCurrentStatement(); if (statement != null) { Hashtable newStatement = (Hashtable)statement.clone(); newStatement.put(key, value); // If Attribute- set AttrValue- to its prev value or all. // If Attribute- or AttrValue-, save the previous 3 values. if(key.startsWith("Attribute-")) { // If Attribute- set AttrValue- to its prev value or all. String digit = key.substring(key.length() -1); String attrVal = new String("AttrValue-" + digit); String inVal = value.toString(); String attrPrev = inVal.concat("-prev-1"); // Try to get the prev value for this Attribute val = (String) statement.get(attrPrev); if(val != null) { // Yes, use it. newStatement.put(attrVal, val); } else // No prev value, default to all newStatement.put(attrVal, "all"); // Only save if it has changed since the last time we // saved a prev-1 // Create the three key names for the Attribute- str1 = key.concat("-prev-1"); str2 = key.concat("-prev-2"); str3 = key.concat("-prev-3"); String prevAttrName = (String)statement.get(key); String prevVal = (String) statement.get(str1); if(prevVal == null || !prevAttrName.equals(prevVal)) { // rotate -1 and -2 up to -2 and -3 if they exist. val = (String)newStatement.get(str2); if(val != null) newStatement.put(str3, val); val = (String)newStatement.get(str1); if(val != null) newStatement.put(str2, val); // Save the previous one. newStatement.put(str1, prevAttrName); } // Also save the AttrValue- value we had. // Create the three key names using the actual attr name str1 = prevAttrName.concat("-prev-1"); str2 = prevAttrName.concat("-prev-2"); str3 = prevAttrName.concat("-prev-3"); // Get the current value of AttrValue- String curVal = (String) statement.get(attrVal); // Get the value of the -prev-1 entry prevVal = (String) statement.get(str1); // Only save the values if it has changed since the // last time we saved a prev-1 if(prevVal == null || !curVal.equals(prevVal)) { // rotate -1 and -2 up to -2 and -3 if they exist. val = (String)newStatement.get(str2); if(val != null) newStatement.put(str3, val); val = (String)newStatement.get(str1); if(val != null) newStatement.put(str2, val); // Save the previous one. newStatement.put(str1, curVal); } } else if(key.startsWith("AttrValue-")) { // Get the Attribute- name itself that goes with // this AttrValue- String digit = key.substring(key.length() -1); String attr = new String("Attribute-" + digit); String attrName = (String) newStatement.get(attr); // Create the three key names using the actual attr name str1 = attrName.concat("-prev-1"); str2 = attrName.concat("-prev-2"); str3 = attrName.concat("-prev-3"); // rotate -1 and -2 up to -2 and -3 if they exist. val = (String)newStatement.get(str2); if(val != null) newStatement.put(str3, val); val = (String)newStatement.get(str1); if(val != null) newStatement.put(str2, val); newStatement.put(str1, value); } append(newStatement); } } // append() /** * Append the last statement of the given type. Note that memory * of these previous statements is not limited to what's in the * buffer. * * <p>If the given statementType has not been encountered before, * query a default value from the shuffler service. * @param statementType statement type */ public void appendLastOfType(String statementType) { prevBufPointer = bufPointer; Hashtable statement = (Hashtable)prevStatements.get(statementType); if (statement == null) statement = shufflerService.getDefaultStatement(statementType); append(statement); // If no new statement, don't allow anything to be removed later. if(prevBufPointer == bufPointer) lastAppendedBuf = -1; else lastAppendedBuf = bufPointer; } // appendLastOfType() /****************************************************************** * Summary: Return the last statement of this type. * *****************************************************************/ public Hashtable getLastOfType(String statementType) { prevBufPointer = bufPointer; Hashtable statement = (Hashtable)prevStatements.get(statementType); if (statement == null) statement = shufflerService.getDefaultStatement(statementType); return statement; } /************************************************** <pre> * Summary: Remove the last statement which was appended and restore * statement to where it was before the last append. * </pre> **************************************************/ public void removeLastAppendedStatement() { // Go to the most previous position if(prevBufPointer >= 0 && prevBufPointer < buffer.size()) goToStatementByIndex(prevBufPointer); // Remove the last appended statement. if(lastAppendedBuf >= 0 && lastAppendedBuf < buffer.size()) buffer.removeElementAt(lastAppendedBuf); // Fix the forward and backward arrows. for (Enumeration en = listeners.elements(); en.hasMoreElements(); ) { StatementListener listener = (StatementListener)en.nextElement(); listener.backMovabilityChanged(canGoBack()); listener.forwardMovabilityChanged(canGoForward()); } } /************************************************** <pre> * Summary: Switch to the given statement without effecting the history. * </pre> **************************************************/ public void goToStatementByIndex(int newBufPointer) { if (newBufPointer >= 0 && newBufPointer < buffer.size()) { bufPointer = newBufPointer; updateWithoutNewHistory(); } } public int getNumInHistory() { return buffer.size(); } /** * is it possible to go back? * @return boolean */ public boolean canGoBack() { return bufPointer > 0; } // canGoBack() /** * Move the buffer pointer to the previous statement. */ public void goBack() { if (bufPointer > 0) { bufPointer--; Hashtable statement = (Hashtable)buffer.elementAt(bufPointer); for (Enumeration en = listeners.elements(); en.hasMoreElements(); ) { StatementListener listener = (StatementListener)en.nextElement(); listener.newStatement(statement); listener.backMovabilityChanged(canGoBack()); listener.forwardMovabilityChanged(canGoForward()); } } } // goBack() /** * is it possible to go forward? * @return boolean */ public boolean canGoForward() { return bufPointer + 1 < buffer.size(); } // canGoForward() /** * Go forward to the next statement and return that statement. * Return null if going forward is not possible. * @return next statement */ public void goForward() { if (bufPointer + 1 < buffer.size()) { bufPointer++; Hashtable statement = (Hashtable)buffer.elementAt(bufPointer); for (Enumeration en = listeners.elements(); en.hasMoreElements(); ) { StatementListener listener = (StatementListener)en.nextElement(); listener.newStatement(statement); listener.backMovabilityChanged(canGoBack()); listener.forwardMovabilityChanged(canGoForward()); } } } // goForward() /** * get current statement * @return current */ public Hashtable getCurrentStatement() { if (0 <= bufPointer && bufPointer < buffer.size()) { return (Hashtable)buffer.elementAt(bufPointer); } else { String statementType = shufflerService.getDefaultStatementType(); return shufflerService.getDefaultStatement(statementType); } } // getCurrentStatement() /** * Update the current shuffler panels, but no change has taken * place that caused the need for a history update. This is * primarily for use after adding or removing a file from the * DB so that we can get the panels updated. */ public void updateWithoutNewHistory() { StatementListener listener; Enumeration en; // If the locator is not being used, get out of here if(FillDBManager.locatorOff()) return; try { Hashtable statement = getCurrentStatement(); // If there is nothing in 'buffer', then append this one if(buffer.size() == 0) { append(statement); } // If there is already something in 'buffer', then we will have // the most recent one. So, do not append to history. else { for (en = listeners.elements(); en.hasMoreElements();) { listener =(StatementListener)en.nextElement(); listener.newStatement(statement); listener.backMovabilityChanged(canGoBack()); listener.forwardMovabilityChanged(canGoForward()); } } } catch(Exception e) { Messages.postError("Problem updating locator statement"); Messages.writeStackTrace(e); } } /** * Update the current shuffler panels, but no change has taken * place that caused the need for a history update. This is * primarily for use after adding or removing a file from the * DB so that we can get the panels updated. Disallow statements * ending in 'internal use'. They are for temp internal use and * should not be gone to as a default history. */ public void updateWithoutNewHistoryNotInternal() { StatementListener listener; Enumeration en; Hashtable statement=null; boolean foundOne=false; try { // Get the current statement in case the buffer is empty statement = getCurrentStatement(); // Start by looking at the current Statement, if it has a // menuString of 'by objtype', go to the next previous one // and test it until we find one which is not by that name. while (bufPointer >= 0 && buffer.size() > 0) { statement = (Hashtable)buffer.elementAt(bufPointer); String menuString = (String) statement.get("MenuString"); if(!menuString.endsWith("internal use")) { // We found one that is not 'internal use', so break out // of here and use this statement. foundOne = true; break; } // try the next previous one bufPointer--; } // If there is already something in 'buffer', then we will have // the most recent one. So, do not append to history. if(foundOne) { for (en = listeners.elements(); en.hasMoreElements();) { listener =(StatementListener)en.nextElement(); listener.newStatement(statement); listener.backMovabilityChanged(canGoBack()); listener.forwardMovabilityChanged(canGoForward()); } } else { // If we did not find one, then default to the standard // default statement. String statementType =shufflerService.getDefaultStatementType(); statement = shufflerService.getDefaultStatement(statementType); append(statement); } } catch(Exception e) { Messages.postError("Problem updating locator statement"); Messages.writeStackTrace(e); } } /** Write out the current shuffler statement to a named file. * This one is for backwards compatibility before label was used */ public void writeCurStatement(String name) { // Simply pass name as the label as well as the name itself. writeCurStatement(name, name); } /** Write out the current shuffler statement to a named file. * */ public void writeCurStatement(String name, String label) { Hashtable curStatement; //String dir, shufDir; String filepath; String filename; ObjectOutput out; //File file; curStatement = getCurrentStatement(); //dir = System.getProperty("userdir"); //shufDir = new String(dir + "/shuffler"); //file = new File(shufDir); // If this directory does not exist, make it. //if(!file.exists()) { // file.mkdir(); //} if(label != null) { // Set a value in the statement with the label string curStatement.put("MenuLabel", label); } // Convert all spaces in the name to '_'. filename = name.replace(' ', '_'); //filepath = new String (shufDir + "/" + filename); filepath=FileUtil.savePath("USER/LOCATOR/"+filename); try { out = new ObjectOutputStream(new FileOutputStream(filepath)); // Write it out. out.writeObject(curStatement); out.close(); } catch (Exception e) { Messages.writeStackTrace(e); } // Update the spotter menu. for (Enumeration en = listeners.elements(); en.hasMoreElements(); ) { StatementListener listener = (StatementListener)en.nextElement(); listener.saveListChanged(); } // The following is not really necessary, but when a programmable // button is pressed and a new statement is written, there is no // visible sign that it has completed. The following at least // causes a blink of the locator table area to let the user know // something has happened. SessionShare sshare = ResultTable.getSshare(); StatementHistory history = sshare.statementHistory(); if(history != null) history.updateWithoutNewHistory(); } /** Remove the Saved Statement by this name from the disk */ public void removeSavedStatement(String name) { String filepath; String filename; // Convert all spaces in the name to '_'. filename = name.replace(' ', '_'); //filepath = new String (shufDir + "/" + filename); filepath=FileUtil.savePath("USER/LOCATOR/"+filename); // Remove the file File file = new File(filepath); file.delete(); // Update the spotter menu. for (Enumeration en = listeners.elements(); en.hasMoreElements(); ) { StatementListener listener = (StatementListener)en.nextElement(); listener.saveListChanged(); } } /** Read saved shuffler statement by this name. * */ public void readNamedStatement(String name) { String filepath; String filename; ObjectInputStream in; //String dir; Hashtable statement; //dir = System.getProperty("userdir"); // Convert all spaces in the name to '_'. filename = name.replace(' ', '_'); //filepath = new String (dir + "/shuffler/" + filename); filepath=FileUtil.savePath("USER/LOCATOR/"+filename); if(filepath==null) return; try { in = new ObjectInputStream(new FileInputStream(filepath)); // Read it in. statement = (Hashtable) in.readObject(); in.close(); } catch (Exception e) { Messages.writeStackTrace(e); Messages.postWarning("This button has not been programmed. " + "\n Press and hold 3 sec to program it with the current " + "Locator search."); return; } // Get the objType for the statement we read in. // Check to see if it is different from the StatementHistory we // are in now. String objType = (String)statement.get("ObjectType"); if(!objType.equals(objectType)) { // If the object type has changed, set the new object type as // the active one and get the StatementHistory for this object // type. then call append for That StatementHistory object // and not the one we are in now. SessionShare sshare = ResultTable.getSshare(); LocatorHistory lh = sshare.getLocatorHistory(); // Set History Active Object type to this type. lh.setActiveObjType(objType); // Now get history for this type. StatementHistory history = sshare.statementHistory(); // If history is null, this button may not have been programmed if(history == null) { Messages.postWarning("This button has not been programmed. " + "\n Press and hold 3 sec to program it with the current " + "Locator search."); return; } // append to history list and make it the current statement. history.append(statement); } else // append to history list and make it the current statement. append(statement); } /** Get the list of named statements from the directory 'shuffler'. * * Return an ArrayList of ArrayLists where the inside one is * a list of length 2 containing the filename and menu label as * the two items. */ public ArrayList getNamedStatementList() { File[] list; String dir; String statementType; File file; Hashtable statement; LocatorHistory lHistory; ArrayList allObjTypes; /** list of custom saved statement menu entries in the form of a list of nameNlabel items */ ArrayList menuList=null; /** list of 2 items, filename and menu label */ ArrayList nameNlabel; ObjectInputStream in; dir=FileUtil.savePath("USER/LOCATOR"); file = new File (dir); list = file.listFiles(); // If the directory does not exist, return an empty list if(list == null) list = new File[0]; SessionShare sshare = ResultTable.getSshare(); lHistory = sshare.getLocatorHistory(); ArrayList allStatementTypes = lHistory.getallStatementTypes(); menuList = new ArrayList(); // Go thru the files and only keep the ones with spotter types // which are current. for(int i=0; i < list.length; i++) { try { in = new ObjectInputStream(new FileInputStream(list[i])); // Read it in. statement = (Hashtable) in.readObject(); in.close(); } catch (ClassNotFoundException e) { continue; } catch (FileNotFoundException e) { continue; } catch (IOException e) { continue; } // This value is of the form objtype/menu_string // eg. 'vnmr_data/by type' statementType = (String)statement.get("Statement_type"); // Does this Type exist currently? // Need all satementTypes, in the form objtype/menu_string // combine objType and menuString if (allStatementTypes.contains(statementType)) { // Yes, add this to the menu list // Use the value of MenuLabel for the menu here, unless // is has the key string of '**skip**', then do not put // this item into the menu. String menuLabel = (String)statement.get("MenuLabel"); if(menuLabel == null) { nameNlabel = new ArrayList(2); String name = list[i].getName(); // Convert all '_' to spaces. name = name.replace('_', ' '); nameNlabel.add(name); nameNlabel.add(name); menuList.add(nameNlabel); } else if(!menuLabel.equals("**skip**")) { nameNlabel = new ArrayList(2); String name = list[i].getName(); // Convert all '_' to spaces. name = name.replace('_', ' '); nameNlabel.add(name); nameNlabel.add(menuLabel); menuList.add(nameNlabel); } // else if **skip**, do not add it. } } return menuList; } public ShufflerService getShufflerService() { return shufflerService; } public Vector getBuffer() { return buffer; } public int getBufPointer() { return bufPointer; } /************************************************** <pre> * Summary: Update the column width values for the current statement. * * The args are fraction of the total width, where the sum of * the 4 widths = 1.0. * * </pre> **************************************************/ public void updateCurStatementWidth(double colWidth0, double colWidth1, double colWidth2, double colWidth3) { Hashtable curStatement; curStatement = getCurrentStatement(); curStatement.put("colWidth0", new Double(colWidth0)); curStatement.put("colWidth1", new Double(colWidth1)); curStatement.put("colWidth2", new Double(colWidth2)); curStatement.put("colWidth3", new Double(colWidth3)); } } // class StatementHistory
apache-2.0
FabioNgo/sound-cloud-player
Source Code/src/ngo/music/soundcloudplayer/boundary/fragment/real/SCSongSearchFragment.java
1109
package ngo.music.soundcloudplayer.boundary.fragment.real; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import ngo.music.soundcloudplayer.R; import ngo.music.soundcloudplayer.adapters.SCSongAdapter; import ngo.music.soundcloudplayer.adapters.SCSearchSongAdapter; import ngo.music.soundcloudplayer.boundary.MusicPlayerMainActivity; import ngo.music.soundcloudplayer.boundary.fragment.abstracts.SoundCloudExploreFragment; import ngo.music.soundcloudplayer.controller.SongController; import ngo.music.soundcloudplayer.general.Constants; import ngo.music.soundcloudplayer.service.MusicPlayerService; public class SCSongSearchFragment extends SoundCloudExploreFragment { public SCSongSearchFragment() { // TODO Auto-generated constructor stub super(); query = MusicPlayerMainActivity.query; } @Override protected int getCategory() { // TODO Auto-generated method stub return SEARCH; } }
apache-2.0
jdahlstrom/vaadin.react
server/src/test/java/com/vaadin/server/react/harnesses/SyncFlowTestHarness.java
566
package com.vaadin.server.react.harnesses; import java.util.function.Supplier; import com.vaadin.server.react.Flow; import com.vaadin.server.react.Subscriber; public class SyncFlowTestHarness extends FlowTestHarness { @Override @SuppressWarnings("unchecked") public <T> Flow<T> flow(T... actual) { return Flow.of(actual); } @Override public <T> void verifyFlow(Flow<T> flow, Supplier<Subscriber<? super T>> subSup) { for (int i = 0; i < 2; i++) { verifyFlow(flow, subSup.get()); } } }
apache-2.0
hortonworks/cloudbreak
cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/validation/FileSystemValidationResult.java
453
package com.sequenceiq.cloudbreak.cloud.event.validation; import com.sequenceiq.cloudbreak.cloud.event.CloudPlatformResult; public class FileSystemValidationResult extends CloudPlatformResult { public FileSystemValidationResult(Long resourceId) { super(resourceId); } public FileSystemValidationResult(String statusReason, Exception errorDetails, Long resourceId) { super(statusReason, errorDetails, resourceId); } }
apache-2.0
gustavoorsi/searchahouse.com
searchahouse/src/main/java/edu/searchahouse/endpoints/aop/ExceptionControllerAdvice.java
4756
package edu.searchahouse.endpoints.aop; import java.util.stream.Collectors; import org.springframework.dao.DuplicateKeyException; import org.springframework.hateoas.VndErrors; import org.springframework.http.HttpStatus; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import edu.searchahouse.exceptions.EntityNotFoundException; import edu.searchahouse.exceptions.EntityNotUpdatedException; //@formatter:off /** * * Advice class that check if a rest endpoint throws an exception and change the response code and message according. * * * 1XX: Information * * 2XX: Success * 200 - OK: * -> Everything worked * 201 - Created (mostly use for POST): * -> The server has successfully created a new resource * -> Newly created resource's location returned in the Location header * 202 - Accepted: * -> The server has accepted the request, but it is not yet complete * -> A location to determine the request's current status can be returned in the location header * 3XX: Redirection * * 4XX: Client Error * 400 - Bad Request: * -> Malformed syntax * -> Should not be repeated without modification * 401 - Unauthorized: * -> Authentication is required * -> Includes a WWW-Authentication header * 403 - Forbidden: * -> Server has understood but refused to honor the request * -> Should not be repeated without modification * 404 - Not Found: * -> The server cannot find a resource matching a URI * 406 - Not Acceptable: * -> The server can only return response entities that do not match the client's Accept header * 409 - Conflict: * -> The resource is in a state that is in conflict with the request * -> Client should attempt to rectify the conflict and then resubmit the request * 422 - Unprocessable Entity: * -> The resource already exist. * * 5XX: Server Error (if the app is responding a 500 code it means we have a bug or didn't thought all possible scenarios.) * * * @author Gustavo Orsi * */ // @formatter:on @ControllerAdvice public class ExceptionControllerAdvice { /** * * Catch <code>EntityNotFoundException</code> exception thrown by any endpoint and change the return code. * * @param ex * @return */ @ResponseBody @ExceptionHandler(EntityNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) VndErrors courseNotFoundExceptionHandler(EntityNotFoundException ex) { return new VndErrors(HttpStatus.NOT_FOUND.getReasonPhrase(), ex.getMessage()); } /** * * Catch <code>IllegalArgumentException</code> exception thrown by any endpoint and change the return code. * * @param ex * @return */ @ResponseBody @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) VndErrors illegalArgumentExceptionHandler(IllegalArgumentException ex) { return new VndErrors(HttpStatus.BAD_REQUEST.getReasonPhrase(), ex.getMessage()); } /** * * * @param ex * @return */ @ResponseBody @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) VndErrors internalServerErrorHandler(Exception ex) { return new VndErrors(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), ex.getLocalizedMessage()); } /** * * * @param ex * @return */ @ResponseBody @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) VndErrors internalServerErrorHandler(MethodArgumentNotValidException ex) { String errorMessage = ex.getBindingResult().getAllErrors() .stream() .map( ObjectError::getDefaultMessage ) .collect( Collectors.toList() ).toString(); return new VndErrors(HttpStatus.BAD_REQUEST.getReasonPhrase(), errorMessage ); } /** * * * @param ex * @return */ @ResponseBody @ExceptionHandler(EntityNotUpdatedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) VndErrors entityNotUpdatedExceptionHandler(EntityNotUpdatedException ex) { return new VndErrors(HttpStatus.BAD_REQUEST.getReasonPhrase(), ex.getLocalizedMessage()); } /** * * * @param ex * @return */ @ResponseBody @ExceptionHandler(DuplicateKeyException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) VndErrors duplicateFieldHandler(DuplicateKeyException ex) { return new VndErrors(HttpStatus.BAD_REQUEST.getReasonPhrase(), ex.getMostSpecificCause().getLocalizedMessage()); } }
apache-2.0
find-happiness/android-aishang
app/src/main/java/com/aishang/app/ui/MyBuyAndSale/RentAdapter.java
2867
package com.aishang.app.ui.MyBuyAndSale; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import com.aishang.app.R; import com.aishang.app.data.model.JRentalListResult; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; /** * Created by song on 2016/2/17. */ public class RentAdapter extends RecyclerView.Adapter<RentAdapter.ViewHolder> { List<JRentalListResult.RentalItem> items; @Inject public RentAdapter() { items = new ArrayList<JRentalListResult.RentalItem>(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_buy, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { final JRentalListResult.RentalItem item = items.get(position); holder.name.setText(item.getName()); holder.address.setText("地址:" + item.getAddress()); holder.roomNum.setText("房间数:"); if (item.getStatus() == 0) { holder.status.setText("状态"); } else { holder.status.setText("状态"); } holder.rentDate.setText( "出租时间:" + item.getResStartDate().split(" ")[0] + "-" + item.getResEndDate().split(" ")[0]); holder.price.setText(item.getPriceText()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //intentToDetail(holder.getContext(), hotel.getHotelID(), hotel.getName()); } }); } @Override public int getItemCount() { return items.size(); } public List<JRentalListResult.RentalItem> getItems() { return items; } public void setItems(List<JRentalListResult.RentalItem> items) { this.items = items; } private void intentToDetail(Context ctx, int hotelID, String hotelName) { } /** * This class contains all butterknife-injected Views & Layouts from layout file * 'item_my_order.xml' * for easy to all layout elements. * * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers * (http://github.com/avast) */ static class ViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.name) TextView name; @Bind(R.id.status) TextView status; @Bind(R.id.room_num) TextView roomNum; @Bind(R.id.rent_date) TextView rentDate; @Bind(R.id.address) TextView address; @Bind(R.id.price) TextView price; public Context getContext() { return this.itemView.getContext(); } ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } }
apache-2.0
jasonstack/cassandra
src/java/org/apache/cassandra/hints/HintsDispatchExecutor.java
11594
/* * 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.cassandra.hints; import java.io.File; import java.util.Map; import java.util.UUID; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BooleanSupplier; import java.util.function.Predicate; import java.util.function.Supplier; import com.google.common.util.concurrent.RateLimiter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor; import org.apache.cassandra.concurrent.NamedThreadFactory; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.io.FSReadError; import org.apache.cassandra.locator.InetAddressAndPort; import org.apache.cassandra.service.StorageService; /** * A multi-threaded (by default) executor for dispatching hints. * * Most of dispatch is triggered by {@link HintsDispatchTrigger} running every ~10 seconds. */ final class HintsDispatchExecutor { private static final Logger logger = LoggerFactory.getLogger(HintsDispatchExecutor.class); private final File hintsDirectory; private final ExecutorService executor; private final AtomicBoolean isPaused; private final Predicate<InetAddressAndPort> isAlive; private final Map<UUID, Future> scheduledDispatches; HintsDispatchExecutor(File hintsDirectory, int maxThreads, AtomicBoolean isPaused, Predicate<InetAddressAndPort> isAlive) { this.hintsDirectory = hintsDirectory; this.isPaused = isPaused; this.isAlive = isAlive; scheduledDispatches = new ConcurrentHashMap<>(); executor = new JMXEnabledThreadPoolExecutor(maxThreads, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), new NamedThreadFactory("HintsDispatcher", Thread.MIN_PRIORITY), "internal"); } /* * It's safe to terminate dispatch in process and to deschedule dispatch. */ void shutdownBlocking() { scheduledDispatches.clear(); executor.shutdownNow(); try { executor.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { throw new AssertionError(e); } } boolean isScheduled(HintsStore store) { return scheduledDispatches.containsKey(store.hostId); } Future dispatch(HintsStore store) { return dispatch(store, store.hostId); } Future dispatch(HintsStore store, UUID hostId) { /* * It is safe to perform dispatch for the same host id concurrently in two or more threads, * however there is nothing to win from it - so we don't. * * Additionally, having just one dispatch task per host id ensures that we'll never violate our per-destination * rate limit, without having to share a ratelimiter between threads. * * It also simplifies reasoning about dispatch sessions. */ return scheduledDispatches.computeIfAbsent(hostId, uuid -> executor.submit(new DispatchHintsTask(store, hostId))); } Future transfer(HintsCatalog catalog, Supplier<UUID> hostIdSupplier) { return executor.submit(new TransferHintsTask(catalog, hostIdSupplier)); } void completeDispatchBlockingly(HintsStore store) { Future future = scheduledDispatches.get(store.hostId); try { if (future != null) future.get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } } void interruptDispatch(UUID hostId) { Future future = scheduledDispatches.remove(hostId); if (null != future) future.cancel(true); } private final class TransferHintsTask implements Runnable { private final HintsCatalog catalog; /* * Supplies target hosts to stream to. Generally returns the one the DynamicSnitch thinks is closest. * We use a supplier here to be able to get a new host if the current one dies during streaming. */ private final Supplier<UUID> hostIdSupplier; private TransferHintsTask(HintsCatalog catalog, Supplier<UUID> hostIdSupplier) { this.catalog = catalog; this.hostIdSupplier = hostIdSupplier; } @Override public void run() { UUID hostId = hostIdSupplier.get(); InetAddressAndPort address = StorageService.instance.getEndpointForHostId(hostId); logger.info("Transferring all hints to {}: {}", address, hostId); if (transfer(hostId)) return; logger.warn("Failed to transfer all hints to {}: {}; will retry in {} seconds", address, hostId, 10); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } hostId = hostIdSupplier.get(); logger.info("Transferring all hints to {}: {}", address, hostId); if (!transfer(hostId)) { logger.error("Failed to transfer all hints to {}: {}", address, hostId); throw new RuntimeException("Failed to transfer all hints to " + hostId); } } private boolean transfer(UUID hostId) { catalog.stores() .map(store -> new DispatchHintsTask(store, hostId)) .forEach(Runnable::run); return !catalog.hasFiles(); } } private final class DispatchHintsTask implements Runnable { private final HintsStore store; private final UUID hostId; private final RateLimiter rateLimiter; DispatchHintsTask(HintsStore store, UUID hostId) { this.store = store; this.hostId = hostId; // rate limit is in bytes per second. Uses Double.MAX_VALUE if disabled (set to 0 in cassandra.yaml). // max rate is scaled by the number of nodes in the cluster (CASSANDRA-5272). // the goal is to bound maximum hints traffic going towards a particular node from the rest of the cluster, // not total outgoing hints traffic from this node - this is why the rate limiter is not shared between // all the dispatch tasks (as there will be at most one dispatch task for a particular host id at a time). int nodesCount = Math.max(1, StorageService.instance.getTokenMetadata().getSizeOfAllEndpoints() - 1); int throttleInKB = DatabaseDescriptor.getHintedHandoffThrottleInKB() / nodesCount; this.rateLimiter = RateLimiter.create(throttleInKB == 0 ? Double.MAX_VALUE : throttleInKB * 1024); } public void run() { try { dispatch(); } finally { scheduledDispatches.remove(hostId); } } private void dispatch() { while (true) { if (isPaused.get()) break; HintsDescriptor descriptor = store.poll(); if (descriptor == null) break; try { if (!dispatch(descriptor)) break; } catch (FSReadError e) { logger.error(String.format("Failed to dispatch hints file %s: file is corrupted", descriptor.fileName()), e); store.cleanUp(descriptor); store.markCorrupted(descriptor); throw e; } } } /* * Will return true if dispatch was successful, false if we hit a failure (destination node went down, for example). */ private boolean dispatch(HintsDescriptor descriptor) { logger.trace("Dispatching hints file {}", descriptor.fileName()); InetAddressAndPort address = StorageService.instance.getEndpointForHostId(hostId); if (address != null) return deliver(descriptor, address); // address == null means the target no longer exist; find new home for each hint entry. convert(descriptor); return true; } private boolean deliver(HintsDescriptor descriptor, InetAddressAndPort address) { File file = new File(hintsDirectory, descriptor.fileName()); InputPosition offset = store.getDispatchOffset(descriptor); BooleanSupplier shouldAbort = () -> !isAlive.test(address) || isPaused.get(); try (HintsDispatcher dispatcher = HintsDispatcher.create(file, rateLimiter, address, descriptor.hostId, shouldAbort)) { if (offset != null) dispatcher.seek(offset); if (dispatcher.dispatch()) { store.delete(descriptor); store.cleanUp(descriptor); logger.info("Finished hinted handoff of file {} to endpoint {}: {}", descriptor.fileName(), address, hostId); return true; } else { store.markDispatchOffset(descriptor, dispatcher.dispatchPosition()); store.offerFirst(descriptor); logger.info("Finished hinted handoff of file {} to endpoint {}: {}, partially", descriptor.fileName(), address, hostId); return false; } } } // for each hint in the hints file for a node that isn't part of the ring anymore, write RF hints for each replica private void convert(HintsDescriptor descriptor) { File file = new File(hintsDirectory, descriptor.fileName()); try (HintsReader reader = HintsReader.open(file, rateLimiter)) { reader.forEach(page -> page.hintsIterator().forEachRemaining(HintsService.instance::writeForAllReplicas)); store.delete(descriptor); store.cleanUp(descriptor); logger.info("Finished converting hints file {}", descriptor.fileName()); } } } public boolean isPaused() { return isPaused.get(); } public boolean hasScheduledDispatches() { return !scheduledDispatches.isEmpty(); } }
apache-2.0
vladmihalcea/high-performance-java-persistence
core/src/test/java/com/vladmihalcea/book/hpjp/spring/transaction/jta/dao/GenericDAO.java
237
package com.vladmihalcea.book.hpjp.spring.transaction.jta.dao; import java.io.Serializable; /** * @author Vlad Mihalcea */ public interface GenericDAO<T, ID extends Serializable> { T findById(ID id); T persist(T entity); }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/ProductPackageItemErrorReason.java
1475
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ProductPackageItemError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ProductPackageItemError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="ARCHIVED_PRODUCT_NOT_ALLOWED"/> * &lt;enumeration value="INACTIVE_MANDATORY_PRODUCT_NOT_ALLOWED"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ProductPackageItemError.Reason") @XmlEnum public enum ProductPackageItemErrorReason { /** * * Add a archived product to product package is not allowed. * * */ ARCHIVED_PRODUCT_NOT_ALLOWED, /** * * Inactive mandatory product is not allowed in active product package. * * */ INACTIVE_MANDATORY_PRODUCT_NOT_ALLOWED, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static ProductPackageItemErrorReason fromValue(String v) { return valueOf(v); } }
apache-2.0
Distrotech/fop
src/java/org/apache/fop/fo/FObj.java
29191
/* * 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. */ /* $Id$ */ package org.apache.fop.fo; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.apache.xmlgraphics.util.QName; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.extensions.ExtensionAttachment; import org.apache.fop.fo.flow.Marker; import org.apache.fop.fo.properties.PropertyMaker; /** * Base class for representation of formatting objects and their processing. * All standard formatting object classes extend this class. */ public abstract class FObj extends FONode implements Constants { /** the list of property makers */ private static final PropertyMaker[] PROPERTY_LIST_TABLE = FOPropertyMapping.getGenericMappings(); /** pointer to the descendant subtree */ protected FONode firstChild; /** pointer to the end of the descendant subtree */ protected FONode lastChild; /** The list of extension attachments, null if none */ private List<ExtensionAttachment> extensionAttachments = null; /** The map of foreign attributes, null if none */ private Map<QName, String> foreignAttributes = null; /** Used to indicate if this FO is either an Out Of Line FO (see rec) * or a descendant of one. Used during FO validation. */ private boolean isOutOfLineFODescendant = false; /** Markers added to this element. */ private Map markers = null; private int bidiLevel = -1; // The value of properties relevant for all fo objects private String id = null; // End of property values /** * Create a new formatting object. * * @param parent the parent node */ public FObj(FONode parent) { super(parent); // determine if isOutOfLineFODescendant should be set if (parent != null && parent instanceof FObj) { if (((FObj) parent).getIsOutOfLineFODescendant()) { isOutOfLineFODescendant = true; } else { int foID = getNameId(); if (foID == FO_FLOAT || foID == FO_FOOTNOTE || foID == FO_FOOTNOTE_BODY) { isOutOfLineFODescendant = true; } } } } /** {@inheritDoc} */ public FONode clone(FONode parent, boolean removeChildren) throws FOPException { FObj fobj = (FObj) super.clone(parent, removeChildren); if (removeChildren) { fobj.firstChild = null; } return fobj; } /** * Returns the PropertyMaker for a given property ID. * @param propId the property ID * @return the requested Property Maker */ public static PropertyMaker getPropertyMakerFor(int propId) { return PROPERTY_LIST_TABLE[propId]; } /** {@inheritDoc} */ public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { setLocator(locator); pList.addAttributesToList(attlist); if (!inMarker() || "marker".equals(elementName)) { bind(pList); } } /** * Create a default property list for this element. * {@inheritDoc} */ protected PropertyList createPropertyList(PropertyList parent, FOEventHandler foEventHandler) throws FOPException { return getBuilderContext().getPropertyListMaker().make(this, parent); } /** * Bind property values from the property list to the FO node. * Must be overridden in all FObj subclasses that have properties * applying to it. * @param pList the PropertyList where the properties can be found. * @throws FOPException if there is a problem binding the values */ public void bind(PropertyList pList) throws FOPException { id = pList.get(PR_ID).getString(); } /** * {@inheritDoc} * @throws FOPException FOP Exception */ protected void startOfNode() throws FOPException { if (id != null) { checkId(id); } } /** * Setup the id for this formatting object. * Most formatting objects can have an id that can be referenced. * This methods checks that the id isn't already used by another FO * * @param id the id to check * @throws ValidationException if the ID is already defined elsewhere * (strict validation only) */ private void checkId(String id) throws ValidationException { if (!inMarker() && !id.equals("")) { Set idrefs = getBuilderContext().getIDReferences(); if (!idrefs.contains(id)) { idrefs.add(id); } else { getFOValidationEventProducer().idNotUnique(this, getName(), id, true, locator); } } } /** * Returns Out Of Line FO Descendant indicator. * @return true if Out of Line FO or Out Of Line descendant, false otherwise */ boolean getIsOutOfLineFODescendant() { return isOutOfLineFODescendant; } /** {@inheritDoc}*/ protected void addChildNode(FONode child) throws FOPException { if (child.getNameId() == FO_MARKER) { addMarker((Marker) child); } else { ExtensionAttachment attachment = child.getExtensionAttachment(); if (attachment != null) { /* This removes the element from the normal children, * so no layout manager is being created for them * as they are only additional information. */ addExtensionAttachment(attachment); } else { if (firstChild == null) { firstChild = child; lastChild = child; } else { if (lastChild == null) { FONode prevChild = firstChild; while (prevChild.siblings != null && prevChild.siblings[1] != null) { prevChild = prevChild.siblings[1]; } FONode.attachSiblings(prevChild, child); } else { FONode.attachSiblings(lastChild, child); lastChild = child; } } } } } /** * Used by RetrieveMarker during Marker-subtree cloning * @param child the (cloned) child node * @param parent the (cloned) parent node * @throws FOPException when the child could not be added to the parent */ protected static void addChildTo(FONode child, FONode parent) throws FOPException { parent.addChildNode(child); } /** {@inheritDoc} */ public void removeChild(FONode child) { FONode nextChild = null; if (child.siblings != null) { nextChild = child.siblings[1]; } if (child == firstChild) { firstChild = nextChild; if (firstChild != null) { firstChild.siblings[0] = null; } } else { FONode prevChild = child.siblings[0]; prevChild.siblings[1] = nextChild; if (nextChild != null) { nextChild.siblings[0] = prevChild; } } if (child == lastChild) { if (child.siblings != null) { lastChild = siblings[0]; } else { lastChild = null; } } } /** * Find the nearest parent, grandparent, etc. FONode that is also an FObj * @return FObj the nearest ancestor FONode that is an FObj */ public FObj findNearestAncestorFObj() { FONode par = parent; while (par != null && !(par instanceof FObj)) { par = par.parent; } return (FObj) par; } /** * Check if this formatting object generates reference areas. * @return true if generates reference areas * TODO see if needed */ public boolean generatesReferenceAreas() { return false; } /** {@inheritDoc} */ public FONodeIterator getChildNodes() { if (hasChildren()) { return new FObjIterator(this); } return null; } /** * Indicates whether this formatting object has children. * @return true if there are children */ public boolean hasChildren() { return this.firstChild != null; } /** * Return an iterator over the object's childNodes starting * at the passed-in node (= first call to iterator.next() will * return childNode) * @param childNode First node in the iterator * @return A ListIterator or null if childNode isn't a child of * this FObj. */ public FONodeIterator getChildNodes(FONode childNode) { FONodeIterator it = getChildNodes(); if (it != null) { if (firstChild == childNode) { return it; } else { while (it.hasNext() && it.nextNode().siblings[1] != childNode) { //nop } if (it.hasNext()) { return it; } else { return null; } } } return null; } /** * Notifies a FObj that one of it's children is removed. * This method is subclassed by Block to clear the * firstInlineChild variable in case it doesn't generate * any areas (see addMarker()). * @param node the node that was removed */ void notifyChildRemoval(FONode node) { //nop } /** * Add the marker to this formatting object. * If this object can contain markers it checks that the marker * has a unique class-name for this object and that it is * the first child. * @param marker Marker to add. */ protected void addMarker(Marker marker) { String mcname = marker.getMarkerClassName(); if (firstChild != null) { // check for empty childNodes for (Iterator iter = getChildNodes(); iter.hasNext();) { FONode node = (FONode) iter.next(); if (node instanceof FObj || (node instanceof FOText && ((FOText) node).willCreateArea())) { getFOValidationEventProducer().markerNotInitialChild(this, getName(), mcname, locator); return; } else if (node instanceof FOText) { iter.remove(); notifyChildRemoval(node); } } } if (markers == null) { markers = new java.util.HashMap(); } if (!markers.containsKey(mcname)) { markers.put(mcname, marker); } else { getFOValidationEventProducer().markerNotUniqueForSameParent(this, getName(), mcname, locator); } } /** * @return true if there are any Markers attached to this object */ public boolean hasMarkers() { return markers != null && !markers.isEmpty(); } /** * @return the collection of Markers attached to this object */ public Map getMarkers() { return markers; } /** {@inheritDoc} */ protected String getContextInfoAlt() { StringBuffer sb = new StringBuffer(); if (getLocalName() != null) { sb.append(getName()); sb.append(", "); } if (hasId()) { sb.append("id=").append(getId()); return sb.toString(); } String s = gatherContextInfo(); if (s != null) { sb.append("\""); if (s.length() < 32) { sb.append(s); } else { sb.append(s.substring(0, 32)); sb.append("..."); } sb.append("\""); return sb.toString(); } else { return null; } } /** {@inheritDoc} */ protected String gatherContextInfo() { if (getLocator() != null) { return super.gatherContextInfo(); } else { ListIterator iter = getChildNodes(); if (iter == null) { return null; } StringBuffer sb = new StringBuffer(); while (iter.hasNext()) { FONode node = (FONode) iter.next(); String s = node.gatherContextInfo(); if (s != null) { if (sb.length() > 0) { sb.append(", "); } sb.append(s); } } return (sb.length() > 0 ? sb.toString() : null); } } /** * Convenience method for validity checking. Checks if the * incoming node is a member of the "%block;" parameter entity * as defined in Sect. 6.2 of the XSL 1.0 & 1.1 Recommendations * * @param nsURI namespace URI of incoming node * @param lName local name (i.e., no prefix) of incoming node * @return true if a member, false if not */ protected boolean isBlockItem(String nsURI, String lName) { return (FO_URI.equals(nsURI) && ("block".equals(lName) || "table".equals(lName) || "table-and-caption".equals(lName) || "block-container".equals(lName) || "list-block".equals(lName) || "float".equals(lName) || isNeutralItem(nsURI, lName))); } /** * Convenience method for validity checking. Checks if the * incoming node is a member of the "%inline;" parameter entity * as defined in Sect. 6.2 of the XSL 1.0 & 1.1 Recommendations * * @param nsURI namespace URI of incoming node * @param lName local name (i.e., no prefix) of incoming node * @return true if a member, false if not */ protected boolean isInlineItem(String nsURI, String lName) { return (FO_URI.equals(nsURI) && ("bidi-override".equals(lName) || "character".equals(lName) || "external-graphic".equals(lName) || "instream-foreign-object".equals(lName) || "inline".equals(lName) || "inline-container".equals(lName) || "leader".equals(lName) || "page-number".equals(lName) || "page-number-citation".equals(lName) || "page-number-citation-last".equals(lName) || "basic-link".equals(lName) || ("multi-toggle".equals(lName) && (getNameId() == FO_MULTI_CASE || findAncestor(FO_MULTI_CASE) > 0)) || ("footnote".equals(lName) && !isOutOfLineFODescendant) || isNeutralItem(nsURI, lName))); } /** * Convenience method for validity checking. Checks if the * incoming node is a member of the "%block;" parameter entity * or "%inline;" parameter entity * @param nsURI namespace URI of incoming node * @param lName local name (i.e., no prefix) of incoming node * @return true if a member, false if not */ protected boolean isBlockOrInlineItem(String nsURI, String lName) { return (isBlockItem(nsURI, lName) || isInlineItem(nsURI, lName)); } /** * Convenience method for validity checking. Checks if the * incoming node is a member of the neutral item list * as defined in Sect. 6.2 of the XSL 1.0 & 1.1 Recommendations * @param nsURI namespace URI of incoming node * @param lName local name (i.e., no prefix) of incoming node * @return true if a member, false if not */ protected boolean isNeutralItem(String nsURI, String lName) { return (FO_URI.equals(nsURI) && ("multi-switch".equals(lName) || "multi-properties".equals(lName) || "wrapper".equals(lName) || (!isOutOfLineFODescendant && "float".equals(lName)) || "retrieve-marker".equals(lName) || "retrieve-table-marker".equals(lName))); } /** * Convenience method for validity checking. Checks if the * current node has an ancestor of a given name. * @param ancestorID ID of node name to check for (e.g., FO_ROOT) * @return number of levels above FO where ancestor exists, * -1 if not found */ protected int findAncestor(int ancestorID) { int found = 1; FONode temp = getParent(); while (temp != null) { if (temp.getNameId() == ancestorID) { return found; } found += 1; temp = temp.getParent(); } return -1; } /** * Clears the list of child nodes. */ public void clearChildNodes() { this.firstChild = null; } /** @return the "id" property. */ public String getId() { return id; } /** @return whether this object has an id set */ public boolean hasId() { return (id != null && id.length() > 0); } /** {@inheritDoc} */ public String getNamespaceURI() { return FOElementMapping.URI; } /** {@inheritDoc} */ public String getNormalNamespacePrefix() { return "fo"; } /** {@inheritDoc} */ public boolean isBidiRangeBlockItem() { String ns = getNamespaceURI(); String ln = getLocalName(); return !isNeutralItem(ns, ln) && isBlockItem(ns, ln); } /** * Recursively set resolved bidirectional level of FO (and its ancestors) if * and only if it is non-negative and if either the current value is reset (-1) * or the new value is less than the current value. * @param bidiLevel a non-negative bidi embedding level */ public void setBidiLevel(int bidiLevel) { assert bidiLevel >= 0; if ( bidiLevel >= 0 ) { if ( ( this.bidiLevel < 0 ) || ( bidiLevel < this.bidiLevel ) ) { this.bidiLevel = bidiLevel; if ( parent != null ) { FObj foParent = (FObj) parent; int parentBidiLevel = foParent.getBidiLevel(); if ( ( parentBidiLevel < 0 ) || ( bidiLevel < parentBidiLevel ) ) { foParent.setBidiLevel ( bidiLevel ); } } } } } /** * Obtain resolved bidirectional level of FO. * @return either a non-negative bidi embedding level or -1 * in case no bidi levels have been assigned */ public int getBidiLevel() { return bidiLevel; } /** * Obtain resolved bidirectional level of FO or nearest FO * ancestor that has a resolved level. * @return either a non-negative bidi embedding level or -1 * in case no bidi levels have been assigned to this FO or * any ancestor */ public int getBidiLevelRecursive() { for ( FONode fn = this; fn != null; fn = fn.getParent() ) { if ( fn instanceof FObj ) { int level = ( (FObj) fn).getBidiLevel(); if ( level >= 0 ) { return level; } } } return -1; } /** * Add a new extension attachment to this FObj. * (see org.apache.fop.fo.FONode for details) * * @param attachment the attachment to add. */ void addExtensionAttachment(ExtensionAttachment attachment) { if (attachment == null) { throw new NullPointerException( "Parameter attachment must not be null"); } if (extensionAttachments == null) { extensionAttachments = new java.util.ArrayList<ExtensionAttachment>(); } if (log.isDebugEnabled()) { log.debug("ExtensionAttachment of category " + attachment.getCategory() + " added to " + getName() + ": " + attachment); } extensionAttachments.add(attachment); } /** @return the extension attachments of this FObj. */ public List/*<ExtensionAttachment>*/ getExtensionAttachments() { if (extensionAttachments == null) { return Collections.EMPTY_LIST; } else { return extensionAttachments; } } /** @return true if this FObj has extension attachments */ public boolean hasExtensionAttachments() { return extensionAttachments != null; } /** * Adds a foreign attribute to this FObj. * @param attributeName the attribute name as a QName instance * @param value the attribute value */ public void addForeignAttribute(QName attributeName, String value) { /* TODO: Handle this over FOP's property mechanism so we can use * inheritance. */ if (attributeName == null) { throw new NullPointerException("Parameter attributeName must not be null"); } if (foreignAttributes == null) { foreignAttributes = new java.util.HashMap<QName, String>(); } foreignAttributes.put(attributeName, value); } /** @return the map of foreign attributes */ public Map getForeignAttributes() { if (foreignAttributes == null) { return Collections.EMPTY_MAP; } else { return foreignAttributes; } } /** {@inheritDoc} */ public String toString() { return (super.toString() + "[@id=" + this.id + "]"); } /** Basic {@link FONode.FONodeIterator} implementation */ public static class FObjIterator implements FONodeIterator { private static final int F_NONE_ALLOWED = 0; private static final int F_SET_ALLOWED = 1; private static final int F_REMOVE_ALLOWED = 2; private FONode currentNode; private final FObj parentNode; private int currentIndex; private int flags = F_NONE_ALLOWED; FObjIterator(FObj parent) { this.parentNode = parent; this.currentNode = parent.firstChild; this.currentIndex = 0; this.flags = F_NONE_ALLOWED; } /** {@inheritDoc} */ public FObj parentNode() { return parentNode; } /** {@inheritDoc} */ public Object next() { if (currentNode != null) { if (currentIndex != 0) { if (currentNode.siblings != null && currentNode.siblings[1] != null) { currentNode = currentNode.siblings[1]; } else { throw new NoSuchElementException(); } } currentIndex++; flags |= (F_SET_ALLOWED | F_REMOVE_ALLOWED); return currentNode; } else { throw new NoSuchElementException(); } } /** {@inheritDoc} */ public Object previous() { if (currentNode.siblings != null && currentNode.siblings[0] != null) { currentIndex--; currentNode = currentNode.siblings[0]; flags |= (F_SET_ALLOWED | F_REMOVE_ALLOWED); return currentNode; } else { throw new NoSuchElementException(); } } /** {@inheritDoc} */ public void set(Object o) { if ((flags & F_SET_ALLOWED) == F_SET_ALLOWED) { FONode newNode = (FONode) o; if (currentNode == parentNode.firstChild) { parentNode.firstChild = newNode; } else { FONode.attachSiblings(currentNode.siblings[0], newNode); } if (currentNode.siblings != null && currentNode.siblings[1] != null) { FONode.attachSiblings(newNode, currentNode.siblings[1]); } if (currentNode == parentNode.lastChild) { parentNode.lastChild = newNode; } } else { throw new IllegalStateException(); } } /** {@inheritDoc} */ public void add(Object o) { FONode newNode = (FONode) o; if (currentIndex == -1) { if (currentNode != null) { FONode.attachSiblings(newNode, currentNode); } parentNode.firstChild = newNode; currentIndex = 0; currentNode = newNode; if (parentNode.lastChild == null) { parentNode.lastChild = newNode; } } else { if (currentNode.siblings != null && currentNode.siblings[1] != null) { FONode.attachSiblings((FONode) o, currentNode.siblings[1]); } FONode.attachSiblings(currentNode, (FONode) o); if (currentNode == parentNode.lastChild) { parentNode.lastChild = newNode; } } flags &= F_NONE_ALLOWED; } /** {@inheritDoc} */ public boolean hasNext() { return (currentNode != null) && ((currentIndex == 0) || (currentNode.siblings != null && currentNode.siblings[1] != null)); } /** {@inheritDoc} */ public boolean hasPrevious() { return (currentIndex != 0) || (currentNode.siblings != null && currentNode.siblings[0] != null); } /** {@inheritDoc} */ public int nextIndex() { return currentIndex + 1; } /** {@inheritDoc} */ public int previousIndex() { return currentIndex - 1; } /** {@inheritDoc} */ public void remove() { if ((flags & F_REMOVE_ALLOWED) == F_REMOVE_ALLOWED) { parentNode.removeChild(currentNode); if (currentIndex == 0) { //first node removed currentNode = parentNode.firstChild; } else if (currentNode.siblings != null && currentNode.siblings[0] != null) { currentNode = currentNode.siblings[0]; currentIndex--; } else { currentNode = null; } flags &= F_NONE_ALLOWED; } else { throw new IllegalStateException(); } } /** {@inheritDoc} */ public FONode lastNode() { while (currentNode != null && currentNode.siblings != null && currentNode.siblings[1] != null) { currentNode = currentNode.siblings[1]; currentIndex++; } return currentNode; } /** {@inheritDoc} */ public FONode firstNode() { currentNode = parentNode.firstChild; currentIndex = 0; return currentNode; } /** {@inheritDoc} */ public FONode nextNode() { return (FONode) next(); } /** {@inheritDoc} */ public FONode previousNode() { return (FONode) previous(); } } }
apache-2.0
etirelli/jbpm-console-ng
jbpm-wb-human-tasks/jbpm-wb-human-tasks-client/src/main/java/org/jbpm/workbench/ht/client/editors/tasklogs/TaskLogsViewImpl.java
2080
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.jbpm.workbench.ht.client.editors.tasklogs; import java.util.List; import javax.enterprise.context.Dependent; import javax.enterprise.event.Event; import javax.inject.Inject; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.ui.Composite; import org.jboss.errai.common.client.dom.HTMLElement; import org.jboss.errai.common.client.dom.UnorderedList; import org.jboss.errai.ui.shared.api.annotations.DataField; import org.jboss.errai.ui.shared.api.annotations.Templated; import org.uberfire.workbench.events.NotificationEvent; import static org.jboss.errai.common.client.dom.DOMUtil.removeAllChildren; import static org.jboss.errai.common.client.dom.Window.getDocument; @Dependent @Templated(value = "TaskLogsViewImpl.html") public class TaskLogsViewImpl extends Composite implements TaskLogsPresenter.TaskLogsView { @Inject @DataField public UnorderedList logTextArea; @Inject private Event<NotificationEvent> notification; @Override public void displayNotification(String text) { notification.fire(new NotificationEvent(text)); } @Override public void setLogTextAreaText(final List<String> logs) { removeAllChildren(logTextArea); logs.forEach(log -> { HTMLElement li = getDocument().createElement("li"); li.setInnerHTML(SafeHtmlUtils.htmlEscape(log)); logTextArea.appendChild(li); }); } }
apache-2.0
DFTinc/cordova-plugin-onyx
src/android/OnyxPlugin.java
9623
package com.dft.cordova.plugin.onyx; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaInterface; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import android.util.Log; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.imgproc.Imgproc; import com.dft.onyx.FingerprintTemplate; public class OnyxPlugin extends CordovaPlugin implements OnyxMatch.MatchResultCallback { public static final String TAG = "OnyxPlugin"; public static final String IMAGE_URI_PREFIX = "data:image/jpeg;base64,"; public static String mPackageName; public static CallbackContext mCallbackContext; public static PluginResult mPluginResult; private Activity mActivity; private Context mContext; public static JSONObject mArgs; private static String mExecuteAction; public static PluginAction mPluginAction; public enum PluginAction { CAPTURE("capture"), MATCH("match"); private final String key; PluginAction(String key) { this.key = key; } public String getKey() { return this.key; } } public enum OnyxConfig { ONYX_LICENSE("onyxLicense"), RETURN_RAW_IMAGE("returnRawImage"), RETURN_PROCESSED_IMAGE("returnProcessedImage"), RETURN_ENHANCED_IMAGE("returnEnhancedImage"), RETURN_WSQ("returnWSQ"), RETURN_FINGERPRINT_TEMPLATE("returnFingerprintTemplate"), SHOULD_CONVERT_TO_ISO_TEMPLATE("shouldConvertToISOTemplate"), COMPUTE_NFIQ_METRICS("computeNfiqMetrics"), CROP_SIZE("cropSize"), CROP_SIZE_WIDTH("width"), CROP_SIZE_HEIGHT("height"), CROP_FACTOR("cropFactor"), SHOW_LOADING_SPINNER("showLoadingSpinner"), USE_MANUAL_CAPTURE("useManualCapture"), USE_ONYX_LIVE("useOnyxLive"), USE_FLASH("useFlash"), RETICLE_ORIENTATION("reticleOrientation"), RETICLE_ORIENTATION_LEFT("LEFT"), RETICLE_ORIENTATION_RIGHT("RIGHT"), RETICLE_ORIENTATION_THUMB_PORTRAIT("THUMB_PORTRAIT"), BACKGROUND_COLOR_HEX_STRING("backgroundColorHexString"), SHOW_BACK_BUTTON("showBackButton"), SHOW_MANUAL_CAPTURE_TEXT("showManualCaptureText"), MANUAL_CAPTURE_TEXT("manualCaptureText"), BACK_BUTTON_TEXT("backButtonText"), REFERENCE("reference"), PROBE("probe"), PYRAMID_SCALES("pyramidScales"); private final String key; OnyxConfig(String key) { this.key = key; } public String getKey() { return this.key; } } /** * Constructor */ public OnyxPlugin() { } /** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); Log.v(TAG, "Init Onyx"); mPackageName = cordova.getActivity().getApplicationContext().getPackageName(); mPluginResult = new PluginResult(PluginResult.Status.NO_RESULT); mActivity = cordova.getActivity(); mContext = cordova.getActivity().getApplicationContext(); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException { mCallbackContext = callbackContext; Log.v(TAG, "OnyxPlugin action: " + action); mExecuteAction = action; mArgs = args.getJSONObject(0); if (!mArgs.has("onyxLicense") || !mArgs.has("action")) { mPluginResult = new PluginResult(PluginResult.Status.ERROR); mCallbackContext.error("Missing required parameters"); mCallbackContext.sendPluginResult(mPluginResult); return true; } if (action.equalsIgnoreCase(PluginAction.MATCH.getKey())) { mPluginAction = PluginAction.MATCH; } else if (action.equalsIgnoreCase(PluginAction.CAPTURE.getKey())) { mPluginAction = PluginAction.CAPTURE; } if (null != mPluginAction) { switch (mPluginAction) { case MATCH: doMatch(); break; case CAPTURE: launchOnyx(); break; } } else { onError("Invalid plugin action."); } return true; } public static void onFinished(int resultCode, JSONObject result) { if (resultCode == Activity.RESULT_OK) { mPluginResult = new PluginResult(PluginResult.Status.OK); try { result.put("action", mExecuteAction); } catch (JSONException e) { String errorMessage = "Failed to set JSON key value pair: " + e.getMessage(); mCallbackContext.error(errorMessage); mPluginResult = new PluginResult(PluginResult.Status.ERROR); } mCallbackContext.success(result); } else if (resultCode == Activity.RESULT_CANCELED) { mPluginResult = new PluginResult(PluginResult.Status.ERROR); mCallbackContext.error("Cancelled"); } mCallbackContext.sendPluginResult(mPluginResult); } private void keepCordovaCallback() { mPluginResult = new PluginResult(PluginResult.Status.NO_RESULT); mPluginResult.setKeepCallback(true); mCallbackContext.sendPluginResult(mPluginResult); } public static void onError(String errorMessage) { Log.e(TAG, errorMessage); mCallbackContext.error(errorMessage); mPluginResult = new PluginResult(PluginResult.Status.ERROR); mCallbackContext.sendPluginResult(mPluginResult); } private void launchOnyx() { mActivity.runOnUiThread(new Runnable() { public void run() { Intent onyxIntent = new Intent(mContext, OnyxActivity.class); onyxIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(onyxIntent); } }); keepCordovaCallback(); } private void doMatch() throws JSONException { // Get values for JSON keys String encodedReference = mArgs.getString(OnyxConfig.REFERENCE.getKey()); String encodedProbe = mArgs.getString(OnyxConfig.PROBE.getKey()); JSONArray scalesJSONArray = null; if (mArgs.has(OnyxConfig.PYRAMID_SCALES.getKey())) { scalesJSONArray = mArgs.getJSONArray(OnyxConfig.PYRAMID_SCALES.getKey()); } // Decode reference fingerprint template data byte[] referenceBytes = Base64.decode(encodedReference, 0); // Get encoded probe processed fingerprint image data from image URI String encodedProbeDataString = encodedProbe.substring(IMAGE_URI_PREFIX.length(), encodedProbe.length()); // Decode probe probe image data byte[] probeBytes = Base64.decode(encodedProbeDataString, 0); // Create a bitmap from the probe bytes Bitmap probeBitmap = BitmapFactory.decodeByteArray(probeBytes, 0, probeBytes.length); // Create a mat from the bitmap Mat matProbe = new Mat(); Utils.bitmapToMat(probeBitmap, matProbe); Imgproc.cvtColor(matProbe, matProbe, Imgproc.COLOR_RGB2GRAY); // Create reference fingerprint template from bytes FingerprintTemplate ftRef = new FingerprintTemplate(referenceBytes, 0); // Convert pyramid scales from JSON array to double array double[] argsScales = null; if (null != scalesJSONArray && scalesJSONArray.length() > 0) { argsScales = new double[scalesJSONArray.length()]; for (int i = 0; i < argsScales.length; i++) { argsScales[i] = Double.parseDouble(scalesJSONArray.optString(i)); } } final double[] pyramidScales = argsScales; OnyxMatch matchTask = new OnyxMatch(mContext, OnyxPlugin.this); matchTask.execute(ftRef, matProbe, pyramidScales); } @Override public void onMatchFinished(boolean match, float score) { JSONObject result = new JSONObject(); String errorMessage = null; try { result.put("isVerified", match); result.put("matchScore", score); } catch (JSONException e) { errorMessage = "Failed to set JSON key value pair: " + e.toString(); } if (null != errorMessage) { Log.e(TAG, errorMessage); onError(errorMessage); } else { onFinished(Activity.RESULT_OK, result); } } }
apache-2.0
MaximTar/satellite
src/main/resources/libs/JAT/jat/gps_ins/relative/RGPS_SIMU.java
2539
package jat.gps_ins.relative; /* JAT: Java Astrodynamics Toolkit * * Copyright (c) 2003 The JAT Project. All rights reserved. * * This file is part of JAT. JAT is free software; you can * redistribute it and/or modify it under the terms of the * NASA Open Source Agreement, version 1.3 or later. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * NASA Open Source Agreement for more details. * * You should have received a copy of the NASA Open Source Agreement * along with this program; if not, write to the NASA Goddard * Space Flight Center at opensource@gsfc.nasa.gov. * * * File Created on May 9, 2003 */ import jat.alg.estimators.*; import jat.alg.integrators.*; import jat.gps.*; //import jat.gps_ins.*; import jat.ins.*; /** * The RGPS_SIMU.java Class runs the RGPS/IMU EKF. * @author <a href="mailto:dgaylor@users.sourceforge.net">Dave Gaylor * @version 1.0 */ public class RGPS_SIMU { /** * main - runs the EKF. * @params args none. */ public static void main(String[] args) { String dir = "C:\\Jat\\jat\\input\\"; String gpsmeasfile = "gps\\rgpsmeas_rbar_geom1_mp.jat"; // String gpsmeasfile = "gpsmeasblk.txt"; String insmeasfile = "simu_rbar.jat"; String rinexfile = "gps\\rinex.n"; // RGPS_MeasurementList gps = new RGPS_MeasurementList(); // gps.readFromFile(dir+gpsmeasfile); RGPS_MeasurementList gps = RGPS_MeasurementList.recover(dir+gpsmeasfile); INS_MeasurementList ins = INS_MeasurementList.recover(dir+insmeasfile); // int big = ins.size(); // System.out.println("ins size = "+big); long seed = -1; GPS_Constellation constellation = new GPS_Constellation(dir+rinexfile); LinePrinter lp1 = new LinePrinter("C:\\Jat\\jat\\output\\ekf_simu_rbar_geom1_mp_new_at_1.txt"); LinePrinter lp2 = new LinePrinter("C:\\Jat\\jat\\output\\ekf_simu_rbar_geom1_mp_new_at_2.txt"); LinePrinter lp3 = new LinePrinter("C:\\Jat\\jat\\output\\ekf_simu_rbar_geom1_mp_at_resid.txt"); ProcessModel process = new RGPS_SIMU_ProcessModel(ins, constellation, lp1, lp2, lp3, seed); MeasurementModel meas = new RGPS_INS_MeasurementModel(gps, constellation); ExtendedKalmanFilter ekf = new ExtendedKalmanFilter(meas, gps, process); long ts = System.currentTimeMillis(); ekf.process(); long tf = System.currentTimeMillis(); double dtf = (tf - ts)/(60.0 * 1000.0); System.out.println("EKF Time Elapsed: "+dtf); } }
apache-2.0
randyychan/Ledgr
src/com/example/ledgr/dataobjects/ItemsData.java
13338
package com.example.ledgr.dataobjects; import java.util.ArrayList; import java.util.UUID; import junit.framework.Assert; import org.joda.time.LocalDate; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import com.example.ledgr.MainActivity; import com.example.ledgr.Utils; import com.example.ledgr.alarmandnotification.Alarm; import com.example.ledgr.contentprovider.ItemContentProvider; import com.example.ledgr.contentprovider.RentalContentProvider; import com.example.ledgr.temboo.TembooFacebook; public class ItemsData { public static final int SYNCED = 0; public static final int INSERTED = 1; public static final int UPDATED = 2; public static final int DELETED = 3; public static final int GET = 4; public static final int RENTED_OUT = 0; public static final int CURRENTLY_RENTING = 1; public static final int PENDING = 0; public static final int COMPLETE = 1; protected int alarm_id = 0; public static Cursor getItems_data(Activity activity) { Cursor cursor = activity.getContentResolver(). query(ItemContentProvider.CONTENT_URI, null, null, null, null); return cursor; } public static void addItem(Item item, Activity activity) { ContentValues values = ItemContentProvider.itemToValues(item); values.put(ItemContentProvider.C_DIRTY, INSERTED); activity.getContentResolver(). insert(ItemContentProvider.CONTENT_URI, values); activity.getContentResolver().notifyChange(ItemContentProvider.CONTENT_URI, null, true); //temboo TembooFacebook tfb = new TembooFacebook(); tfb.postItem(item); } public static void syncedItem(String item_id, Context context) { ContentValues values = new ContentValues(); values.put(ItemContentProvider.C_DIRTY, SYNCED); context.getContentResolver().update(ItemContentProvider.CONTENT_URI, values, ItemContentProvider.C_ID + " = ?", new String[] {item_id}); } public static void syncedDeleteItem(String item_id, Context context) { context.getContentResolver().delete(ItemContentProvider.CONTENT_URI, ItemContentProvider.C_ID + " = ?", new String[] {item_id}); } public static Cursor itemsToSync(Context context) { Cursor cursor = context.getContentResolver() .query(ItemContentProvider.CONTENT_URI, null, ItemContentProvider.C_DIRTY + " != ?", new String[] {Integer.toString(SYNCED)}, null); return cursor; } public static Cursor rentalsToSync(Context context) { Cursor cursor = context.getContentResolver() .query(RentalContentProvider.CONTENT_URI, null, RentalContentProvider.C_DIRTY + " != ?", new String[] {Integer.toString(SYNCED)}, null); return cursor; } public static ArrayList<Item> retrieveItemsRentedByUserId(String userId, Activity activity) { Cursor cursor = activity.getContentResolver() .query(RentalContentProvider.CONTENT_URI, null, RentalContentProvider.C_RENTER_ID + " = ? AND " + RentalContentProvider.C_DIRTY + " != ? AND " + RentalContentProvider.C_DIRTY + " != ?", new String[] {userId, Integer.toString(DELETED), Integer.toString(GET)}, null); cursor.moveToFirst(); ArrayList<Item> items = new ArrayList<Item>(); while(!cursor.isAfterLast()) { Item item = RentalContentProvider.createItemFromCursor(cursor); items.add(item); cursor.moveToNext(); } return items; } public static ArrayList<Rental> retrieveItemsLentByUserId(String userId, Activity activity) { Cursor cursor = activity.getContentResolver() .query(RentalContentProvider.CONTENT_URI, null, RentalContentProvider.C_OWNER_ID + " = ? AND " + RentalContentProvider.C_DIRTY + " != ? AND " + RentalContentProvider.C_DIRTY + " != ?", new String[] {userId, Integer.toString(DELETED), Integer.toString(GET)}, null); cursor.moveToFirst(); ArrayList<Rental> rentals = new ArrayList<Rental>(); while(!cursor.isAfterLast()) { Rental rental = RentalContentProvider.createRentalFromCursor(cursor); rentals.add(rental); cursor.moveToNext(); } return rentals; } public static ArrayList<User> retrieveUserIdsCurrentlyRenting(Activity activity) { Cursor cursor = activity.getContentResolver().query(RentalContentProvider.CONTENT_URI, new String[] {"DISTINCT " + RentalContentProvider.C_OWNER_ID, RentalContentProvider.C_OWNER_NAME}, RentalContentProvider.C_DIRTY + " != ? AND " + RentalContentProvider.C_DIRTY + " != ? AND " + RentalContentProvider.C_RENTED_OUT_OR_RENTING + " = ?", new String[] {Integer.toString(DELETED), Integer.toString(GET), Integer.toString(CURRENTLY_RENTING)}, null); ArrayList<User> users = new ArrayList<User>(); cursor.moveToFirst(); while(!cursor.isAfterLast()) { String userId = cursor.getString(cursor.getColumnIndexOrThrow(RentalContentProvider.C_OWNER_ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(RentalContentProvider.C_OWNER_NAME)); System.out.println("Current Users Renting = " + name + " " + userId); User user = new User(userId, name); users.add(user); cursor.moveToNext(); } return users; } public static ArrayList<User> retrieveUserIdsRenting(Activity activity) { Cursor cursor = activity.getContentResolver().query(RentalContentProvider.CONTENT_URI, new String[] {"DISTINCT " + RentalContentProvider.C_RENTER_ID, RentalContentProvider.C_RENTER_NAME}, RentalContentProvider.C_DIRTY + " != ? AND " + RentalContentProvider.C_DIRTY + " != ? AND " + RentalContentProvider.C_RENTED_OUT_OR_RENTING + " = ?", new String[] {Integer.toString(DELETED), Integer.toString(GET), Integer.toString(RENTED_OUT)}, null); ArrayList<User> users = new ArrayList<User>(); cursor.moveToFirst(); while(!cursor.isAfterLast()) { String userId = cursor.getString(cursor.getColumnIndexOrThrow(RentalContentProvider.C_RENTER_ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(RentalContentProvider.C_RENTER_NAME)); User user = new User(userId, name); users.add(user); cursor.moveToNext(); } return users; } public static Item retrieveItemById(String item_id, Activity activity) { Cursor cursor = activity.getContentResolver(). query(ItemContentProvider.CONTENT_URI, null, ItemContentProvider.C_ID + " = ? and " + ItemContentProvider.C_DIRTY + " != ?", new String[] {item_id, Integer.toString(DELETED)}, null); cursor.moveToFirst(); Item item = ItemContentProvider.createItemFromCursor(cursor); return item; } public static boolean deleteItemById(String item_id, Activity activity) { ContentValues values = new ContentValues(); values.put(ItemContentProvider.C_DIRTY, DELETED); activity.getContentResolver().update(ItemContentProvider.CONTENT_URI, values, ItemContentProvider.C_ID + " = ?", new String[] {item_id}); activity.getContentResolver().notifyChange(ItemContentProvider.CONTENT_URI, null, true); return true; } public static void updateItem(Item item, Activity activity) { ContentValues values = ItemContentProvider.itemToValues(item); values.put(ItemContentProvider.C_DIRTY, UPDATED); activity.getContentResolver().update(ItemContentProvider.CONTENT_URI, values, ItemContentProvider.C_ID + " = ?", new String[] {item.getItem_id()}); activity.getContentResolver().notifyChange(ItemContentProvider.CONTENT_URI, null, true); } public static boolean rentItemById(String item_id, User renter, LocalDate dueDate, Activity activity) { ContentValues values = new ContentValues(); values.put(ItemContentProvider.C_RENTED, 1); values.put(ItemContentProvider.C_DIRTY, UPDATED); activity.getContentResolver().update(ItemContentProvider.CONTENT_URI, values, ItemContentProvider.C_ID + " = ?", new String[] {item_id}); Cursor cursor = activity.getContentResolver().query(ItemContentProvider.CONTENT_URI, null, ItemContentProvider.C_ID + " = ?", new String[] {item_id}, null); cursor.moveToFirst(); Item item = ItemContentProvider.createItemFromCursor(cursor); SharedPreferences prefs = activity.getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE); String userid = prefs.getString(MainActivity.MAIN_USERID, ""); String username = prefs.getString(MainActivity.MAIN_USERNAME, ""); //TODO need to send rental Rental rental = new Rental(item, dueDate, renter, new User(userid, username)); Alarm alarm = new Alarm(); alarm.SetAlarm(activity.getApplicationContext(), 0, item.getTitle(), renter.getFirstName(), item_id, dueDate); rental.setRental_alarm_id(0); ContentValues contentValues = RentalContentProvider.rentalToValues(rental); contentValues.put(RentalContentProvider.C_ID, UUID.randomUUID().toString()); contentValues.put(RentalContentProvider.C_DIRTY, INSERTED); contentValues.put(RentalContentProvider.C_RENTED_OUT_OR_RENTING, RENTED_OUT); activity.getContentResolver().insert(RentalContentProvider.CONTENT_URI, contentValues); activity.getContentResolver().notifyChange(ItemContentProvider.CONTENT_URI, null, true); return false; } public static boolean cancelRentalById(String item_id, Activity activity) { ContentValues values = new ContentValues(); values.put(ItemContentProvider.C_RENTED, 0); values.put(ItemContentProvider.C_DIRTY, UPDATED); activity.getContentResolver().update(ItemContentProvider.CONTENT_URI, values, ItemContentProvider.C_ID + " = ?", new String[] {item_id}); ContentValues rentalValues = new ContentValues(); rentalValues.put(RentalContentProvider.C_DIRTY, DELETED); activity.getContentResolver() .update(RentalContentProvider.CONTENT_URI, rentalValues, RentalContentProvider.C_ITEMID + " = ?", new String[] {item_id}); activity.getContentResolver().notifyChange(ItemContentProvider.CONTENT_URI, null, true); //activity.getContentResolver().delete(RentalContentProvider.CONTENT_URI, RentalContentProvider.C_ITEMID + " = ?", new String[] {item_id}); return false; } public static void syncedDeleteRental(String rental_id, Context context) { context.getContentResolver().delete(RentalContentProvider.CONTENT_URI, RentalContentProvider.C_ID + " = ?", new String[] {rental_id}); } public static void syncedRental(String rental_id, Context context) { ContentValues values = new ContentValues(); values.put(ItemContentProvider.C_DIRTY, SYNCED); context.getContentResolver().update(RentalContentProvider.CONTENT_URI, values, RentalContentProvider.C_ID + " = ?", new String[] {rental_id}); } public static void syncedGetRental(Rental rental, Context context) { ContentValues values = RentalContentProvider.rentalToValues(rental); System.out.println("pcount values" + values.getAsInteger(RentalContentProvider.C_PICTURE_COUNT)); values.put(RentalContentProvider.C_DIRTY, SYNCED); values.put(RentalContentProvider.C_RENTED_OUT_OR_RENTING, CURRENTLY_RENTING); values.put(RentalContentProvider.C_PENDING_RENTAL, PENDING); context.getContentResolver().update(RentalContentProvider.CONTENT_URI, values, RentalContentProvider.C_ID + " = ?", new String[] {rental.getRental_id()}); Cursor cursor = context.getContentResolver().query(RentalContentProvider.CONTENT_URI, null, RentalContentProvider.C_DIRTY + " = ?", new String[] {rental.getRental_id()}, null); //TODO: perform notification to user about new rental here! // also refresh the rental screen Utils.notifyRental(context, rental); } public static void fetchRental(String rental_id, Context context) { ContentValues values = new ContentValues(); //put fake mock data values.put(RentalContentProvider.C_DUEDAY, 15); values.put(RentalContentProvider.C_DUEMONTH, 6); values.put(RentalContentProvider.C_DUEYEAR, 2000); values.put(RentalContentProvider.C_ID, rental_id); values.put(RentalContentProvider.C_DIRTY, GET); values.put(RentalContentProvider.C_RENTED_OUT_OR_RENTING, CURRENTLY_RENTING); values.put(RentalContentProvider.C_PENDING_RENTAL, PENDING); context.getContentResolver().insert(RentalContentProvider.CONTENT_URI, values); context.getContentResolver().notifyChange(ItemContentProvider.CONTENT_URI, null, true); } public static void deleteRental(String rental_id, Context context) { context.getContentResolver().delete(RentalContentProvider.CONTENT_URI, RentalContentProvider.C_ID + " = ?", new String[] {rental_id}); } public static Rental retrieveRentalById(String item_id, Activity activity) { Cursor cursor = activity.getContentResolver().query(RentalContentProvider.CONTENT_URI, null, RentalContentProvider.C_ITEMID + " = ? AND " + RentalContentProvider.C_DIRTY + " != ? AND " + RentalContentProvider.C_DIRTY + " != ?", new String[] {item_id, Integer.toString(DELETED), Integer.toString(GET)}, null); cursor.moveToFirst(); return RentalContentProvider.cursorToRental(cursor); } public static void venmoChargeComplete(String item_id, Context context) { ContentValues values = new ContentValues(); values.put(RentalContentProvider.C_PENDING_RENTAL, COMPLETE); int count = context.getContentResolver().update(RentalContentProvider.CONTENT_URI, values, RentalContentProvider.C_ITEMID + " = ?", new String[] {item_id}); Assert.assertEquals(1, count); } }
apache-2.0
pivotal/spring-social-strava
spring-social-strava/src/main/java/org/springframework/social/strava/api/impl/json/StravaSegmentMixin.java
247
package org.springframework.social.strava.api.impl.json; import com.fasterxml.jackson.annotation.JsonProperty; abstract class StravaSegmentMixin extends StravaObjectMixin { StravaSegmentMixin( @JsonProperty("id") long id) {} }
apache-2.0
hurricup/intellij-community
plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java
26823
// Copyright 2010 Victor Iacoban // // 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.zmlx.hg4idea.util; import com.intellij.dvcs.DvcsUtil; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.util.BackgroundTaskUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Couple; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vcs.history.FileHistoryPanelImpl; import com.intellij.openapi.vcs.history.VcsFileRevisionEx; import com.intellij.openapi.vcs.vfs.AbstractVcsVirtualFile; import com.intellij.openapi.vcs.vfs.VcsVirtualFile; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.zmlx.hg4idea.*; import org.zmlx.hg4idea.command.HgCatCommand; import org.zmlx.hg4idea.command.HgRemoveCommand; import org.zmlx.hg4idea.command.HgStatusCommand; import org.zmlx.hg4idea.command.HgWorkingCopyRevisionsCommand; import org.zmlx.hg4idea.execution.HgCommandResult; import org.zmlx.hg4idea.execution.ShellCommand; import org.zmlx.hg4idea.execution.ShellCommandException; import org.zmlx.hg4idea.log.HgHistoryUtil; import org.zmlx.hg4idea.provider.HgChangeProvider; import org.zmlx.hg4idea.repo.HgRepository; import org.zmlx.hg4idea.repo.HgRepositoryManager; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * HgUtil is a collection of static utility methods for Mercurial. */ public abstract class HgUtil { public static final Pattern URL_WITH_PASSWORD = Pattern.compile("(?:.+)://(?:.+)(:.+)@(?:.+)"); //http(s)://username:password@url public static final int MANY_FILES = 100; private static final Logger LOG = Logger.getInstance(HgUtil.class); public static final String DOT_HG = ".hg"; public static final String TIP_REFERENCE = "tip"; public static final String HEAD_REFERENCE = "HEAD"; public static File copyResourceToTempFile(String basename, String extension) throws IOException { final InputStream in = HgUtil.class.getClassLoader().getResourceAsStream("python/" + basename + extension); final File tempFile = FileUtil.createTempFile(basename, extension); final byte[] buffer = new byte[4096]; OutputStream out = null; try { out = new FileOutputStream(tempFile, false); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); } finally { try { out.close(); } catch (IOException e) { // ignore } } try { in.close(); } catch (IOException e) { // ignore } tempFile.deleteOnExit(); return tempFile; } public static void markDirectoryDirty(final Project project, final VirtualFile file) throws InvocationTargetException, InterruptedException { VfsUtil.markDirtyAndRefresh(true, true, false, file); VcsDirtyScopeManager.getInstance(project).dirDirtyRecursively(file); } public static void markFileDirty( final Project project, final VirtualFile file ) throws InvocationTargetException, InterruptedException { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { VcsDirtyScopeManager.getInstance(project).fileDirty(file); } }); runWriteActionAndWait(new Runnable() { public void run() { file.refresh(true, false); } }); } /** * Runs the given task as a write action in the event dispatching thread and waits for its completion. */ public static void runWriteActionAndWait(@NotNull final Runnable runnable) throws InvocationTargetException, InterruptedException { GuiUtils.runOrInvokeAndWait(new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(runnable); } }); } /** * Schedules the given task to be run as a write action in the event dispatching thread. */ public static void runWriteActionLater(@NotNull final Runnable runnable) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(runnable); } }); } /** * Returns a temporary python file that will be deleted on exit. * * Also all compiled version of the python file will be deleted. * * @param base The basename of the file to copy * @return The temporary copy the specified python file, with all the necessary hooks installed * to make sure it is completely removed at shutdown */ @Nullable public static File getTemporaryPythonFile(String base) { try { final File file = copyResourceToTempFile(base, ".py"); final String fileName = file.getName(); ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { public void run() { File[] files = file.getParentFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(fileName); } }); if (files != null) { for (File file1 : files) { file1.delete(); } } } }); return file; } catch (IOException e) { return null; } } /** * Calls 'hg remove' to remove given files from the VCS. * @param project * @param files files to be removed from the VCS. */ public static void removeFilesFromVcs(Project project, List<FilePath> files) { final HgRemoveCommand command = new HgRemoveCommand(project); for (FilePath filePath : files) { final VirtualFile vcsRoot = VcsUtil.getVcsRootFor(project, filePath); if (vcsRoot == null) { continue; } command.executeInCurrentThread(new HgFile(vcsRoot, filePath)); } } /** * Finds the nearest parent directory which is an hg root. * @param dir Directory which parent will be checked. * @return Directory which is the nearest hg root being a parent of this directory, * or <code>null</code> if this directory is not under hg. * @see com.intellij.openapi.vcs.AbstractVcs#isVersionedDirectory(com.intellij.openapi.vfs.VirtualFile) */ @Nullable public static VirtualFile getNearestHgRoot(VirtualFile dir) { VirtualFile currentDir = dir; while (currentDir != null) { if (isHgRoot(currentDir)) { return currentDir; } currentDir = currentDir.getParent(); } return null; } /** * Checks if the given directory is an hg root. */ public static boolean isHgRoot(@Nullable VirtualFile dir) { return dir != null && dir.findChild(DOT_HG) != null; } /** * Gets the Mercurial root for the given file path or null if non exists: * the root should not only be in directory mappings, but also the .hg repository folder should exist. * @see #getHgRootOrThrow(com.intellij.openapi.project.Project, com.intellij.openapi.vcs.FilePath) */ @Nullable public static VirtualFile getHgRootOrNull(Project project, FilePath filePath) { if (project == null) { return getNearestHgRoot(VcsUtil.getVirtualFile(filePath.getPath())); } return getNearestHgRoot(VcsUtil.getVcsRootFor(project, filePath)); } /** * Get hg roots for paths * * @param filePaths the context paths * @return a set of hg roots */ @NotNull public static Set<VirtualFile> hgRoots(@NotNull Project project, @NotNull Collection<FilePath> filePaths) { HashSet<VirtualFile> roots = new HashSet<>(); for (FilePath path : filePaths) { ContainerUtil.addIfNotNull(roots, getHgRootOrNull(project, path)); } return roots; } /** * Gets the Mercurial root for the given file path or null if non exists: * the root should not only be in directory mappings, but also the .hg repository folder should exist. * @see #getHgRootOrThrow(com.intellij.openapi.project.Project, com.intellij.openapi.vcs.FilePath) * @see #getHgRootOrNull(com.intellij.openapi.project.Project, com.intellij.openapi.vcs.FilePath) */ @Nullable public static VirtualFile getHgRootOrNull(Project project, @NotNull VirtualFile file) { return getHgRootOrNull(project, VcsUtil.getFilePath(file.getPath())); } /** * Gets the Mercurial root for the given file path or throws a VcsException if non exists: * the root should not only be in directory mappings, but also the .hg repository folder should exist. * @see #getHgRootOrNull(com.intellij.openapi.project.Project, com.intellij.openapi.vcs.FilePath) */ @NotNull public static VirtualFile getHgRootOrThrow(Project project, FilePath filePath) throws VcsException { final VirtualFile vf = getHgRootOrNull(project, filePath); if (vf == null) { throw new VcsException(HgVcsMessages.message("hg4idea.exception.file.not.under.hg", filePath.getPresentableUrl())); } return vf; } @NotNull public static VirtualFile getHgRootOrThrow(Project project, VirtualFile file) throws VcsException { return getHgRootOrThrow(project, VcsUtil.getFilePath(file.getPath())); } @Nullable public static VirtualFile getRootForSelectedFile(@NotNull Project project) { VirtualFile selectedFile = DvcsUtil.getSelectedFile(project); if (selectedFile != null) { return getHgRootOrNull(project, selectedFile); } return null; } /** * Shows a message dialog to enter the name of new branch. * * @return name of new branch or {@code null} if user has cancelled the dialog. */ @Nullable public static String getNewBranchNameFromUser(@NotNull HgRepository repository, @NotNull String dialogTitle) { return Messages.showInputDialog(repository.getProject(), "Enter the name of new branch:", dialogTitle, Messages.getQuestionIcon(), "", new HgBranchReferenceValidator(repository)); } /** * Checks is a merge operation is in progress on the given repository. * Actually gets the number of parents of the current revision. If there are 2 parents, then a merge is going on. Otherwise there is * only one parent. * @param project project to work on. * @param repository repository which is checked on merge. * @return True if merge operation is in progress, false if there is no merge operation. */ public static boolean isMergeInProgress(@NotNull Project project, VirtualFile repository) { return new HgWorkingCopyRevisionsCommand(project).parents(repository).size() > 1; } /** * Groups the given files by their Mercurial repositories and returns the map of relative paths to files for each repository. * @param hgFiles files to be grouped. * @return key is repository, values is the non-empty list of relative paths to files, which belong to this repository. */ @NotNull public static Map<VirtualFile, List<String>> getRelativePathsByRepository(Collection<HgFile> hgFiles) { final Map<VirtualFile, List<String>> map = new HashMap<>(); if (hgFiles == null) { return map; } for(HgFile file : hgFiles) { final VirtualFile repo = file.getRepo(); List<String> files = map.get(repo); if (files == null) { files = new ArrayList<>(); map.put(repo, files); } files.add(file.getRelativePath()); } return map; } @NotNull public static HgFile getFileNameInTargetRevision(Project project, HgRevisionNumber vcsRevisionNumber, HgFile localHgFile) { //get file name in target revision if it was moved/renamed // if file was moved but not committed then hg status would return nothing, so it's better to point working dir as '.' revision HgStatusCommand statCommand = new HgStatusCommand.Builder(false).copySource(true).baseRevision(vcsRevisionNumber). targetRevision(HgRevisionNumber.getInstance("", ".")).build(project); Set<HgChange> changes = statCommand.executeInCurrentThread(localHgFile.getRepo(), Collections.singletonList(localHgFile.toFilePath())); for (HgChange change : changes) { if (change.afterFile().equals(localHgFile)) { return change.beforeFile(); } } return localHgFile; } @NotNull public static FilePath getOriginalFileName(@NotNull FilePath filePath, ChangeListManager changeListManager) { Change change = changeListManager.getChange(filePath); if (change == null) { return filePath; } FileStatus status = change.getFileStatus(); if (status == HgChangeProvider.COPIED || status == HgChangeProvider.RENAMED) { ContentRevision beforeRevision = change.getBeforeRevision(); assert beforeRevision != null : "If a file's status is copied or renamed, there must be an previous version"; return beforeRevision.getFile(); } else { return filePath; } } /** * Returns all HG roots in the project. */ public static @NotNull List<VirtualFile> getHgRepositories(@NotNull Project project) { final List<VirtualFile> repos = new LinkedList<>(); for (VcsRoot root : ProjectLevelVcsManager.getInstance(project).getAllVcsRoots()) { if (HgVcs.VCS_NAME.equals(root.getVcs().getName())) { repos.add(root.getPath()); } } return repos; } @NotNull public static Map<VirtualFile, Collection<VirtualFile>> sortByHgRoots(@NotNull Project project, @NotNull Collection<VirtualFile> files) { Map<VirtualFile, Collection<VirtualFile>> sorted = new HashMap<>(); HgRepositoryManager repositoryManager = getRepositoryManager(project); for (VirtualFile file : files) { HgRepository repo = repositoryManager.getRepositoryForFile(file); if (repo == null) { continue; } Collection<VirtualFile> filesForRoot = sorted.get(repo.getRoot()); if (filesForRoot == null) { filesForRoot = new HashSet<>(); sorted.put(repo.getRoot(), filesForRoot); } filesForRoot.add(file); } return sorted; } @NotNull public static Map<VirtualFile, Collection<FilePath>> groupFilePathsByHgRoots(@NotNull Project project, @NotNull Collection<FilePath> files) { Map<VirtualFile, Collection<FilePath>> sorted = new HashMap<>(); if (project.isDisposed()) return sorted; HgRepositoryManager repositoryManager = getRepositoryManager(project); for (FilePath file : files) { HgRepository repo = repositoryManager.getRepositoryForFile(file); if (repo == null) { continue; } Collection<FilePath> filesForRoot = sorted.get(repo.getRoot()); if (filesForRoot == null) { filesForRoot = new HashSet<>(); sorted.put(repo.getRoot(), filesForRoot); } filesForRoot.add(file); } return sorted; } @NotNull public static ProgressIndicator executeOnPooledThread(@NotNull Runnable runnable, @NotNull Disposable parentDisposable) { return BackgroundTaskUtil.executeOnPooledThread(runnable, parentDisposable); } /** * Convert {@link VcsVirtualFile} to the {@link LocalFileSystem local} Virtual File. * * TODO * It is a workaround for the following problem: VcsVirtualFiles returned from the {@link FileHistoryPanelImpl} contain the current path * of the file, not the path that was in certain revision. This has to be fixed by making {@link HgFileRevision} implement * {@link VcsFileRevisionEx}. */ @Nullable public static VirtualFile convertToLocalVirtualFile(@Nullable VirtualFile file) { if (!(file instanceof AbstractVcsVirtualFile)) { return file; } LocalFileSystem lfs = LocalFileSystem.getInstance(); VirtualFile resultFile = lfs.findFileByPath(file.getPath()); if (resultFile == null) { resultFile = lfs.refreshAndFindFileByPath(file.getPath()); } return resultFile; } @NotNull public static List<Change> getDiff(@NotNull final Project project, @NotNull final VirtualFile root, @NotNull final FilePath path, @Nullable final HgRevisionNumber revNum1, @Nullable final HgRevisionNumber revNum2) { HgStatusCommand statusCommand; if (revNum1 != null) { //rev2==null means "compare with local version" statusCommand = new HgStatusCommand.Builder(true).ignored(false).unknown(false).copySource(!path.isDirectory()).baseRevision(revNum1) .targetRevision(revNum2).build(project); } else { LOG.assertTrue(revNum2 != null, "revision1 and revision2 can't both be null. Path: " + path); //rev1 and rev2 can't be null both// //get initial changes// statusCommand = new HgStatusCommand.Builder(true).ignored(false).unknown(false).copySource(false).baseRevision(revNum2) .build(project); } Collection<HgChange> hgChanges = statusCommand.executeInCurrentThread(root, Collections.singleton(path)); List<Change> changes = new ArrayList<>(); //convert output changes to standart Change class for (HgChange hgChange : hgChanges) { FileStatus status = convertHgDiffStatus(hgChange.getStatus()); if (status != FileStatus.UNKNOWN) { changes.add(HgHistoryUtil.createChange(project, root, hgChange.beforeFile().getRelativePath(), revNum1, hgChange.afterFile().getRelativePath(), revNum2, status)); } } return changes; } @NotNull public static FileStatus convertHgDiffStatus(@NotNull HgFileStatusEnum hgstatus) { if (hgstatus.equals(HgFileStatusEnum.ADDED)) { return FileStatus.ADDED; } else if (hgstatus.equals(HgFileStatusEnum.DELETED)) { return FileStatus.DELETED; } else if (hgstatus.equals(HgFileStatusEnum.MODIFIED)) { return FileStatus.MODIFIED; } else if (hgstatus.equals(HgFileStatusEnum.COPY)) { return HgChangeProvider.COPIED; } else if (hgstatus.equals(HgFileStatusEnum.UNVERSIONED)) { return FileStatus.UNKNOWN; } else if (hgstatus.equals(HgFileStatusEnum.IGNORED)) { return FileStatus.IGNORED; } else { return FileStatus.UNKNOWN; } } @NotNull public static byte[] loadContent(@NotNull Project project, @Nullable HgRevisionNumber revisionNumber, @NotNull HgFile fileToCat) { HgCommandResult result = new HgCatCommand(project).execute(fileToCat, revisionNumber, fileToCat.toFilePath().getCharset()); return result != null && result.getExitValue() == 0 ? result.getBytesOutput() : ArrayUtil.EMPTY_BYTE_ARRAY; } public static String removePasswordIfNeeded(@NotNull String path) { Matcher matcher = URL_WITH_PASSWORD.matcher(path); if (matcher.matches()) { return path.substring(0, matcher.start(1)) + path.substring(matcher.end(1), path.length()); } return path; } @NotNull public static String getDisplayableBranchOrBookmarkText(@NotNull HgRepository repository) { HgRepository.State state = repository.getState(); String branchText = ""; if (state != HgRepository.State.NORMAL) { branchText += state.toString() + " "; } return branchText + repository.getCurrentBranchName(); } @NotNull public static HgRepositoryManager getRepositoryManager(@NotNull Project project) { return ServiceManager.getService(project, HgRepositoryManager.class); } @Nullable public static HgRepository getCurrentRepository(@NotNull Project project) { if (project.isDisposed()) return null; return DvcsUtil.guessRepositoryForFile(project, getRepositoryManager(project), DvcsUtil.getSelectedFile(project), HgProjectSettings.getInstance(project).getRecentRootPath()); } @Nullable public static HgRepository getRepositoryForFile(@NotNull Project project, @Nullable VirtualFile file) { if (file == null || project.isDisposed()) return null; HgRepositoryManager repositoryManager = getRepositoryManager(project); VirtualFile root = getHgRootOrNull(project, file); return repositoryManager.getRepositoryForRoot(root); } @Nullable public static String getRepositoryDefaultPath(@NotNull Project project, @NotNull VirtualFile root) { HgRepository hgRepository = getRepositoryManager(project).getRepositoryForRoot(root); assert hgRepository != null : "Repository can't be null for root " + root.getName(); return hgRepository.getRepositoryConfig().getDefaultPath(); } @Nullable public static String getRepositoryDefaultPushPath(@NotNull Project project, @NotNull VirtualFile root) { HgRepository hgRepository = getRepositoryManager(project).getRepositoryForRoot(root); assert hgRepository != null : "Repository can't be null for root " + root.getName(); return hgRepository.getRepositoryConfig().getDefaultPushPath(); } @Nullable public static String getRepositoryDefaultPushPath(@NotNull HgRepository repository) { return repository.getRepositoryConfig().getDefaultPushPath(); } @Nullable public static String getConfig(@NotNull Project project, @NotNull VirtualFile root, @NotNull String section, @Nullable String configName) { HgRepository hgRepository = getRepositoryManager(project).getRepositoryForRoot(root); assert hgRepository != null : "Repository can't be null for root " + root.getName(); return hgRepository.getRepositoryConfig().getNamedConfig(section, configName); } @NotNull public static Collection<String> getRepositoryPaths(@NotNull Project project, @NotNull VirtualFile root) { HgRepository hgRepository = getRepositoryManager(project).getRepositoryForRoot(root); assert hgRepository != null : "Repository can't be null for root " + root.getName(); return hgRepository.getRepositoryConfig().getPaths(); } public static boolean isExecutableValid(@Nullable String executable) { try { if (StringUtil.isEmptyOrSpaces(executable)) { return false; } HgCommandResult result = getVersionOutput(executable); return result.getExitValue() == 0 && !result.getRawOutput().isEmpty(); } catch (Throwable e) { LOG.info("Error during hg executable validation: ", e); return false; } } @NotNull public static HgCommandResult getVersionOutput(@NotNull String executable) throws ShellCommandException, InterruptedException { String hgExecutable = executable.trim(); List<String> cmdArgs = new ArrayList<>(); cmdArgs.add(hgExecutable); cmdArgs.add("version"); cmdArgs.add("-q"); ShellCommand shellCommand = new ShellCommand(cmdArgs, null, CharsetToolkit.getDefaultSystemCharset()); return shellCommand.execute(false, false); } public static List<String> getNamesWithoutHashes(Collection<HgNameWithHashInfo> namesWithHashes) { //return names without duplication (actually for several heads in one branch) List<String> names = new ArrayList<>(); for (HgNameWithHashInfo hash : namesWithHashes) { if (!names.contains(hash.getName())) { names.add(hash.getName()); } } return names; } public static List<String> getSortedNamesWithoutHashes(Collection<HgNameWithHashInfo> namesWithHashes) { List<String> names = getNamesWithoutHashes(namesWithHashes); Collections.sort(names); return names; } @NotNull public static Couple<String> parseUserNameAndEmail(@NotNull String authorString) { //special characters should be retained for properly filtering by username. For Mercurial "a.b" username is not equal to "a b" // Vasya Pupkin <vasya.pupkin@jetbrains.com> -> Vasya Pupkin , vasya.pupkin@jetbrains.com int startEmailIndex = authorString.indexOf('<'); int startDomainIndex = authorString.indexOf('@'); int endEmailIndex = authorString.indexOf('>'); String userName; String email; if (0 < startEmailIndex && startEmailIndex < startDomainIndex && startDomainIndex < endEmailIndex) { email = authorString.substring(startEmailIndex + 1, endEmailIndex); userName = authorString.substring(0, startEmailIndex).trim(); } // vasya.pupkin@email.com || <vasya.pupkin@email.com> else if (!authorString.contains(" ") && startDomainIndex > 0) { //simple e-mail check. john@localhost userName = ""; if (startEmailIndex >= 0 && startDomainIndex > startEmailIndex && startDomainIndex < endEmailIndex) { email = authorString.substring(startEmailIndex + 1, endEmailIndex).trim(); } else { email = authorString; } } else { userName = authorString.trim(); email = ""; } return Couple.of(userName, email); } @NotNull public static List<String> getTargetNames(@NotNull HgRepository repository) { return ContainerUtil.sorted(ContainerUtil.map(repository.getRepositoryConfig().getPaths(), new Function<String, String>() { @Override public String fun(String s) { return removePasswordIfNeeded(s); } })); } }
apache-2.0
asacamano/K2
java/all-in-one/src/main/java/com/google/k2crypto/keyversions/PrivateKeyVersion.java
1102
/* * Copyright 2014 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.k2crypto.keyversions; /** * Class representing PrivateKeyVersions. Extended by specific implementations such as * DSAPrivateKeyVersion * * @author John Maheswaran (maheswaran@google.com) */ public abstract class PrivateKeyVersion extends AsymmetricKeyVersion { /** * Constructor for PrivateKeyVersion * * @param builder The Builder object used to build this PrivateKeyVersion */ protected PrivateKeyVersion(Builder builder) { super(builder); } }
apache-2.0
lbitonti/liquibase-hana
src/main/java/liquibase/sqlgenerator/ext/DropDefaultValueGeneratorHanaDB.java
2082
package liquibase.sqlgenerator.ext; import liquibase.database.Database; import liquibase.database.ext.HanaDBDatabase; import liquibase.datatype.DataTypeFactory; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.sqlgenerator.core.DropDefaultValueGenerator; import liquibase.statement.core.DropDefaultValueStatement; public class DropDefaultValueGeneratorHanaDB extends DropDefaultValueGenerator { @Override public int getPriority() { return PRIORITY_DATABASE; } @Override public boolean supports(DropDefaultValueStatement statement, Database database) { return database instanceof HanaDBDatabase; } @Override public Sql[] generateSql(DropDefaultValueStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { if (!supports(statement, database)) { return sqlGeneratorChain.generateSql(statement, database); } String tableName = statement.getTableName(); String columnName = statement.getColumnName(); String catalogName = statement.getCatalogName(); String schemaToUse = statement.getSchemaName(); if (schemaToUse == null) { schemaToUse = database.getDefaultSchemaName(); } String columnDataType = statement.getColumnDataType(); if (columnDataType == null) { columnDataType = SqlGeneratorHelperHanaDB.getColumnDataDefinition((HanaDBDatabase) database, catalogName, schemaToUse, tableName, columnName); } String sql = "ALTER TABLE " + database.escapeTableName(catalogName, schemaToUse, tableName) + " ALTER (" + database.escapeColumnName(catalogName, schemaToUse, tableName, columnName) + " " + DataTypeFactory.getInstance().fromDescription(columnDataType, database).toDatabaseDataType(database) + " DEFAULT NULL)"; return new Sql[]{ new UnparsedSql(sql, getAffectedColumn(statement)) }; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-iotthingsgraph/src/main/java/com/amazonaws/services/iotthingsgraph/model/FlowExecutionEventType.java
2594
/* * Copyright 2014-2019 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.iotthingsgraph.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum FlowExecutionEventType { EXECUTION_STARTED("EXECUTION_STARTED"), EXECUTION_FAILED("EXECUTION_FAILED"), EXECUTION_ABORTED("EXECUTION_ABORTED"), EXECUTION_SUCCEEDED("EXECUTION_SUCCEEDED"), STEP_STARTED("STEP_STARTED"), STEP_FAILED("STEP_FAILED"), STEP_SUCCEEDED("STEP_SUCCEEDED"), ACTIVITY_SCHEDULED("ACTIVITY_SCHEDULED"), ACTIVITY_STARTED("ACTIVITY_STARTED"), ACTIVITY_FAILED("ACTIVITY_FAILED"), ACTIVITY_SUCCEEDED("ACTIVITY_SUCCEEDED"), START_FLOW_EXECUTION_TASK("START_FLOW_EXECUTION_TASK"), SCHEDULE_NEXT_READY_STEPS_TASK("SCHEDULE_NEXT_READY_STEPS_TASK"), THING_ACTION_TASK("THING_ACTION_TASK"), THING_ACTION_TASK_FAILED("THING_ACTION_TASK_FAILED"), THING_ACTION_TASK_SUCCEEDED("THING_ACTION_TASK_SUCCEEDED"), ACKNOWLEDGE_TASK_MESSAGE("ACKNOWLEDGE_TASK_MESSAGE"); private String value; private FlowExecutionEventType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return FlowExecutionEventType corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static FlowExecutionEventType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (FlowExecutionEventType enumEntry : FlowExecutionEventType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
apache-2.0
mumabinggan/WeygoPhone
app/src/main/java/com/weygo/weygophone/pages/tabs/home/widget/WGHomeContentFloorClassifyColumnView.java
858
package com.weygo.weygophone.pages.tabs.home.widget; import android.content.Context; import android.util.AttributeSet; import com.weygo.weygophone.R; import com.weygo.weygophone.pages.common.widget.WGCommonHorizontalListView; /** * Created by muma on 2017/6/4. */ public class WGHomeContentFloorClassifyColumnView extends WGCommonHorizontalListView { public WGHomeContentFloorClassifyColumnView(Context context) { super(context); } public WGHomeContentFloorClassifyColumnView(Context context, AttributeSet attrs) { super(context, attrs); } public WGHomeContentFloorClassifyColumnView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected int itemResId() { return R.layout.wghome_content_floor_classify_column_item; } }
apache-2.0
lmjacksoniii/hazelcast
hazelcast/src/test/java/com/hazelcast/internal/metrics/metricsets/RuntimeMetricSetTest.java
3465
package com.hazelcast.internal.metrics.metricsets; import com.hazelcast.internal.metrics.LongGauge; import com.hazelcast.internal.metrics.ProbeLevel; import com.hazelcast.internal.metrics.impl.MetricsRegistryImpl; import com.hazelcast.logging.Logger; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.QuickTest; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.lang.management.ManagementFactory; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; @RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class RuntimeMetricSetTest extends HazelcastTestSupport { private final static int TEN_MB = 10 * 1024 * 1024; private MetricsRegistryImpl metricsRegistry; private Runtime runtime; @Before public void setup() { metricsRegistry = new MetricsRegistryImpl(Logger.getLogger(MetricsRegistryImpl.class), ProbeLevel.INFO); RuntimeMetricSet.register(metricsRegistry); runtime = Runtime.getRuntime(); } @Test public void utilityConstructor() { assertUtilityConstructor(RuntimeMetricSet.class); } @Test public void freeMemory() { final LongGauge gauge = metricsRegistry.newLongGauge("runtime.freeMemory"); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(runtime.freeMemory(), gauge.read(), TEN_MB); } }); } @Test public void totalMemory() { final LongGauge gauge = metricsRegistry.newLongGauge("runtime.totalMemory"); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(runtime.totalMemory(), gauge.read(), TEN_MB); } }); } @Test public void maxMemory() { final LongGauge gauge = metricsRegistry.newLongGauge("runtime.maxMemory"); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(runtime.maxMemory(), gauge.read(), TEN_MB); } }); } @Test public void usedMemory() { final LongGauge gauge = metricsRegistry.newLongGauge("runtime.usedMemory"); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { double expected = runtime.totalMemory() - runtime.freeMemory(); assertEquals(expected, gauge.read(), TEN_MB); } }); } @Test public void availableProcessors() { LongGauge gauge = metricsRegistry.newLongGauge("runtime.availableProcessors"); assertEquals(runtime.availableProcessors(), gauge.read()); } @Test public void uptime() { final LongGauge gauge = metricsRegistry.newLongGauge("runtime.uptime"); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { double expected = ManagementFactory.getRuntimeMXBean().getUptime(); assertEquals(expected, gauge.read(), TimeUnit.MINUTES.toMillis(1)); } }); } }
apache-2.0
aiyanbo/guava
guava-testlib/src/com/google/common/collect/testing/testers/MapCreationTester.java
5714
/* * Copyright (C) 2007 The Guava 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.google.common.collect.testing.testers; import static com.google.common.collect.testing.features.CollectionSize.ONE; import static com.google.common.collect.testing.features.CollectionSize.ZERO; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS; import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES; import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.testing.AbstractMapTester; import com.google.common.collect.testing.Helpers; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.MapFeature; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; /** * A generic JUnit test which tests creation (typically through a constructor or * static factory method) of a map. Can't be invoked directly; please see * {@link com.google.common.collect.testing.MapTestSuiteBuilder}. * * @author Chris Povirk * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class MapCreationTester<K, V> extends AbstractMapTester<K, V> { @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeySupported() { initMapWithNullKey(); expectContents(createArrayWithNullKey()); } @MapFeature.Require(absent = ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeyUnsupported() { try { initMapWithNullKey(); fail("Creating a map containing a null key should fail"); } catch (NullPointerException expected) { } } @MapFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullValueSupported() { initMapWithNullValue(); expectContents(createArrayWithNullValue()); } @MapFeature.Require(absent = ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullValueUnsupported() { try { initMapWithNullValue(); fail("Creating a map containing a null value should fail"); } catch (NullPointerException expected) { } } @MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES}) @CollectionSize.Require(absent = ZERO) public void testCreateWithNullKeyAndValueSupported() { Entry<K, V>[] entries = createSamplesArray(); entries[getNullLocation()] = entry(null, null); resetMap(entries); expectContents(entries); } @MapFeature.Require(value = ALLOWS_NULL_KEYS, absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesNotRejected() { expectFirstRemoved(getEntriesMultipleNullKeys()); } @MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() { expectFirstRemoved(getEntriesMultipleNonNullKeys()); } @MapFeature.Require({ALLOWS_NULL_KEYS, REJECTS_DUPLICATES_AT_CREATION}) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nullDuplicatesRejected() { Entry<K, V>[] entries = getEntriesMultipleNullKeys(); try { resetMap(entries); fail("Should reject duplicate null elements at creation"); } catch (IllegalArgumentException expected) { } } @MapFeature.Require(REJECTS_DUPLICATES_AT_CREATION) @CollectionSize.Require(absent = {ZERO, ONE}) public void testCreateWithDuplicates_nonNullDuplicatesRejected() { Entry<K, V>[] entries = getEntriesMultipleNonNullKeys(); try { resetMap(entries); fail("Should reject duplicate non-null elements at creation"); } catch (IllegalArgumentException expected) { } } private Entry<K, V>[] getEntriesMultipleNullKeys() { Entry<K, V>[] entries = createArrayWithNullKey(); entries[0] = entry(null, entries[0].getValue()); return entries; } private Entry<K, V>[] getEntriesMultipleNonNullKeys() { Entry<K, V>[] entries = createSamplesArray(); entries[0] = entry(k1(), v0()); return entries; } private void expectFirstRemoved(Entry<K, V>[] entries) { resetMap(entries); List<Entry<K, V>> expectedWithDuplicateRemoved = Arrays.asList(entries).subList(1, getNumElements()); expectContents(expectedWithDuplicateRemoved); } /** * Returns the {@link Method} instance for {@link * #testCreateWithNullKeyUnsupported()} so that tests can suppress it * with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147">Sun * bug 5045147</a> is fixed. */ @GwtIncompatible // reflection public static Method getCreateWithNullKeyUnsupportedMethod() { return Helpers.getMethod(MapCreationTester.class, "testCreateWithNullKeyUnsupported"); } }
apache-2.0
asual/summer
modules/el/src/main/java/org/jboss/el/parser/NodeVisitor.java
801
/* * 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.jboss.el.parser; /** * @author Jacob Hookom [jacob@hookom.net] * @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: markt $ */ public interface NodeVisitor { public void visit(Node node) throws Exception; }
apache-2.0
dbflute-test/dbflute-test-dbms-postgresql
src/main/java/org/docksidestage/postgresql/dbflute/cbean/nss/ProductCategoryNss.java
1489
package org.docksidestage.postgresql.dbflute.cbean.nss; import org.docksidestage.postgresql.dbflute.cbean.cq.ProductCategoryCQ; /** * The nest select set-upper of product_category. * @author DBFlute(AutoGenerator) */ public class ProductCategoryNss { // =================================================================================== // Attribute // ========= protected final ProductCategoryCQ _query; public ProductCategoryNss(ProductCategoryCQ query) { _query = query; } public boolean hasConditionQuery() { return _query != null; } // =================================================================================== // Nested Relation // =============== /** * With nested relation columns to select clause. <br> * (商品カテゴリ)product_category by my parent_category_code, named 'productCategorySelf'. * @return The set-upper of more nested relation. {...with[nested-relation].with[more-nested-relation]} (NotNull) */ public ProductCategoryNss withProductCategorySelf() { _query.xdoNss(() -> _query.queryProductCategorySelf()); return new ProductCategoryNss(_query.queryProductCategorySelf()); } }
apache-2.0
objectos/way
orm/orm-compiler/src/main/java/br/com/objectos/way/orm/compiler/CompanionTypeFactory.java
1727
/* * Copyright 2014-2015 Objectos, Fábrica de Software LTDA. * * 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 br.com.objectos.way.orm.compiler; import java.util.Objects; import javax.lang.model.element.Modifier; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; /** * @author marcio.endo@objectos.com.br (Marcio Endo) */ class CompanionTypeFactory implements CompanionTypeExe { private final OrmInject inject; private CompanionTypeFactory(OrmInject inject) { this.inject = inject; } public static CompanionTypeFactory of(OrmPojoInfo pojoInfo) { OrmInject inject = pojoInfo.inject(); return new CompanionTypeFactory(inject); } @Override public CompanionType acceptCompanionType(CompanionType type) { ClassName companionTypeClassName = type.className(); return type.addMethod(MethodSpec.methodBuilder("get") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(inject.parameterSpec()) .returns(companionTypeClassName) .addStatement("$T.requireNonNull($L)", Objects.class, inject.name()) .addStatement("return new $T($L)", companionTypeClassName, inject.name()) .build()); } }
apache-2.0
googlemaps/google-maps-services-java
src/main/java/com/google/maps/PlaceDetailsRequest.java
5703
/* * Copyright 2015 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.maps; import com.google.gson.FieldNamingPolicy; import com.google.maps.errors.ApiException; import com.google.maps.internal.ApiConfig; import com.google.maps.internal.ApiResponse; import com.google.maps.internal.StringJoin; import com.google.maps.internal.StringJoin.UrlValue; import com.google.maps.model.PlaceDetails; /** * A <a href="https://developers.google.com/places/web-service/details#PlaceDetailsRequests">Place * Details</a> request. */ public class PlaceDetailsRequest extends PendingResultBase<PlaceDetails, PlaceDetailsRequest, PlaceDetailsRequest.Response> { static final ApiConfig API_CONFIG = new ApiConfig("/maps/api/place/details/json") .fieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); public PlaceDetailsRequest(GeoApiContext context) { super(context, API_CONFIG, Response.class); } /** * Specifies the Place ID to get Place Details for. Required. * * @param placeId The Place ID to retrieve details for. * @return Returns this {@code PlaceDetailsRequest} for call chaining. */ public PlaceDetailsRequest placeId(String placeId) { return param("placeid", placeId); } /** * Sets the SessionToken for this request. Use this for Place Details requests that are called * following an autocomplete request in the same user session. Optional. * * @param sessionToken Session Token is the session identifier. * @return Returns this {@code PlaceDetailsRequest} for call chaining. */ public PlaceDetailsRequest sessionToken(PlaceAutocompleteRequest.SessionToken sessionToken) { return param("sessiontoken", sessionToken); } /** * Sets the Region for this request. The region code, specified as a ccTLD (country code top-level * domain) two-character value. Most ccTLD codes are identical to ISO 3166-1 codes, with some * exceptions. This parameter will only influence, not fully restrict, results. * * @param region The region code. * @return Returns this {@code PlaceDetailsRequest} for call chaining. */ public PlaceDetailsRequest region(String region) { return param("region", region); } /** * Specifies the field masks of the details to be returned by PlaceDetails. * * @param fields The Field Masks of the fields to return. * @return Returns this {@code PlaceDetailsRequest} for call chaining. */ public PlaceDetailsRequest fields(FieldMask... fields) { return param("fields", StringJoin.join(',', fields)); } @Override protected void validateRequest() { if (!params().containsKey("placeid")) { throw new IllegalArgumentException("Request must contain 'placeId'."); } } public static class Response implements ApiResponse<PlaceDetails> { public String status; public PlaceDetails result; public String[] htmlAttributions; public String errorMessage; @Override public boolean successful() { return "OK".equals(status) || "ZERO_RESULTS".equals(status); } @Override public PlaceDetails getResult() { if (result != null) { result.htmlAttributions = htmlAttributions; } return result; } @Override public ApiException getError() { if (successful()) { return null; } return ApiException.from(status, errorMessage); } } public enum FieldMask implements UrlValue { ADDRESS_COMPONENT("address_component"), ADR_ADDRESS("adr_address"), @Deprecated ALT_ID("alt_id"), BUSINESS_STATUS("business_status"), FORMATTED_ADDRESS("formatted_address"), FORMATTED_PHONE_NUMBER("formatted_phone_number"), GEOMETRY("geometry"), GEOMETRY_LOCATION("geometry/location"), GEOMETRY_LOCATION_LAT("geometry/location/lat"), GEOMETRY_LOCATION_LNG("geometry/location/lng"), GEOMETRY_VIEWPORT("geometry/viewport"), GEOMETRY_VIEWPORT_NORTHEAST("geometry/viewport/northeast"), GEOMETRY_VIEWPORT_NORTHEAST_LAT("geometry/viewport/northeast/lat"), GEOMETRY_VIEWPORT_NORTHEAST_LNG("geometry/viewport/northeast/lng"), GEOMETRY_VIEWPORT_SOUTHWEST("geometry/viewport/southwest"), GEOMETRY_VIEWPORT_SOUTHWEST_LAT("geometry/viewport/southwest/lat"), GEOMETRY_VIEWPORT_SOUTHWEST_LNG("geometry/viewport/southwest/lng"), ICON("icon"), @Deprecated ID("id"), INTERNATIONAL_PHONE_NUMBER("international_phone_number"), NAME("name"), OPENING_HOURS("opening_hours"), @Deprecated PERMANENTLY_CLOSED("permanently_closed"), USER_RATINGS_TOTAL("user_ratings_total"), PHOTOS("photos"), PLACE_ID("place_id"), PLUS_CODE("plus_code"), PRICE_LEVEL("price_level"), RATING("rating"), @Deprecated REFERENCE("reference"), REVIEW("review"), @Deprecated SCOPE("scope"), TYPES("types"), URL("url"), UTC_OFFSET("utc_offset"), VICINITY("vicinity"), WEBSITE("website"); private final String field; FieldMask(final String field) { this.field = field; } @Override public String toUrlValue() { return field; } } }
apache-2.0
CarloMicieli/spring-mvc-movies
src/test/java/com/github/carlomicieli/nerdmovies/models/MailUserTests.java
1421
/* * Copyright 2012 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.github.carlomicieli.nerdmovies.models; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author Carlo Micieli */ public class MailUserTests { @Test public void shouldAddNewRoleToUsers() { MailUser user = new MailUser(); user.setEmailAddress("joey@ramones.com"); user.setPassword("secret"); user.addRole("ROLE_USER"); user.addRole("ROLE_ADMIN"); assertEquals(2, user.getRoles().size()); assertEquals("[ROLE_USER, ROLE_ADMIN]", user.getRoles().toString()); } @Test public void shouldInitializeNewUsers() { MailUser user = new MailUser(); user.init(); assertEquals(true, user.isEnabled()); assertEquals("[ROLE_USER]", user.getRoles().toString()); } }
apache-2.0
ingenieux/beanstalker
beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/config/DeleteConfigurationTemplateMojo.java
2439
/* * Copyright (c) 2016 ingenieux Labs * * 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 br.com.ingenieux.mojo.beanstalk.config; import com.amazonaws.services.elasticbeanstalk.model.DeleteConfigurationTemplateRequest; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import br.com.ingenieux.mojo.beanstalk.AbstractBeanstalkMojo; import br.com.ingenieux.mojo.beanstalk.ConfigurationTemplate; /** * Delete Configuration Template * * @author Aldrin Leal * @since 0.2.7 */ @Mojo(name = "delete-configuration-template") public class DeleteConfigurationTemplateMojo extends AbstractBeanstalkMojo { /** * Beanstalk Application Name */ @Parameter(property = "beanstalk.applicationName", defaultValue = "${project.artifactId}", required = true) String applicationName; /** * Configuration Template Name (Optional) */ @Parameter(property = "beanstalk.configurationTemplate") String configurationTemplate; /** * Configuration Templates */ @Parameter ConfigurationTemplate[] configurationTemplates; @Override protected Object executeInternal() throws MojoExecutionException, MojoFailureException { boolean bConfigurationTemplateDefined = StringUtils.isNotBlank(configurationTemplate); if (bConfigurationTemplateDefined) { deleteConfiguration(configurationTemplate); } else { for (ConfigurationTemplate template : configurationTemplates) { deleteConfiguration(template.getId()); } } return null; } void deleteConfiguration(String templateName) { DeleteConfigurationTemplateRequest req = new DeleteConfigurationTemplateRequest(applicationName, templateName); getService().deleteConfigurationTemplate(req); } }
apache-2.0
davidmigloz/supermarket-agent-system
src/main/java/com/davidflex/supermarket/agents/shop/ShopAgent.java
4443
package com.davidflex.supermarket.agents.shop; import com.davidflex.supermarket.agents.behaviours.shop_agent.ListenEmployeesBehaviour; import com.davidflex.supermarket.agents.behaviours.shop_agent.ListenNewOrdersBehaviour; import com.davidflex.supermarket.agents.behaviours.shop_agent.ShowDataBehaviour; import com.davidflex.supermarket.agents.utils.DFUtils; import com.davidflex.supermarket.agents.utils.JadeUtils; import com.davidflex.supermarket.ontologies.company.CompanyOntolagy; import com.davidflex.supermarket.ontologies.company.CompanyOntolagyVocabulary; import com.davidflex.supermarket.ontologies.company.concepts.Warehouse; import com.davidflex.supermarket.ontologies.ecommerce.ECommerceOntologyVocabulary; import com.davidflex.supermarket.ontologies.ecommerce.concepts.Location; import com.davidflex.supermarket.ontologies.shop.ShopOntology; import com.davidflex.supermarket.ontologies.shop.ShopOntologyVocabulary; import jade.content.lang.Codec; import jade.content.lang.sl.SLCodec; import jade.content.onto.BeanOntologyException; import jade.content.onto.Ontology; import jade.core.AID; import jade.core.Agent; import jade.domain.FIPAException; import jade.wrapper.ContainerController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; public class ShopAgent extends Agent { private static final Logger logger = LoggerFactory.getLogger(ShopAgent.class); private Codec codec; private Ontology ontology; private ContainerController container; private List<Warehouse> warehouses; private AtomicLong orderIDs; private Map<Long, Location> activeOrders; private Map<AID, Location> drones; public ShopAgent() { codec = new SLCodec(0); // fipa-sl0 try { ontology = CompanyOntolagy.getInstance(); } catch (BeanOntologyException e) { logger.error("Ontology error!", e); doDelete(); } container = JadeUtils.createContainer("personalShopAgents"); warehouses = new ArrayList<>(); orderIDs = new AtomicLong(); activeOrders = new HashMap<>(); drones = new HashMap<>(); } @Override protected void setup() { // Setup content manager getContentManager().registerLanguage(codec); getContentManager().registerOntology(ontology, ShopOntology.ONTOLOGY_NAME); getContentManager().registerOntology(ontology, CompanyOntolagyVocabulary.ONTOLOGY_NAME); // Register in DF try { DFUtils.registerInDF(this, ECommerceOntologyVocabulary.SHOP_NAME, ECommerceOntologyVocabulary.SHOP_TYPE); } catch (FIPAException e) { logger.error("Error at registering in DF", e); doDelete(); } // Add behaviours addBehaviour(new ListenNewOrdersBehaviour(this)); addBehaviour(new ListenEmployeesBehaviour(this)); addBehaviour(new ShowDataBehaviour(this)); } @Override protected void takeDown() { try { DFUtils.deregisterFromDF(this); } catch (FIPAException e) { logger.error("Error at deregistering in DF", e); } } public Codec getCodec() { return codec; } public String getShopOntologyName() { return ShopOntologyVocabulary.ONTOLOGY_NAME; } public Ontology getCompanyOntology() { return ontology; } public ContainerController getContainer() { return container; } /** * Register a new order. * * @param location customer location * @return orderID */ public long addNewOrder(Location location) { long num = orderIDs.incrementAndGet(); activeOrders.put(num, location); return num; } public Map<Long, Location> getActiveOrders() { return activeOrders; } public void registerWarehouse(Warehouse warehouse) { warehouses.add(warehouse); } public List<Warehouse> getWarehouses() { return warehouses; } public void setDronePosition(AID drone, Location position){ drones.put(drone, position); } public void unregisterDrone(AID drone) { drones.remove(drone); } public Map<AID, Location> getDrones() { return drones; } }
apache-2.0
cbeams/bitcoinj
core/src/test/java/com/google/bitcoin/wallet/DeterministicKeyChainTest.java
14404
/** * Copyright 2013 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.bitcoin.wallet; import com.google.bitcoin.core.*; import com.google.bitcoin.crypto.DeterministicKey; import com.google.bitcoin.params.UnitTestParams; import com.google.bitcoin.store.UnreadableWalletException; import com.google.bitcoin.utils.BriefLogFormatter; import com.google.bitcoin.utils.Threading; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.io.Resources; import org.bitcoinj.wallet.Protos; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.params.KeyParameter; import java.io.IOException; import java.security.SecureRandom; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static org.junit.Assert.*; public class DeterministicKeyChainTest { private DeterministicKeyChain chain; private final byte[] SEED = Sha256Hash.create("don't use a string seed like this in real life".getBytes()).getBytes(); @Before public void setup() { BriefLogFormatter.init(); // You should use a random seed instead. The secs constant comes from the unit test file, so we can compare // serialized data properly. long secs = 1389353062L; chain = new DeterministicKeyChain(SEED, secs); chain.setLookaheadSize(10); assertEquals(secs, checkNotNull(chain.getSeed()).getCreationTimeSeconds()); } @Test public void mnemonicCode() throws Exception { final List<String> words = chain.toMnemonicCode(); assertEquals("aerobic toe save section draw warm cute upon raccoon mother priority pilot taste sweet next traffic fatal sword dentist original crisp team caution rebel", Joiner.on(" ").join(words)); new DeterministicSeed(words, checkNotNull(chain.getSeed()).getCreationTimeSeconds()); } @Test public void derive() throws Exception { ECKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); ECKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); final Address address = new Address(UnitTestParams.get(), "n1GyUANZand9Kw6hGSV9837cCC9FFUQzQa"); assertEquals(address, key1.toAddress(UnitTestParams.get())); assertEquals("n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X", key2.toAddress(UnitTestParams.get()).toString()); assertEquals(key1, chain.findKeyFromPubHash(address.getHash160())); assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey())); key1.sign(Sha256Hash.ZERO_HASH); ECKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE); assertEquals("mnXiDR4MKsFxcKJEZjx4353oXvo55iuptn", key3.toAddress(UnitTestParams.get()).toString()); key3.sign(Sha256Hash.ZERO_HASH); } @Test public void events() throws Exception { // Check that we get the right events at the right time. final List<List<ECKey>> listenerKeys = Lists.newArrayList(); long secs = 1389353062L; chain = new DeterministicKeyChain(SEED, secs); chain.addEventListener(new AbstractKeyChainEventListener() { @Override public void onKeysAdded(List<ECKey> keys) { listenerKeys.add(keys); } }, Threading.SAME_THREAD); assertEquals(0, listenerKeys.size()); chain.setLookaheadSize(5); assertEquals(0, listenerKeys.size()); ECKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE); assertEquals(1, listenerKeys.size()); // 1 event final List<ECKey> firstEvent = listenerKeys.get(0); assertEquals(6, firstEvent.size()); // 5 lookahead keys and 1 to satisfy the request. assertTrue(firstEvent.contains(key)); // order is not specified. listenerKeys.clear(); key = chain.getKey(KeyChain.KeyPurpose.CHANGE); assertEquals(1, listenerKeys.size()); // 1 event assertEquals(1, listenerKeys.get(0).size()); // 1 key. DeterministicKey eventKey = (DeterministicKey) listenerKeys.get(0).get(0); assertNotEquals(key, eventKey); // The key added is not the one that's served. assertEquals(6, eventKey.getChildNumber().i()); listenerKeys.clear(); key = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); assertEquals(1, listenerKeys.size()); // 1 event assertEquals(6, listenerKeys.get(0).size()); // 1 key. eventKey = (DeterministicKey) listenerKeys.get(0).get(0); // The key added IS the one that's served because we did not previously request any RECEIVE_FUNDS keys. assertEquals(key, eventKey); assertEquals(0, eventKey.getChildNumber().i()); } @Test public void random() { // Can't test much here but verify the constructor worked and the class is functional. The other tests rely on // a fixed seed to be deterministic. chain = new DeterministicKeyChain(new SecureRandom()); chain.setLookaheadSize(10); chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).sign(Sha256Hash.ZERO_HASH); chain.getKey(KeyChain.KeyPurpose.CHANGE).sign(Sha256Hash.ZERO_HASH); } @Test public void serializeUnencrypted() throws UnreadableWalletException { DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE); List<Protos.Key> keys = chain.serializeToProtobuf(); // 1 root seed, 1 master key, 1 account key, 2 internal keys, 3 derived and 20 lookahead. assertEquals(28, keys.size()); // Get another key that will be lost during round-tripping, to ensure we can derive it again. DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE); final String EXPECTED_SERIALIZATION = checkSerialization(keys, "deterministic-wallet-serialization.txt"); // Round trip the data back and forth to check it is preserved. int oldLookaheadSize = chain.getLookaheadSize(); chain = DeterministicKeyChain.fromProtobuf(keys, null).get(0); assertEquals(EXPECTED_SERIALIZATION, protoToString(chain.serializeToProtobuf())); assertEquals(key1, chain.findKeyFromPubHash(key1.getPubKeyHash())); assertEquals(key2, chain.findKeyFromPubHash(key2.getPubKeyHash())); assertEquals(key3, chain.findKeyFromPubHash(key3.getPubKeyHash())); assertEquals(key4, chain.getKey(KeyChain.KeyPurpose.CHANGE)); key1.sign(Sha256Hash.ZERO_HASH); key2.sign(Sha256Hash.ZERO_HASH); key3.sign(Sha256Hash.ZERO_HASH); key4.sign(Sha256Hash.ZERO_HASH); assertEquals(oldLookaheadSize, chain.getLookaheadSize()); } @Test(expected = IllegalStateException.class) public void notEncrypted() { chain.toDecrypted("fail"); } @Test(expected = IllegalStateException.class) public void encryptTwice() { chain = chain.toEncrypted("once"); chain = chain.toEncrypted("twice"); } private void checkEncryptedKeyChain(DeterministicKeyChain encChain, DeterministicKey key1) { // Check we can look keys up and extend the chain without the AES key being provided. DeterministicKey encKey1 = encChain.findKeyFromPubKey(key1.getPubKey()); DeterministicKey encKey2 = encChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); assertFalse(key1.isEncrypted()); assertTrue(encKey1.isEncrypted()); assertEquals(encKey1.getPubKeyPoint(), key1.getPubKeyPoint()); final KeyParameter aesKey = checkNotNull(encChain.getKeyCrypter()).deriveKey("open secret"); encKey1.sign(Sha256Hash.ZERO_HASH, aesKey); encKey2.sign(Sha256Hash.ZERO_HASH, aesKey); assertTrue(encChain.checkAESKey(aesKey)); assertFalse(encChain.checkPassword("access denied")); assertTrue(encChain.checkPassword("open secret")); } @Test public void encryption() throws UnreadableWalletException { DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKeyChain encChain = chain.toEncrypted("open secret"); DeterministicKey encKey1 = encChain.findKeyFromPubKey(key1.getPubKey()); checkEncryptedKeyChain(encChain, key1); // Round-trip to ensure de/serialization works and that we can store two chains and they both deserialize. List<Protos.Key> serialized = encChain.serializeToProtobuf(); List<Protos.Key> doubled = Lists.newArrayListWithExpectedSize(serialized.size() * 2); doubled.addAll(serialized); doubled.addAll(serialized); final List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(doubled, encChain.getKeyCrypter()); assertEquals(2, chains.size()); encChain = chains.get(0); checkEncryptedKeyChain(encChain, chain.findKeyFromPubKey(key1.getPubKey())); encChain = chains.get(1); checkEncryptedKeyChain(encChain, chain.findKeyFromPubKey(key1.getPubKey())); DeterministicKey encKey2 = encChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); // Decrypt and check the keys match. DeterministicKeyChain decChain = encChain.toDecrypted("open secret"); DeterministicKey decKey1 = decChain.findKeyFromPubHash(encKey1.getPubKeyHash()); DeterministicKey decKey2 = decChain.findKeyFromPubHash(encKey2.getPubKeyHash()); assertEquals(decKey1.getPubKeyPoint(), encKey1.getPubKeyPoint()); assertEquals(decKey2.getPubKeyPoint(), encKey2.getPubKeyPoint()); assertFalse(decKey1.isEncrypted()); assertFalse(decKey2.isEncrypted()); assertNotEquals(encKey1.getParent(), decKey1.getParent()); // parts of a different hierarchy // Check we can once again derive keys from the decrypted chain. decChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).sign(Sha256Hash.ZERO_HASH); decChain.getKey(KeyChain.KeyPurpose.CHANGE).sign(Sha256Hash.ZERO_HASH); } @Test public void watchingChain() throws UnreadableWalletException { Utils.setMockClock(); DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE); DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE); DeterministicKey watchingKey = chain.getWatchingKey(); final String pub58 = watchingKey.serializePubB58(); assertEquals("xpub68KFnj3bqUx1s7mHejLDBPywCAKdJEu1b49uniEEn2WSbHmZ7xbLqFTjJbtx1LUcAt1DwhoqWHmo2s5WMJp6wi38CiF2hYD49qVViKVvAoi", pub58); watchingKey = DeterministicKey.deserializeB58(null, pub58); chain = new DeterministicKeyChain(watchingKey); assertEquals(Utils.currentTimeSeconds(), chain.getEarliestKeyCreationTime()); chain.setLookaheadSize(10); assertEquals(key1.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint()); assertEquals(key2.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint()); final DeterministicKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE); assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint()); try { // Can't sign with a key from a watching chain. key.sign(Sha256Hash.ZERO_HASH); fail(); } catch (ECKey.MissingPrivateKeyException e) { // Ignored. } // Test we can serialize and deserialize a watching chain OK. List<Protos.Key> serialization = chain.serializeToProtobuf(); checkSerialization(serialization, "watching-wallet-serialization.txt"); chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0); final DeterministicKey rekey4 = chain.getKey(KeyChain.KeyPurpose.CHANGE); assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint()); } @Test(expected = IllegalStateException.class) public void watchingCannotEncrypt() throws Exception { final DeterministicKey accountKey = chain.getKeyByPath(DeterministicKeyChain.ACCOUNT_ZERO_PATH); chain = new DeterministicKeyChain(accountKey.getPubOnly()); chain = chain.toEncrypted("this doesn't make any sense"); } @Test public void bloom() { DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); // The filter includes the internal keys as well (for now), although I'm not sure if we should allow funds to // be received on them or not .... assertEquals(32, chain.numBloomFilterEntries()); BloomFilter filter = chain.getFilter(32, 0.001, 1); assertTrue(filter.contains(key1.getPubKey())); assertTrue(filter.contains(key1.getPubKeyHash())); assertTrue(filter.contains(key2.getPubKey())); assertTrue(filter.contains(key2.getPubKeyHash())); } private String protoToString(List<Protos.Key> keys) { StringBuilder sb = new StringBuilder(); for (Protos.Key key : keys) { sb.append(key.toString()); sb.append("\n"); } return sb.toString().trim(); } private String checkSerialization(List<Protos.Key> keys, String filename) { try { String sb = protoToString(keys); String expected = Resources.toString(getClass().getResource(filename), Charsets.UTF_8); assertEquals(expected, sb); return expected; } catch (IOException e) { throw new RuntimeException(e); } } }
apache-2.0
grisu48/Hyperion
org.feldspaten.hyperion/src/org/feldspaten/hyperion/html/Page.java
2022
package org.feldspaten.hyperion.html; import java.util.LinkedList; import java.util.List; public class Page extends Html { private String title = ""; /** If > 0, autorefresh is enabled with the given interval */ private int autoRefreshDelay = 0; /** Meta fields */ private List<String> metas = new LinkedList<>(); /** Stylesheet file */ private String stylesheet = null; @Override protected String generateHeader() { final StringBuffer buffer = new StringBuffer(); buffer.append("<!DOCTYPE html>"); buffer.append("\n"); buffer.append("<html><head>"); buffer.append("\n"); if (!title.isEmpty()) { buffer.append("<title>"); buffer.append(title); buffer.append("</title>\n"); } buffer.append("\n"); if (isAutoRefreshEnabled()) { buffer.append("<meta http-equiv=\"refresh\" content=\"" + autoRefreshDelay + "\">\n"); } // Add additional metas for (final String meta : metas) { buffer.append("<meta " + meta + " />\n"); } // Stylesheet, if applicable if (stylesheet != null) buffer.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + stylesheet + "\">\n"); buffer.append("</head>\n"); buffer.append("<body>"); return buffer.toString(); } @Override protected String generateFooter() { return "</body>"; } public void setStylesheetFile(final String url) { this.stylesheet = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getAutoRefreshDelay() { return autoRefreshDelay; } public void setAutoRefreshDelay(int autoRefreshDelay) { this.autoRefreshDelay = autoRefreshDelay; } public boolean isAutoRefreshEnabled() { return this.autoRefreshDelay > 0; } /** * Add a raw meta field The meta tag is added automatically, so you don't * need it here * * @param meta * to be added */ public void addMeta(final String meta) { if (meta == null || meta.trim().isEmpty()) return; this.metas.add(meta); } }
apache-2.0
swxca/coolWeather
coolWeather/app/src/main/java/com/xyz/coolweather/util/HttpCallbackListener.java
189
package com.xyz.coolweather.util; /** * Created by yesgxy520 on 6/1/2016. */ public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
apache-2.0
neurospeech/android-hypercube
hypercube/src/main/java/com/neurospeech/hypercube/ui/CustomViewPager.java
4186
package com.neurospeech.hypercube.ui; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import com.neurospeech.hypercube.HyperCubeApplication; /** * ViewPager creates 2 or more fragments even if only 1 fragment is to be displayed. * So we cannot use onCreate event to initialize fragment. * * So we will listen for Page Change event and call fragmentResumed method of PagerFragment. * * However, page change is not fired for first time, so we will call fragmentResumed method * after Adapter is set. */ public class CustomViewPager extends ViewPager { public boolean isAllowSwipe() { return allowSwipe; } public void setAllowSwipe(boolean allowSwipe) { this.allowSwipe = allowSwipe; } private boolean allowSwipe = false; public CustomViewPager(Context context) { super(context); addOnPageChangeListener(pageChangeListener); } public CustomViewPager(Context context, AttributeSet attrs) { super(context, attrs); addOnPageChangeListener(pageChangeListener); } @Override public void setAdapter(PagerAdapter adapter) { super.setAdapter(adapter); //invokeOnResume(); } public void invokeOnResume() { HyperCubeApplication.current.post(new Runnable() { @Override public void run() { if (getChildCount() > 0) { pageChangeListener.onPageSelected(getCurrentItem()); } } }, 500); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if(allowSwipe) return super.onInterceptTouchEvent(event); // Never allow swiping to switch between pages return false; } @Override public boolean onTouchEvent(MotionEvent event) { if(allowSwipe) return super.onTouchEvent(event); // Never allow swiping to switch between pages return false; } public PagerFragment getSelectedFragment() { return selectedFragment; } PagerFragment selectedFragment; PageChangeListener pageChangeListener = new PageChangeListener(); class PageChangeListener implements OnPageChangeListener{ /*public PageChangeListener() { super(); AndroidAppActivity.post(new Runnable() { @Override public void run() { if(getCurrentItem()!=-1){ onPageSelected(getCurrentItem()); } } }); }*/ @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if(selectedFragment != null){ selectedFragment.fragmentPaused(); } if(!(getAdapter() instanceof FragmentPagerAdapter)){ return; } PagerAdapter adapter = getAdapter(); Object obj = adapter.instantiateItem(CustomViewPager.this,position); if(obj instanceof PagerFragment){ selectedFragment = (PagerFragment)obj; postFragmentResumed((Fragment)selectedFragment); } } @Override public void onPageScrollStateChanged(int state) { } } /** * If view is not created, we should postpone calling fragmentResumed method. * @param fragment */ private void postFragmentResumed(final Fragment fragment) { if (fragment.getView() == null) { HyperCubeApplication.current.post(new Runnable() { @Override public void run() { postFragmentResumed(fragment); } }); return; } ((PagerFragment)fragment).fragmentResumed(); } }
apache-2.0
WinDriverTeam/windriver-java
src/main/java/ua/windriver/core/ConfiguredRequestFactory.java
714
package ua.windriver.core; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; public class ConfiguredRequestFactory { private static final Integer READ_TIMEOUT = EnvironmentProperties.HTTP_REQUEST_READ_TIMEOUT.readInteger(); private static final Integer CONNECT_TIMEOUT = EnvironmentProperties.HTTP_REQUEST_CONNECT_TIMEOUT.readInteger(); public static ClientHttpRequestFactory defaultFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(READ_TIMEOUT); factory.setConnectTimeout(CONNECT_TIMEOUT); return factory; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/transform/PutJsonUnmarshaller.java
4208
/* * 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.dynamodbv2.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.dynamodbv2.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Put JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PutJsonUnmarshaller implements Unmarshaller<Put, JsonUnmarshallerContext> { public Put unmarshall(JsonUnmarshallerContext context) throws Exception { Put put = new Put(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Item", targetDepth)) { context.nextToken(); put.setItem(new MapUnmarshaller<String, AttributeValue>(context.getUnmarshaller(String.class), AttributeValueJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("TableName", targetDepth)) { context.nextToken(); put.setTableName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ConditionExpression", targetDepth)) { context.nextToken(); put.setConditionExpression(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ExpressionAttributeNames", targetDepth)) { context.nextToken(); put.setExpressionAttributeNames(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context .getUnmarshaller(String.class)).unmarshall(context)); } if (context.testExpression("ExpressionAttributeValues", targetDepth)) { context.nextToken(); put.setExpressionAttributeValues(new MapUnmarshaller<String, AttributeValue>(context.getUnmarshaller(String.class), AttributeValueJsonUnmarshaller.getInstance()).unmarshall(context)); } if (context.testExpression("ReturnValuesOnConditionCheckFailure", targetDepth)) { context.nextToken(); put.setReturnValuesOnConditionCheckFailure(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return put; } private static PutJsonUnmarshaller instance; public static PutJsonUnmarshaller getInstance() { if (instance == null) instance = new PutJsonUnmarshaller(); return instance; } }
apache-2.0
eFaps/eFaps-Kernel
src/test/java/org/efaps/eql/PrintTest.java
17502
/* * Copyright 2003 - 2021 The eFaps 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 org.efaps.eql; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import org.apache.commons.lang3.reflect.FieldUtils; import org.efaps.admin.user.Person; import org.efaps.db.Context; import org.efaps.db.Instance; import org.efaps.eql.builder.Selectables; import org.efaps.eql2.StmtFlag; import org.efaps.eql2.bldr.AbstractSelectables; import org.efaps.mock.Mocks; import org.efaps.mock.datamodel.CI; import org.efaps.mock.datamodel.Company; import org.efaps.mock.datamodel.Company.CompanyBuilder; import org.efaps.test.AbstractTest; import org.efaps.test.SQLVerify; import org.efaps.util.EFapsException; import org.testng.annotations.Test; /** * The Class PrintTest. */ public class PrintTest extends AbstractTest { @Test public void testObjPrintOneAttribute() throws EFapsException { final String sql = String.format("select T0.%s,T0.ID from %s T0 where T0.ID = 4", Mocks.TestAttribute.getSQLColumnName(), Mocks.SimpleTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.SimpleType.getId() + ".4") .attribute(Mocks.TestAttribute.getName()) .stmt() .execute(); verify.verify(); } @Test public void testObjPrintOneAttributeUsingCI() throws EFapsException { final String sql = String.format("select T0.%s,T0.ID from %s T0 where T0.ID = 4", Mocks.TestAttribute.getSQLColumnName(), Mocks.SimpleTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.SimpleType.getId() + ".4") .attribute(CI.SimpleType.TestAttr) .stmt() .execute(); verify.verify(); } @Test public void testObjPrintVariousAttributes() throws EFapsException { final String sql = String.format("select T0.%s,T0.%s,T0.ID from %s T0 where T0.ID = 4", Mocks.AllAttrBooleanAttribute.getSQLColumnName(), Mocks.AllAttrStringAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .attribute(Mocks.AllAttrBooleanAttribute.getName(), Mocks.AllAttrStringAttribute.getName()) .stmt() .execute(); verify.verify(); } @Test public void testObjPrintVariousAttributes2() throws EFapsException { final String sql = String.format("select T0.%s,T0.%s,T0.ID from %s T0 where T0.ID = 4", Mocks.AllAttrBooleanAttribute.getSQLColumnName(), Mocks.AllAttrStringAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .attribute(Mocks.AllAttrBooleanAttribute.getName()) .attribute(Mocks.AllAttrStringAttribute.getName()) .stmt() .execute(); verify.verify(); } @Test public void testObjPrintAttributeWithAlias() throws EFapsException { final String sql = String.format("select T0.%s,T0.ID from %s T0 where T0.ID = 4", Mocks.AllAttrBooleanAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .attribute(Mocks.AllAttrBooleanAttribute.getName()) .as("BlaBla") .stmt() .execute(); verify.verify(); } @Test public void testObjPrintAttributesWithAlias() throws EFapsException { final String sql = String.format("select T0.%s,T0.%s,T0.ID from %s T0 where T0.ID = 4", Mocks.AllAttrBooleanAttribute.getSQLColumnName(), Mocks.AllAttrStringAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .attribute(Mocks.AllAttrBooleanAttribute.getName()).as("BlaBla") .attribute(Mocks.AllAttrStringAttribute.getName()).as("BlaBla2") .stmt() .execute(); verify.verify(); } @Test public void testObjPrintRespectsCompany() throws EFapsException { final Company company = new CompanyBuilder() .withName("Mock Company") .build(); Context.getThreadContext().setCompany(org.efaps.admin.user.Company.get(company.getId())); final String sql = String.format("select T0.%s,T0.ID from %s T0 where T0.ID = 4 and T0.%s = %s" , Mocks.CompanyStringAttribute.getSQLColumnName(), Mocks.CompanyTypeSQLTable.getSqlTableName(), Mocks.CompanyCompanyAttribute.getSQLColumnName(), company.getId()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.CompanyType.getId() + ".4") .attribute(Mocks.CompanyStringAttribute.getName()) .stmt() .execute(); verify.verify(); } @Test public void testPrintRespectsCompany() throws EFapsException { final Company company = new CompanyBuilder() .withName("Mock Company") .build(); Context.getThreadContext().setCompany(org.efaps.admin.user.Company.get(company.getId())); final String sql = String.format("select T0.%s,T0.ID from %s T0 where T0.%s = %s" , Mocks.CompanyStringAttribute.getSQLColumnName(), Mocks.CompanyTypeSQLTable.getSqlTableName(), Mocks.CompanyCompanyAttribute.getSQLColumnName(), company.getId()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print() .query(CI.CompanyType) .select() .attribute(CI.CompanyType.StringAttribute) .stmt() .execute(); verify.verify(); } @Test public void testPrintRespectsCompanyIndependent() throws EFapsException, IllegalAccessException { final Company company = new CompanyBuilder() .withName("Mock Company") .build(); Context.getThreadContext().setCompany(org.efaps.admin.user.Company.get(company.getId())); final Person person = Context.getThreadContext().getPerson(); FieldUtils.writeDeclaredField(person, "companies", Collections.singleton(company.getId()), true); final String sql = String.format("select T0.%s,T0.ID from %s T0 where T0.%s = %s" , Mocks.CompanyStringAttribute.getSQLColumnName(), Mocks.CompanyTypeSQLTable.getSqlTableName(), Mocks.CompanyCompanyAttribute.getSQLColumnName(), company.getId()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .with(StmtFlag.COMPANYINDEPENDENT) .print() .query(CI.CompanyType) .select() .attribute(CI.CompanyType.StringAttribute) .stmt() .execute(); verify.verify(); } @Test public void testPrintRespectsCompanyIndependentMultiple() throws EFapsException, IllegalAccessException { final Company company = new CompanyBuilder() .withName("Mock Company1") .build(); final Company company2 = new CompanyBuilder() .withName("Mock Company2") .build(); Context.getThreadContext().setCompany(org.efaps.admin.user.Company.get(company.getId())); final Person person = Context.getThreadContext().getPerson(); FieldUtils.writeDeclaredField(person, "companies", new LinkedHashSet<>(Arrays.asList(company.getId(), company2.getId())), true); final String sql = String.format("select T0.%s,T0.ID from %s T0 where T0.%s in (%s,%s)" , Mocks.CompanyStringAttribute.getSQLColumnName(), Mocks.CompanyTypeSQLTable.getSqlTableName(), Mocks.CompanyCompanyAttribute.getSQLColumnName(), company.getId(), company2.getId()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .with(StmtFlag.COMPANYINDEPENDENT) .print() .query(CI.CompanyType) .select() .attribute(CI.CompanyType.StringAttribute) .stmt() .execute(); verify.verify(); } @Test public void testLinkto() throws EFapsException { final String sql = String.format("select T1.%s,T0.ID,T1.ID from %s T0 " + "left join %s T1 on T0.%s=T1.ID where T0.ID = 4", Mocks.TestAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName(), Mocks.SimpleTypeSQLTable.getSqlTableName(), Mocks.AllAttrLinkAttribute.getSQLColumnName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .linkto(Mocks.AllAttrLinkAttribute.getName()) .attribute(Mocks.TestAttribute.getName()) .stmt() .execute(); verify.verify(); } @Test public void testAttributeAndLinkto() throws EFapsException { final String sql = String.format("select T0.%s,T1.%s,T0.ID,T1.ID from %s T0 " + "left join %s T1 on T0.%s=T1.ID where T0.ID = 4", Mocks.AllAttrStringAttribute.getSQLColumnName(), Mocks.TestAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName(), Mocks.SimpleTypeSQLTable.getSqlTableName(), Mocks.AllAttrLinkAttribute.getSQLColumnName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .attribute(Mocks.AllAttrStringAttribute.getName()) .linkto(Mocks.AllAttrLinkAttribute.getName()) .attribute(Mocks.TestAttribute.getName()) .stmt() .execute(); verify.verify(); } @Test public void testOIDSimpleType() throws EFapsException { final String sql = String.format("select T0.ID from %s T0 where T0.ID = 4", Mocks.AllAttrTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .oid() .stmt() .execute(); verify.verify(); } @Test public void testOIDTypedType() throws EFapsException { final String sql = String.format("select T0.ID,T0.TYPE from %s T0 where T0.ID = 4", Mocks.TypedTypeSQLTable.getSqlTableName(), Mocks.TypedType.getId()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.TypedType.getId() + ".4") .oid() .stmt() .execute(); verify.verify(); } @Test public void testPrintInstanceSelectCIAttr() throws EFapsException { final String sql = String.format("select T0.%s,T0.ID,T0.TYPE from %s T0 where T0.ID = 4", Mocks.TypedTypeTestAttr.getSQLColumnName(), Mocks.TypedTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Instance.get(Mocks.TypedType.getId() + ".4")) .select(CI.TypedType.TestAttr) .stmt() .execute(); verify.verify(); } @Test public void testPrintInstanceSelectAttr() throws EFapsException { final String sql = String.format("select T0.%s,T0.ID,T0.TYPE from %s T0 where T0.ID = 4", Mocks.TypedTypeTestAttr.getSQLColumnName(), Mocks.TypedTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Instance.get(Mocks.TypedType.getId() + ".4")) .select(AbstractSelectables.attribute(CI.TypedType.TestAttr.name)) .stmt() .execute(); verify.verify(); } @Test public void testPrintInstanceSelectCIAttrs() throws EFapsException { final String sql = String.format("select T0.%s,T0.%s,T0.ID,T0.TYPE from %s T0 where T0.ID = 4", Mocks.TypedTypeTestAttr.getSQLColumnName(), Mocks.TypedTypeIDAttribute.getSQLColumnName(), Mocks.TypedTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Instance.get(Mocks.TypedType.getId() + ".4")) .select(CI.TypedType.TestAttr, CI.TypedType.ID) .stmt() .execute(); verify.verify(); } @Test public void testPrintInstanceSelectLinkto() throws EFapsException { final String sql = String.format("select T1.%s,T0.ID,T1.ID from %s T0 " + "left join %s T1 on T0.%s=T1.ID where T0.ID = 4", Mocks.TestAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName(), Mocks.SimpleTypeSQLTable.getSqlTableName(), Mocks.AllAttrLinkAttribute.getSQLColumnName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Instance.get(Mocks.AllAttrType.getId() + ".4")) .select(Selectables.linkto(CI.AllAttrType.LinkAttribute).attr(CI.SimpleType.TestAttr)) .stmt() .execute(); verify.verify(); } @Test public void testPrintInstanceSelectAttributeAndLinkto() throws EFapsException { final String sql = String.format("select T0.%s,T1.%s,T0.ID,T1.ID from %s T0 " + "left join %s T1 on T0.%s=T1.ID where T0.ID = 4", Mocks.AllAttrStringAttribute.getSQLColumnName(), Mocks.TestAttribute.getSQLColumnName(), Mocks.AllAttrTypeSQLTable.getSqlTableName(), Mocks.SimpleTypeSQLTable.getSqlTableName(), Mocks.AllAttrLinkAttribute.getSQLColumnName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Mocks.AllAttrType.getId() + ".4") .select(CI.AllAttrType.StringAttribute, Selectables.linkto(CI.AllAttrType.LinkAttribute).attr(CI.SimpleType.TestAttr)) .stmt() .execute(); verify.verify(); } @Test public void testPrintInstanceSelectInstance() throws EFapsException { final String sql = String.format("select T0.ID,T0.TYPE from %s T0 where T0.ID = 4", Mocks.TypedTypeSQLTable.getSqlTableName()); final SQLVerify verify = SQLVerify.builder().withSql(sql).build(); EQL.builder() .print(Instance.get(Mocks.TypedType.getId() + ".4")) .select(AbstractSelectables.instance()) .stmt() .execute(); verify.verify(); } }
apache-2.0
NotFound403/WePay
src/main/java/cn/felord/wepay/ali/sdk/api/response/AlipayPassInstanceAddResponse.java
1571
package cn.felord.wepay.ali.sdk.api.response; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; import cn.felord.wepay.ali.sdk.api.AlipayResponse; /** * ALIPAY API: alipay.pass.instance.add response. * * @author auto create * @version $Id: $Id */ public class AlipayPassInstanceAddResponse extends AlipayResponse { private static final long serialVersionUID = 3196266918236896342L; /** * 接口调用返回结果信息 serialNumber:唯一核销凭证串号(必须由动态传参指定) passId:券唯一id operation:本次调用的操作类型,ADD errorCode:处理结果码(错误码) errorMsg:处理结果说明(错误说明) */ @ApiField("result") private String result; /** * 操作成功标识【true:成功;false:失败】 */ @ApiField("success") private String success; /** * <p>Setter for the field <code>result</code>.</p> * * @param result a {@link java.lang.String} object. */ public void setResult(String result) { this.result = result; } /** * <p>Getter for the field <code>result</code>.</p> * * @return a {@link java.lang.String} object. */ public String getResult( ) { return this.result; } /** * <p>Setter for the field <code>success</code>.</p> * * @param success a {@link java.lang.String} object. */ public void setSuccess(String success) { this.success = success; } /** * <p>Getter for the field <code>success</code>.</p> * * @return a {@link java.lang.String} object. */ public String getSuccess( ) { return this.success; } }
apache-2.0
lei-xia/helix
helix-core/src/test/java/org/apache/helix/integration/task/TestUnregisteredCommand.java
2328
package org.apache.helix.integration.task; /* * 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. */ import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestUnregisteredCommand extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); } @Test public void testUnregisteredCommand() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand("OtherCommand").setTimeoutPerTask(10000L).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); builder.addJob("JOB1", jobBuilder); _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")) .getPartitionState(0), TaskPartitionState.ERROR); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")) .getPartitionNumAttempts(0), 1); } }
apache-2.0
yukuai518/gobblin
gobblin-yarn/src/main/java/gobblin/yarn/GobblinYarnConfigurationKeys.java
4517
/* * Copyright (C) 2014-2016 LinkedIn Corp. 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. */ package gobblin.yarn; /** * A central place for configuration related constants of Gobblin on Yarn. * * @author Yinan Li */ public class GobblinYarnConfigurationKeys { public static final String GOBBLIN_YARN_PREFIX = "gobblin.yarn."; // General Gobblin Yarn application configuration properties. public static final String APPLICATION_NAME_KEY = GOBBLIN_YARN_PREFIX + "app.name"; public static final String APP_QUEUE_KEY = GOBBLIN_YARN_PREFIX + "app.queue"; public static final String APP_REPORT_INTERVAL_MINUTES_KEY = GOBBLIN_YARN_PREFIX + "app.report.interval.minutes"; public static final String MAX_GET_APP_REPORT_FAILURES_KEY = GOBBLIN_YARN_PREFIX + "max.get.app.report.failures"; public static final String EMAIL_NOTIFICATION_ON_SHUTDOWN_KEY = GOBBLIN_YARN_PREFIX + "email.notification.on.shutdown"; // Gobblin Yarn ApplicationMaster configuration properties. public static final String APP_MASTER_MEMORY_MBS_KEY = GOBBLIN_YARN_PREFIX + "app.master.memory.mbs"; public static final String APP_MASTER_CORES_KEY = GOBBLIN_YARN_PREFIX + "app.master.cores"; public static final String APP_MASTER_JARS_KEY = GOBBLIN_YARN_PREFIX + "app.master.jars"; public static final String APP_MASTER_FILES_LOCAL_KEY = GOBBLIN_YARN_PREFIX + "app.master.files.local"; public static final String APP_MASTER_FILES_REMOTE_KEY = GOBBLIN_YARN_PREFIX + "app.master.files.remote"; public static final String APP_MASTER_WORK_DIR_NAME = "appmaster"; public static final String APP_MASTER_JVM_ARGS_KEY = GOBBLIN_YARN_PREFIX + "app.master.jvm.args"; // Gobblin Yarn container configuration properties. public static final String INITIAL_CONTAINERS_KEY = GOBBLIN_YARN_PREFIX + "initial.containers"; public static final String CONTAINER_MEMORY_MBS_KEY = GOBBLIN_YARN_PREFIX + "container.memory.mbs"; public static final String CONTAINER_CORES_KEY = GOBBLIN_YARN_PREFIX + "container.cores"; public static final String CONTAINER_JARS_KEY = GOBBLIN_YARN_PREFIX + "container.jars"; public static final String CONTAINER_FILES_LOCAL_KEY = GOBBLIN_YARN_PREFIX + "container.files.local"; public static final String CONTAINER_FILES_REMOTE_KEY = GOBBLIN_YARN_PREFIX + "container.files.remote"; public static final String CONTAINER_WORK_DIR_NAME = "container"; public static final String CONTAINER_JVM_ARGS_KEY = GOBBLIN_YARN_PREFIX + "container.jvm.args"; public static final String CONTAINER_HOST_AFFINITY_ENABLED = GOBBLIN_YARN_PREFIX + "container.affinity.enabled"; // Helix configuration properties. public static final String HELIX_INSTANCE_MAX_RETRIES = GOBBLIN_YARN_PREFIX + "helix.instance.max.retries"; // Security and authentication configuration properties. public static final String KEYTAB_FILE_PATH = GOBBLIN_YARN_PREFIX + "keytab.file.path"; public static final String KEYTAB_PRINCIPAL_NAME = GOBBLIN_YARN_PREFIX + "keytab.principal.name"; public static final String TOKEN_FILE_NAME = ".token"; public static final String LOGIN_INTERVAL_IN_MINUTES = GOBBLIN_YARN_PREFIX + "login.interval.minutes"; public static final String TOKEN_RENEW_INTERVAL_IN_MINUTES = GOBBLIN_YARN_PREFIX + "token.renew.interval.minutes"; // Resource/dependencies configuration properties. public static final String LIB_JARS_DIR_KEY = GOBBLIN_YARN_PREFIX + "lib.jars.dir"; public static final String LOGS_SINK_ROOT_DIR_KEY = GOBBLIN_YARN_PREFIX + "logs.sink.root.dir"; public static final String LIB_JARS_DIR_NAME = "_libjars"; public static final String APP_JARS_DIR_NAME = "_appjars"; public static final String APP_FILES_DIR_NAME = "_appfiles"; public static final String APP_LOGS_DIR_NAME = "_applogs"; // Other misc configuration properties. public static final String LOG_COPIER_SCHEDULER = GOBBLIN_YARN_PREFIX + "log.copier.scheduler"; public static final String LOG_COPIER_MAX_FILE_SIZE = GOBBLIN_YARN_PREFIX + "log.copier.max.file.size"; public static final String GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE = "log4j-yarn.properties"; }
apache-2.0
dkovalkov/Sketcher-Tab
src/org/sketchertab/style/SketchyStyle.java
2060
package org.sketchertab.style; import android.graphics.Canvas; import android.graphics.PointF; import java.util.ArrayList; import java.util.Map; class SketchyStyle extends StyleBrush { private float prevX; private float prevY; private float density; private ArrayList<PointF> points = new ArrayList<PointF>(); { paint.setAntiAlias(true); } SketchyStyle(float density) { this.density = density; } @Override public void setOpacity(int opacity) { super.setOpacity((int) (opacity * 0.5f)); } public void stroke(Canvas c, float x, float y) { PointF current = new PointF(x, y); points.add(current); c.drawLine(prevX, prevY, x, y, paint); float dx; float dy; float length; for (int i = 0, max = points.size(); i < max; i++) { PointF point = points.get(i); dx = point.x - current.x; dy = point.y - current.y; length = dx * dx + dy * dy; float maxLength = 4000 * density; if (length < maxLength && Math.random() > (length / maxLength / 2)) { float ddx = dx * 0.2F; float ddy = dy * 0.2F; c.drawLine(current.x + ddx, current.y + ddy, point.x - ddx, point.y - ddy, paint); } } prevX = x; prevY = y; } public void strokeStart(float x, float y) { prevX = x; prevY = y; } public void draw(Canvas c) { } public void saveState(Map<StylesFactory.BrushType, Object> state) { ArrayList<PointF> points = new ArrayList<PointF>(); points.addAll(this.points); state.put(StylesFactory.BrushType.SKETCHY, points); } @SuppressWarnings("unchecked") public void restoreState(Map<StylesFactory.BrushType, Object> state) { this.points.clear(); ArrayList<PointF> points = (ArrayList<PointF>) state .get(StylesFactory.BrushType.SKETCHY); this.points.addAll(points); } }
apache-2.0
dagix5/backbox
BackBox/src/it/backbox/client/rest/bean/BoxError.java
255
package it.backbox.client.rest.bean; import com.google.api.client.util.Key; public class BoxError { @Key public String type; @Key public int status; @Key public String code; @Key public BoxContextInfo context_info; }
apache-2.0
jiangjiguang/lib-java
src/com/jiangjg/lib/EffectiveJava/Beetle.java
700
package com.jiangjg.lib.EffectiveJava; class Insect{ private int i=9; protected int j; private int xx=printInit("xx"); public Insect() { System.out.println("i=" + i + ", j=" +j); j=39; } private static int x1=printInit("static I1"); static int printInit(String s){ System.out.println(s); return 47; } } public class Beetle extends Insect { public Beetle(){ System.out.println("k=" +k); System.out.println("j="+j); } private int k = printInit("B.k"); private static int x2=printInit("static 2"); /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("bb"); Beetle beetle = new Beetle(); } }
apache-2.0
ganyao114/SwiftAndroid
eventposter/src/main/java/net/swiftos/eventposter/core/EventPoster.java
1951
package net.swiftos.eventposter.core; import android.app.Application; import net.swiftos.eventposter.factory.HandlerFactory; import net.swiftos.eventposter.modules.activitylife.handler.ActivityLifeHandler; import net.swiftos.eventposter.template.IHandler; /** * Created by gy939 on 2016/10/3. */ public class EventPoster { private static Application app; public static <T extends IHandler> T with(Class<T> handlerType){ IHandler handler = HandlerFactory.getHandler(handlerType); if (handler == null) return null; return (T) handler; } public static void register(Object object){ Injecter.inject(object); } public static void unRegister(Object object){ Injecter.remove(object); } public static void registerDeep(Object object){ Injecter.injectDeep(object); } public static void unRegisterDeep(Object object){ Injecter.removeDeep(object); } public static void init(Application application){ app = application; HandlerFactory.getHandler(ActivityLifeHandler.class).init(application); } public static void destroy(Application application){ app = null; HandlerFactory.getHandler(ActivityLifeHandler.class).destroy(application); } public static Application getApp(){ return app; } public static void preLoad(final Class[] classes){ new Thread(new Runnable() { @Override public void run() { for (Class clazz:classes){ Injecter.load(null,clazz); } } }).start(); } public static void preLoadDeep(final Class[] classes){ new Thread(new Runnable() { @Override public void run() { for (Class clazz:classes){ Injecter.loadDeep(null,clazz); } } }).start(); } }
apache-2.0
jmacglashan/burlap
src/main/java/burlap/domain/singleagent/gridworld/GridWorldRewardFunction.java
4390
package burlap.domain.singleagent.gridworld; import burlap.domain.singleagent.gridworld.state.GridWorldState; import burlap.mdp.core.action.Action; import burlap.mdp.core.state.State; import burlap.mdp.singleagent.model.RewardFunction; /** * This class is used for defining reward functions in grid worlds that are a function of cell of the world to which * the agent transitions. That is, a double matrix (called rewardMatrix) the size of the grid world is stored. In an agent transitions * to cell x,y, then they will receive the double value stored in rewardMatrix[x][y]. The rewards returned for transitioning to an agent position * may be set with the {@link #setReward(int, int, double)} method. * <p> * This reward function is useful for simple grid worlds without any location objects or worlds for which the rewards are independent * of location objects. An alternative to this class is to define worlds with location objects and use the atLocation propositional function * and location types to define rewards. * @author James MacGlashan * */ public class GridWorldRewardFunction implements RewardFunction { protected double [][] rewardMatrix; protected int width; protected int height; /** * Initializes the reward function for a grid world of size width and height and initializes the reward values everywhere to initializingReward. * The reward returned from specific agent positions may be changed with the {@link #setReward(int, int, double)} method. * @param width the width of the grid world * @param height the height of the grid world * @param initializingReward the reward to which all agent position transitions are initialized to return. */ public GridWorldRewardFunction(int width, int height, double initializingReward){ this.initialize(width, height, initializingReward); } /** * Initializes the reward function for a grid world of size width and height and initializes the reward values everywhere to 0. * The reward returned from specific agent positions may be changed with the {@link #setReward(int, int, double)} method. * @param width the width of the grid world * @param height the height of the grid world */ public GridWorldRewardFunction(int width, int height){ this(width, height, 0.); } /** * Initializes the reward matrix. * @param width the width of the grid world * @param height the height of the grid world * @param initializingReward the reward to which all agent position transitions are initialized to return. */ protected void initialize(int width, int height, double initializingReward){ this.rewardMatrix = new double[width][height]; this.width = width; this.height = height; for(int i = 0; i < this.width; i++){ for(int j = 0; j < this.height; j++){ this.rewardMatrix[i][j] = initializingReward; } } } /** * Returns the reward matrix this reward function uses. Changes to the returned matrix *will* change this reward function. * rewardMatrix[x][y] specifies the reward the agent will receive for transitioning to position x,y. * @return the reward matrix this reward function uses */ public double [][] getRewardMatrix(){ return this.rewardMatrix; } /** * Sets the reward the agent will receive to transitioning to position x, y * @param x the x position * @param y the y position * @param r the reward the agent will receive to transitioning to position x, y */ public void setReward(int x, int y, double r){ this.rewardMatrix[x][y] = r; } /** * Returns the reward this reward function will return when the agent transitions to position x, y. * @param x the x position * @param y the y position * @return the reward this reward function will return when the agent transitions to position x, y. */ public double getRewardForTransitionsTo(int x, int y){ return this.rewardMatrix[x][y]; } @Override public double reward(State s, Action a, State sprime) { int x = ((GridWorldState)sprime).agent.x; int y = ((GridWorldState)sprime).agent.y; if(x >= this.width || x < 0 || y >= this.height || y < 0){ throw new RuntimeException("GridWorld reward matrix is only defined for a " + this.width + "x" + this.height +" world, but the agent transitioned to position (" + x + "," + y + "), which is outside the bounds."); } double r = this.rewardMatrix[x][y]; return r; } }
apache-2.0
intuit/wasabi
modules/repository-datastax/src/main/java/com/intuit/wasabi/repository/FavoritesRepository.java
2054
/******************************************************************************* * Copyright 2016 Intuit * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.intuit.wasabi.repository; import com.intuit.wasabi.authenticationobjects.UserInfo; import com.intuit.wasabi.experimentobjects.Experiment; import java.util.List; /** * Handles favorites inside the database. */ public interface FavoritesRepository { /** * Retrieves the list of favorites. * * @param username the requesting user * @return the list of favorites */ List<Experiment.ID> getFavorites(UserInfo.Username username); /** * Adds an experiment ID to the favorites. * * @param username the requesting user * @param experimentID the experiment to favorite * @return the updated list of favorites * @throws RepositoryException if the favorites can not be updated */ List<Experiment.ID> addFavorite(UserInfo.Username username, Experiment.ID experimentID) throws RepositoryException; /** * Removes an experiment from the favorites. * * @param username the requesting user * @param experimentID the experiment to unfavorite * @return the updated list of favorites * @throws RepositoryException if the favorites can not be updated */ List<Experiment.ID> deleteFavorite(UserInfo.Username username, Experiment.ID experimentID) throws RepositoryException; }
apache-2.0
kubernetes-client/java
fluent/src/main/java/io/kubernetes/client/openapi/models/V2MetricStatusFluent.java
8415
/* Copyright 2022 The Kubernetes 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 io.kubernetes.client.openapi.models; /** Generated */ public interface V2MetricStatusFluent< A extends io.kubernetes.client.openapi.models.V2MetricStatusFluent<A>> extends io.kubernetes.client.fluent.Fluent<A> { /** * This method has been deprecated, please use method buildContainerResource instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus getContainerResource(); public io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus buildContainerResource(); public A withContainerResource( io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus containerResource); public java.lang.Boolean hasContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> withNewContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> withNewContainerResourceLike( io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> editContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> editOrNewContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> editOrNewContainerResourceLike( io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus item); /** * This method has been deprecated, please use method buildExternal instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ExternalMetricStatus getExternal(); public io.kubernetes.client.openapi.models.V2ExternalMetricStatus buildExternal(); public A withExternal(io.kubernetes.client.openapi.models.V2ExternalMetricStatus external); public java.lang.Boolean hasExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> withNewExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> withNewExternalLike(io.kubernetes.client.openapi.models.V2ExternalMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> editExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> editOrNewExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> editOrNewExternalLike(io.kubernetes.client.openapi.models.V2ExternalMetricStatus item); /** * This method has been deprecated, please use method buildObject instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ObjectMetricStatus getObject(); public io.kubernetes.client.openapi.models.V2ObjectMetricStatus buildObject(); public A withObject(io.kubernetes.client.openapi.models.V2ObjectMetricStatus _object); public java.lang.Boolean hasObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> withNewObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> withNewObjectLike( io.kubernetes.client.openapi.models.V2ObjectMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> editObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> editOrNewObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> editOrNewObjectLike(io.kubernetes.client.openapi.models.V2ObjectMetricStatus item); /** * This method has been deprecated, please use method buildPods instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2PodsMetricStatus getPods(); public io.kubernetes.client.openapi.models.V2PodsMetricStatus buildPods(); public A withPods(io.kubernetes.client.openapi.models.V2PodsMetricStatus pods); public java.lang.Boolean hasPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> withNewPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> withNewPodsLike( io.kubernetes.client.openapi.models.V2PodsMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> editPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> editOrNewPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> editOrNewPodsLike( io.kubernetes.client.openapi.models.V2PodsMetricStatus item); /** * This method has been deprecated, please use method buildResource instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ResourceMetricStatus getResource(); public io.kubernetes.client.openapi.models.V2ResourceMetricStatus buildResource(); public A withResource(io.kubernetes.client.openapi.models.V2ResourceMetricStatus resource); public java.lang.Boolean hasResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> withNewResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> withNewResourceLike(io.kubernetes.client.openapi.models.V2ResourceMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> editResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> editOrNewResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> editOrNewResourceLike(io.kubernetes.client.openapi.models.V2ResourceMetricStatus item); public java.lang.String getType(); public A withType(java.lang.String type); public java.lang.Boolean hasType(); /** Method is deprecated. use withType instead. */ @java.lang.Deprecated public A withNewType(java.lang.String original); public interface ContainerResourceNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<N>> { public N and(); public N endContainerResource(); } public interface ExternalNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ExternalMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<N>> { public N and(); public N endExternal(); } public interface ObjectNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ObjectMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<N>> { public N and(); public N endObject(); } public interface PodsNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2PodsMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<N>> { public N and(); public N endPods(); } public interface ResourceNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ResourceMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<N>> { public N and(); public N endResource(); } }
apache-2.0
cping/LGame
Java/old/OpenGL-1.0(old_ver)/Loon-backend-JavaSE/src/loon/action/sprite/painting/Drawable.java
4167
/** * Copyright 2008 - 2012 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * @project loon * @author cping * @email:javachenpeng@yahoo.com * @version 0.3.3 */ package loon.action.sprite.painting; import loon.LInput; import loon.LKey; import loon.LTouch; import loon.action.sprite.SpriteBatch; import loon.core.LRelease; import loon.core.geom.Vector2f; import loon.core.timer.GameTime; import loon.utils.MathUtils; public abstract class Drawable implements LRelease { public boolean IsPopup = false; public float transitionOnTime = 0; public float transitionOffTime = 0; public Vector2f bottomLeftPosition = new Vector2f(); public DrawableScreen drawableScreen; boolean otherScreenHasFocus; protected float _transitionPosition = 1f; protected DrawableState _drawableState = DrawableState.TransitionOn; protected boolean _enabled = true; protected boolean _isExiting = false; public DrawableScreen getDrawableScreen() { return drawableScreen; } public void exitScreen() { if (this.transitionOffTime == 0f) { this.drawableScreen.removeDrawable(this); } else { this._isExiting = true; } } public Vector2f getBottomLeftPosition() { return bottomLeftPosition; } public DrawableState getDrawableState() { return _drawableState; } public void setDrawableState(DrawableState state) { _drawableState = state; } public float getTransitionAlpha() { return (1f - this._transitionPosition); } public float getTransitionPosition() { return _transitionPosition; } public abstract void handleInput(LInput input); public boolean isActive() { return !otherScreenHasFocus && (_drawableState == DrawableState.TransitionOn || _drawableState == DrawableState.Active); } public boolean isExiting() { return _isExiting; } public abstract void loadContent(); public abstract void unloadContent(); public abstract void draw(SpriteBatch batch, GameTime elapsedTime); public abstract void update(GameTime elapsedTime); public void update(GameTime gameTime, boolean otherScreenHasFocus, boolean coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (this._isExiting) { this._drawableState = DrawableState.TransitionOff; if (!this.updateTransition(gameTime, this.transitionOffTime, 1)) { this.drawableScreen.removeDrawable(this); } } else if (coveredByOtherScreen) { if (this.updateTransition(gameTime, this.transitionOffTime, 1)) { this._drawableState = DrawableState.TransitionOff; } else { this._drawableState = DrawableState.Hidden; } } else if (this.updateTransition(gameTime, this.transitionOnTime, -1)) { this._drawableState = DrawableState.TransitionOn; } else { this._drawableState = DrawableState.Active; } update(gameTime); } private boolean updateTransition(GameTime gameTime, float time, int direction) { float num; if (time == 0f) { num = 1f; } else { num = (gameTime.getElapsedGameTime() / time); } this._transitionPosition += num * direction; if (((direction < 0) && (this._transitionPosition <= 0f)) || ((direction > 0) && (this._transitionPosition >= 1f))) { this._transitionPosition = MathUtils.clamp( this._transitionPosition, 0f, 1f); return false; } return true; } public abstract void pressed(LTouch e); public abstract void released(LTouch e); public abstract void move(LTouch e); public abstract void pressed(LKey e); public abstract void released(LKey e); public boolean isEnabled() { return _enabled; } public void setEnabled(boolean e) { this._enabled = e; } public void dispose() { this._enabled = false; } }
apache-2.0
slipperyseal/silicone
silicone/src/main/java/net/catchpole/silicone/resource/ClasspathResourceSource.java
1023
package net.catchpole.silicone.resource; // Copyright 2014 catchpole.net // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import java.io.InputStream; /** */ public class ClasspathResourceSource implements ResourceSource { private Class resourceClass; public ClasspathResourceSource(Class resourceClass) { this.resourceClass = resourceClass; } public InputStream getResourceStream(String name) { return this.resourceClass.getResourceAsStream(name); } }
apache-2.0
52North/javaPS
engine/src/main/java/org/n52/javaps/algorithm/annotation/AbstractDataBinding.java
2570
/* * Copyright 2016-2021 52°North Spatial Information Research GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.javaps.algorithm.annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Member; import java.lang.reflect.Type; import java.util.Objects; import org.n52.javaps.description.TypedDataDescription; import com.google.common.primitives.Primitives; /** * TODO JavaDoc * * @author Tom Kunicki, Christian Autermann */ abstract class AbstractDataBinding<M extends AccessibleObject & Member, D extends TypedDataDescription<?>> extends AnnotationBinding<M> { private D description; AbstractDataBinding(M member) { super(member); } public abstract Type getMemberType(); public Type getType() { return getMemberType(); } public Type getPayloadType() { Type type = getType(); if (isEnum(type)) { return String.class; } if (type instanceof Class<?>) { return Primitives.wrap((Class<?>) type); } return type; } protected Object outputToPayload(Object outputValue) { Type type = getType(); if (isEnum(type)) { return ((Enum<?>) outputValue).name(); } else { return outputValue; } } @SuppressWarnings({ "unchecked", "rawtypes" }) protected Object payloadToInput(Object payload) { Type type = getType(); if (isEnum(type)) { Class<? extends Enum> enumClass = (Class<? extends Enum>) type; return Enum.valueOf(enumClass, (String) payload); } return payload; } public boolean isEnum() { return isEnum(getType()); } public static boolean isEnum(Type type) { return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); } public void setDescription(D description) { this.description = Objects.requireNonNull(description); } public D getDescription() { return description; } }
apache-2.0
LuzernWGProjects/Schurter
WebCrawler/src/ch/ice/exceptions/FileParserNotAvailableException.java
290
package ch.ice.exceptions; public class FileParserNotAvailableException extends Exception { private static final long serialVersionUID = 3039694748225707627L; public FileParserNotAvailableException() {} public FileParserNotAvailableException(String message){ super(message); } }
apache-2.0
searchtechnologies/heritrix-connector
engine-3.1.1/engine/src/main/java/org/archive/crawler/restlet/ScriptResource.java
13729
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.crawler.restlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.archive.util.TextUtils; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.resource.Representation; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.restlet.resource.WriterRepresentation; /** * Restlet Resource which runs an arbitrary script, which is supplied * with variables pointing to the job and appContext, from which all * other live crawl objects are reachable. * * Any JSR-223 script engine that's properly discoverable on the * classpath will be available from a drop-down selector. * * @contributor gojomo */ public class ScriptResource extends JobRelatedResource { static ScriptEngineManager MANAGER = new ScriptEngineManager(); // oddly, ordering is different each call to getEngineFactories, so cache static LinkedList<ScriptEngineFactory> FACTORIES = new LinkedList<ScriptEngineFactory>(); static { FACTORIES.addAll(MANAGER.getEngineFactories()); // Sort factories alphabetically so that they appear in the UI consistently Collections.sort(FACTORIES, new Comparator<ScriptEngineFactory>() { @Override public int compare(ScriptEngineFactory sef1, ScriptEngineFactory sef2) { return sef1.getEngineName().compareTo(sef2.getEngineName()); } }); } String script = ""; Exception ex = null; int linesExecuted = 0; String rawOutput = ""; String htmlOutput = ""; String chosenEngine = FACTORIES.isEmpty() ? "" : FACTORIES.getFirst().getNames().get(0); public ScriptResource(Context ctx, Request req, Response res) throws ResourceException { super(ctx, req, res); setModifiable(true); getVariants().add(new Variant(MediaType.TEXT_HTML)); getVariants().add(new Variant(MediaType.APPLICATION_XML)); } @Override public void acceptRepresentation(Representation entity) throws ResourceException { Form form = getRequest().getEntityAsForm(); chosenEngine = form.getFirstValue("engine"); script = form.getFirstValue("script"); if(StringUtils.isBlank(script)) { script=""; } ScriptEngine eng = MANAGER.getEngineByName(chosenEngine); StringWriter rawString = new StringWriter(); PrintWriter rawOut = new PrintWriter(rawString); eng.put("rawOut", rawOut); StringWriter htmlString = new StringWriter(); PrintWriter htmlOut = new PrintWriter(htmlString); eng.put("htmlOut", htmlOut); eng.put("job", cj); eng.put("appCtx", cj.getJobContext()); eng.put("scriptResource", this); try { eng.eval(script); linesExecuted = script.split("\r?\n").length; } catch (ScriptException e) { ex = e; } catch (RuntimeException e) { ex = e; } finally { rawOut.flush(); rawOutput = rawString.toString(); htmlOut.flush(); htmlOutput = htmlString.toString(); eng.put("rawOut", null); eng.put("htmlOut", null); eng.put("job", null); eng.put("appCtx", null); eng.put("scriptResource", null); } //TODO: log script, results somewhere; job log INFO? getResponse().setEntity(represent()); } public Representation represent(Variant variant) throws ResourceException { Representation representation; if (variant.getMediaType() == MediaType.APPLICATION_XML) { representation = new WriterRepresentation(MediaType.APPLICATION_XML) { public void write(Writer writer) throws IOException { XmlMarshaller.marshalDocument(writer,"script", makePresentableMap()); } }; } else { representation = new WriterRepresentation(MediaType.TEXT_HTML) { public void write(Writer writer) throws IOException { ScriptResource.this.writeHtml(writer); } }; } // TODO: remove if not necessary in future? representation.setCharacterSet(CharacterSet.UTF_8); return representation; } protected List<String> getAvailableActions() { List<String> actions = new LinkedList<String>(); actions.add("rescan"); actions.add("add"); actions.add("create"); return actions; } protected Collection<Map<String,String>> getAvailableScriptEngines() { List<Map<String,String>> engines = new LinkedList<Map<String,String>>(); for (ScriptEngineFactory f: FACTORIES) { Map<String,String> engine = new LinkedHashMap<String, String>(); engine.put("engine", f.getNames().get(0)); engine.put("language", f.getLanguageName()); engines.add(engine); } return engines; } protected Collection<Map<String,String>> getAvailableGlobalVariables() { List<Map<String,String>> vars = new LinkedList<Map<String,String>>(); Map<String,String> var; var = new LinkedHashMap<String,String>(); var.put("variable", "rawOut"); var.put("description", "a PrintWriter for arbitrary text output to this page"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "htmlOut"); var.put("description", "a PrintWriter for HTML output to this page"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "job"); var.put("description", "the current CrawlJob instance"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "appCtx"); var.put("description", "current job ApplicationContext, if any"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "scriptResource"); var.put("description", "the ScriptResource implementing this page, which offers utility methods"); vars.add(var); return vars; } /** * Constructs a nested Map data structure with the information represented * by this Resource. The result is particularly suitable for use with with * {@link XmlMarshaller}. * * @return the nested Map data structure */ protected LinkedHashMap<String,Object> makePresentableMap() { LinkedHashMap<String,Object> info = new LinkedHashMap<String,Object>(); String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if(!baseRef.endsWith("/")) { baseRef += "/"; } Reference baseRefRef = new Reference(baseRef); info.put("crawlJobShortName", cj.getShortName()); info.put("crawlJobUrl", new Reference(baseRefRef, "..").getTargetRef()); info.put("availableScriptEngines", getAvailableScriptEngines()); info.put("availableGlobalVariables", getAvailableGlobalVariables()); if(linesExecuted>0) { info.put("linesExecuted", linesExecuted); } if(ex!=null) { info.put("exception", ex); } if(StringUtils.isNotBlank(rawOutput)) { info.put("rawOutput", rawOutput); } if(StringUtils.isNotBlank(htmlOutput)) { info.put("htmlOutput", htmlOutput); } return info; } protected void writeHtml(Writer writer) { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if (!baseRef.endsWith("/")) baseRef += "/"; PrintWriter pw = new PrintWriter(writer); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>Script in "+cj.getShortName()+"</title>"); pw.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + getStylesheetRef() + "\">"); pw.println("<link rel='stylesheet' href='" + getStaticRef("codemirror/codemirror.css") + "'>"); pw.println("<link rel='stylesheet' href='" + getStaticRef("codemirror/util/dialog.css") + "'>"); pw.println("<script src='" + getStaticRef("codemirror/codemirror.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/mode/groovy.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/mode/clike.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/mode/javascript.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/util/dialog.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/util/searchcursor.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/util/search.js") + "'></script>"); pw.println("</head>"); pw.println("<body>"); pw.println("<h1>Execute script for job <i><a href='/engine/job/" +TextUtils.urlEscape(cj.getShortName()) +"'>"+cj.getShortName()+"</a></i></h1>"); // output of previous script, if any if(linesExecuted>0) { pw.println("<span class='success'>"+linesExecuted+" lines executed</span>"); } if(ex!=null) { pw.println("<pre style='color:red; height:150px; overflow:auto'>"); ex.printStackTrace(pw); pw.println("</pre>"); } if(StringUtils.isNotBlank(htmlOutput)) { pw.println("<fieldset><legend>htmlOut</legend>"); pw.println(htmlOutput); pw.println("</fieldset>"); } if(StringUtils.isNotBlank(rawOutput)) { pw.println("<fieldset><legend>rawOut</legend><pre>"); pw.println(StringEscapeUtils.escapeHtml(rawOutput)); pw.println("</pre></fieldset>"); } pw.println("<form method='POST'>"); pw.println("<input type='submit' value='execute'>"); pw.println("<select name='engine' id='selectEngine'>");; for(ScriptEngineFactory f : FACTORIES) { String opt = f.getNames().get(0); pw.println("<option " +(opt.equals(chosenEngine)?" selected='selected' ":"") +"value='"+opt+"'>"+f.getLanguageName()+"</option>"); } pw.println("</select>"); pw.println("<textarea rows='20' style='width:100%' name=\'script\' id='editor'>"+script+"</textarea>"); pw.println("<input type='submit' value='execute'></input>"); pw.println("</form>"); pw.println( "The script will be executed in an engine preloaded " + "with (global) variables:\n<ul>\n" + "<li><code>rawOut</code>: a PrintWriter for arbitrary text output to this page</li>\n" + "<li><code>htmlOut</code>: a PrintWriter for HTML output to this page</li>\n" + "<li><code>job</code>: the current CrawlJob instance</li>\n" + "<li><code>appCtx</code>: current job ApplicationContext, if any</li>\n" + "<li><code>scriptResource</code>: the ScriptResource implementing this " + "page, which offers utility methods</li>\n" + "</ul>"); pw.println("<script>"); pw.println("var modemap = {beanshell: 'text/x-java', groovy: 'groovy', js: 'javascript'};"); pw.println("var selectEngine = document.getElementById('selectEngine');"); pw.println("var editor = document.getElementById('editor');"); pw.println("var cmopts = {"); pw.println(" mode: modemap[selectEngine.value],"); pw.println(" lineNumbers: true, autofocus: true, indentUnit: 4"); pw.println("}"); pw.println("var cm = CodeMirror.fromTextArea(editor, cmopts);"); pw.println("selectEngine.onchange = function(e) { cm.setOption('mode', modemap[selectEngine.value]); }"); pw.println("</script>"); pw.println("</body>"); pw.println("</html>"); pw.flush(); } }
apache-2.0
googleapis/java-vision
proto-google-cloud-vision-v1/src/main/java/com/google/cloud/vision/v1/ParagraphOrBuilder.java
5587
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vision/v1/text_annotation.proto package com.google.cloud.vision.v1; public interface ParagraphOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.vision.v1.Paragraph) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Additional information detected for the paragraph. * </pre> * * <code>.google.cloud.vision.v1.TextAnnotation.TextProperty property = 1;</code> * * @return Whether the property field is set. */ boolean hasProperty(); /** * * * <pre> * Additional information detected for the paragraph. * </pre> * * <code>.google.cloud.vision.v1.TextAnnotation.TextProperty property = 1;</code> * * @return The property. */ com.google.cloud.vision.v1.TextAnnotation.TextProperty getProperty(); /** * * * <pre> * Additional information detected for the paragraph. * </pre> * * <code>.google.cloud.vision.v1.TextAnnotation.TextProperty property = 1;</code> */ com.google.cloud.vision.v1.TextAnnotation.TextPropertyOrBuilder getPropertyOrBuilder(); /** * * * <pre> * The bounding box for the paragraph. * The vertices are in the order of top-left, top-right, bottom-right, * bottom-left. When a rotation of the bounding box is detected the rotation * is represented as around the top-left corner as defined when the text is * read in the 'natural' orientation. * For example: * * when the text is horizontal it might look like: * 0----1 * | | * 3----2 * * when it's rotated 180 degrees around the top-left corner it becomes: * 2----3 * | | * 1----0 * and the vertex order will still be (0, 1, 2, 3). * </pre> * * <code>.google.cloud.vision.v1.BoundingPoly bounding_box = 2;</code> * * @return Whether the boundingBox field is set. */ boolean hasBoundingBox(); /** * * * <pre> * The bounding box for the paragraph. * The vertices are in the order of top-left, top-right, bottom-right, * bottom-left. When a rotation of the bounding box is detected the rotation * is represented as around the top-left corner as defined when the text is * read in the 'natural' orientation. * For example: * * when the text is horizontal it might look like: * 0----1 * | | * 3----2 * * when it's rotated 180 degrees around the top-left corner it becomes: * 2----3 * | | * 1----0 * and the vertex order will still be (0, 1, 2, 3). * </pre> * * <code>.google.cloud.vision.v1.BoundingPoly bounding_box = 2;</code> * * @return The boundingBox. */ com.google.cloud.vision.v1.BoundingPoly getBoundingBox(); /** * * * <pre> * The bounding box for the paragraph. * The vertices are in the order of top-left, top-right, bottom-right, * bottom-left. When a rotation of the bounding box is detected the rotation * is represented as around the top-left corner as defined when the text is * read in the 'natural' orientation. * For example: * * when the text is horizontal it might look like: * 0----1 * | | * 3----2 * * when it's rotated 180 degrees around the top-left corner it becomes: * 2----3 * | | * 1----0 * and the vertex order will still be (0, 1, 2, 3). * </pre> * * <code>.google.cloud.vision.v1.BoundingPoly bounding_box = 2;</code> */ com.google.cloud.vision.v1.BoundingPolyOrBuilder getBoundingBoxOrBuilder(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ java.util.List<com.google.cloud.vision.v1.Word> getWordsList(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ com.google.cloud.vision.v1.Word getWords(int index); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ int getWordsCount(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ java.util.List<? extends com.google.cloud.vision.v1.WordOrBuilder> getWordsOrBuilderList(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ com.google.cloud.vision.v1.WordOrBuilder getWordsOrBuilder(int index); /** * * * <pre> * Confidence of the OCR results for the paragraph. Range [0, 1]. * </pre> * * <code>float confidence = 4;</code> * * @return The confidence. */ float getConfidence(); }
apache-2.0
OpenVnmrJ/OpenVnmrJ
src/cryo/src/ClientGui.java
11697
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /* * * */ /* * * Varian, Inc. and its contributors. Use, disclosure and * reproduction is prohibited without prior consent. */ import java.awt.event.*; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.io.*; import java.text.*; import cryoaccess.*; import org.omg.CORBA.*; /** * A class to interface to PC clients over CORBA. */ public class ClientGui { public static void main(String[] args) { ORB orb = null; orb = ORB.init(args, null); if (orb != null) { try { new ClientGui(orb); } catch (Exception e) { System.err.println(e); System.exit(-1); } } else { System.err.println("can't initiate orb"); System.exit(-1); } } /*end of main*/ private ORB orb; private org.omg.CORBA.Object obj; private CryoBay cryoBay; public ClientGui(ORB o) throws Exception { ShutdownFrame sf; BufferedReader reader; boolean modulePresent; File file; CryoThread update; orb = o; obj = null; cryoBay = null; //System.out.println("running test client."); // instantiate ModuleAccessor file = new File("/vnmr/acqqueue/cryoBay.CORBAref"); if ( file.exists() ) { reader = new BufferedReader( new FileReader(file) ); obj = orb.string_to_object( reader.readLine() ); } if (obj == null) { throw new Exception("string_to_object is null: cryoBay.CORBAref"); } //System.out.println("Got object."); cryoBay = CryoBayHelper.narrow(obj); if (cryoBay == null) { throw new Exception("cryoBay is null"); } if ( cryoBay._non_existent() ) { throw new Exception("cryoBay is not running"); } sf = new ShutdownFrame(cryoBay); update = new CryoThread(cryoBay, sf, this); sf.show(); update.start(); } /*end of constructor*/ public ORB getOrb(){ return orb; } } /*end of TestClientGui Class*/ class ShutdownFrame extends JFrame implements WindowListener, ActionListener { JButton cmdClose; JLabel lblBStatus; JLabel lblBHeater; JLabel lblBTemp; JLabel lblBCli; JTextField lblStatus; JTextField lblHeater; JTextField lblTemp; JTextField lblCli; public CryoBay cryoB; ShutdownFrame(CryoBay cb) { super("CryoBay Monitor"); cryoB= cb; cmdClose = new JButton("Close"){ public JToolTip createToolTip(){ return new JToolTip(); } }; cmdClose.setToolTipText("Close program"); cmdClose.addActionListener(this); addWindowListener(this); GridBagConstraints gbc = new GridBagConstraints(); Border loweredbevel = BorderFactory.createLoweredBevelBorder(); lblBStatus= new JLabel("Status: "); lblBHeater= new JLabel("Heater: "); lblBTemp= new JLabel(" Temp: "); lblBCli= new JLabel(" CLI: "); lblStatus = new JTextField(17); lblStatus.setEditable(false); lblStatus.setOpaque(true); lblStatus.setBorder(loweredbevel); lblHeater = new JTextField(17); lblHeater.setEditable(false); lblHeater.setOpaque(true); lblHeater.setBorder(loweredbevel); lblTemp = new JTextField(17); lblTemp.setEditable(false); lblTemp.setOpaque(true); lblTemp.setBorder(loweredbevel); lblCli = new JTextField(17); lblCli.setEditable(false); lblCli.setOpaque(true); lblCli.setBorder(loweredbevel); JPanel lblPanel = new JPanel(); lblPanel.setLayout(new GridBagLayout()); gbc.insets = new Insets(2, 5, 2, 5); setGbc(gbc, 0, 0, 1, 1); lblPanel.add(lblBStatus, gbc); setGbc(gbc, 0, 1, 1, 1); lblPanel.add(lblBHeater, gbc); setGbc(gbc, 0, 2, 1, 1); lblPanel.add(lblBTemp, gbc); setGbc(gbc, 0, 3, 1, 1); lblPanel.add(lblBCli, gbc); JPanel valPanel = new JPanel(); valPanel.setLayout(new GridBagLayout()); gbc.insets = new Insets(2, 5, 2, 5); setGbc(gbc, 0, 0, 1, 1); valPanel.add(lblStatus, gbc); setGbc(gbc, 0, 1, 1, 1); valPanel.add(lblHeater, gbc); setGbc(gbc, 0, 2, 1, 1); valPanel.add(lblTemp, gbc); setGbc(gbc, 0, 3, 1, 1); valPanel.add(lblCli, gbc); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridBagLayout()); gbc.anchor= GridBagConstraints.CENTER; setGbc(gbc, 0, 5, 1, 1); buttonPanel.add(cmdClose, gbc); // finally, add the panels to the content pane getContentPane().setLayout(new GridBagLayout()); gbc.insets = new Insets(10, 10, 10 , 10); gbc.anchor = GridBagConstraints.CENTER; setGbc(gbc, 0, 0, 1, 4); getContentPane().add(lblPanel, gbc); setGbc(gbc, 1, 0, 1, 4); getContentPane().add(valPanel, gbc); setGbc(gbc, 0, 5, 0, 0); getContentPane().add(buttonPanel, gbc); setSize(300, 220); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screenSize.width/2 - 300, screenSize.height/2 - 220); setResizable(true); } private void setGbc(GridBagConstraints gbc, int x, int y, int w, int h) { gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; } public void actionPerformed(ActionEvent ae) { String cmd = ae.getActionCommand(); if (cmd.equals("Close") ){ cmdDisconnect(); } } public void windowClosing(WindowEvent e) { cmdDisconnect(); } // following not used but need to be "implemented" public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} private void cmdDisconnect(){ //close main window this.dispose(); System.exit(0); } public CryoBay reconnectServer(ORB o, ReconnectThread rct){ BufferedReader reader; File file; ORB orb; org.omg.CORBA.Object obj; orb = o; obj = null; cryoB = null; try{ // instantiate ModuleAccessor file = new File("/vnmr/acqqueue/cryoBay.CORBAref"); if ( file.exists() ) { reader = new BufferedReader( new FileReader(file) ); obj = orb.string_to_object( reader.readLine() ); } if(obj!=null){ cryoB = CryoBayHelper.narrow(obj); } if (cryoB != null) { if ( !(cryoB._non_existent()) ) { //System.out.println("reconnected!!!!"); rct.reconnected=true; } } }catch(Exception e){ //System.out.println("Got error: " + e); } return cryoB; } private void warning(String msg) { final JDialog warn; JButton ok; JLabel message; warn = new JDialog(); warn.setTitle(msg); message = new JLabel("CryoBay: " + msg); ok = new JButton("Ok"); ok.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { warn.dispose(); } } ); warn.getContentPane().setLayout( new BorderLayout() ); warn.getContentPane().add(message, "North"); warn.getContentPane().add(ok, "South"); warn.setSize(200, 80); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); warn.setLocation(screenSize.width/2 - 100, screenSize.height/2 - 40); warn.setResizable(false); warn.show(); } } /* end of shutdown frame class */ class CryoThread extends Thread{ CryoBay cryo; ShutdownFrame frame; ClientGui clientGui; ORB orb; ReconnectThread reconnectThread; String[] statusString= {"SYSTEM OFF", "COOLING", "READY", "WARMING", "FAULT", "FAULT- He Pressure", "FAULT- T drift", "RESTARTING", "STOPPING", "EXITING", "Maintenance Needed", "FAULT- Vacuum", "FAULT- Low cooling power", "FAULT- Compressor"}; int status; double heater; double cli; double temp; boolean stop= false; public CryoThread(CryoBay cb, ShutdownFrame sf, ClientGui cg){ cryo= cb; frame = sf; clientGui=cg; } public void updateStates(){ NumberFormat nf= NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2); try{ //System.out.println("getting variables."); status= cryo.cryoGetStatusCORBA(); frame.lblStatus.setText(statusString[status] + " "); heater= cryo.cryoGetHeaterCORBA(); frame.lblHeater.setText(nf.format(heater) + " watts"); temp= cryo.cryoGetTempCORBA(); frame.lblTemp.setText(nf.format(temp) + " deg"); cli= cryo.cryoGetCliCORBA(); if(Double.isNaN(cli)){ frame.lblCli.setText(cli + " "); } else frame.lblCli.setText(nf.format(cli) + " "); } catch (org.omg.CORBA.COMM_FAILURE cf){ // stop thread and try to reconnect to the server frame.lblStatus.setText("FAILURE!! Server connected?"); stop=true; return; } } public void run(){ //System.out.println("running cryothread"); while(!stop){ updateStates(); try{ sleep(1000); } catch(Exception e){ System.out.println("cannot sleep!"); } } //System.out.println("reconnect thread starting..."); reconnectThread= new ReconnectThread(cryo, frame, clientGui); reconnectThread.start(); } } class ReconnectThread extends Thread{ CryoBay cryo; ShutdownFrame frame; ClientGui clientGui; CryoThread cryoThread; ORB orb; boolean reconnected= false; public ReconnectThread(CryoBay cb, ShutdownFrame sf, ClientGui cg){ cryo= cb; frame = sf; clientGui=cg; orb= clientGui.getOrb(); } public void run(){ while(!reconnected){ cryo= frame.reconnectServer(orb, this); try{ sleep(1000); } catch(Exception e){ System.out.println("cannot sleep!"); } } //System.out.println("starting cryothread"); cryoThread= new CryoThread(cryo, frame, clientGui); cryoThread.start(); } }
apache-2.0
RuthRainbow/anemone
src/main/java/group7/anemone/UI/UITheme.java
550
package group7.anemone.UI; import java.util.LinkedHashMap; import java.util.Set; public class UITheme { public enum Types { SHARK, FISH, FOOD, WALL, BACKGROUND, SIDEPANEL1, NEURON, NEURON_FIRED } private LinkedHashMap<Types, Integer> elements = new LinkedHashMap<Types, Integer>(); public void setColor(Types key, int col){ elements.put(key, col); } public int getColor(Types types){ return elements.get(types); } public Types[] getKeys(){ Set<Types> keys = elements.keySet(); return keys.toArray(new Types[keys.size()]); } }
apache-2.0
vuzixtokyo/sample-prompter
app/src/androidTest/java/jp/co/c_lis/prompter/android/ApplicationTest.java
359
package jp.co.c_lis.prompter.android; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
apache-2.0
canlasd/Map-Plotting
demo/src/com/google/maps/android/utils/demo/ClusteringDemoActivity.java
5098
/* * Copyright 2013 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.maps.android.utils.demo; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.model.LatLng; import com.google.maps.android.clustering.ClusterManager; import com.google.maps.android.utils.demo.model.BaseDemoActivity; import com.google.maps.android.utils.demo.model.MyItem; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; public class ClusteringDemoActivity extends BaseDemoActivity { private ClusterManager<MyItem> mClusterManager; private final static String mLogTag = "GeoJsonDemo"; private final String mGeoJsonUrl = "https://data.sfgov.org/resource/ritf-b9ki.json"; // initialize time variable double entry_time=0; double thirty = 0; @Override protected void startDemo() { getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.773972, -122.431297), 10)); mClusterManager = new ClusterManager<MyItem>(this, getMap()); getMap().setOnCameraChangeListener(mClusterManager); DownloadGeoJsonFile downloadGeoJsonFile = new DownloadGeoJsonFile(); // Download the GeoJSON file downloadGeoJsonFile.execute(mGeoJsonUrl); Toast.makeText(this, "Zoom in to find data", Toast.LENGTH_LONG).show(); } private class DownloadGeoJsonFile extends AsyncTask<String, Void, JSONObject> { @Override protected JSONObject doInBackground(String... params) { try { URL url = new URL(mGeoJsonUrl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("X-App-Token", "nOOgZHt8V7HN8W0HMJEV4fWgx"); // Open a stream from the URL InputStream stream = new URL(params[0]).openStream(); String line; StringBuilder result = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); while ((line = reader.readLine()) != null) { // Read and save each line of the stream result.append(line); } // Close the stream reader.close(); stream.close(); JSONArray array; array = new JSONArray(result.toString()); // get number of milliseconds in 30 days ago thirty = TimeUnit.MILLISECONDS.convert(-30, TimeUnit.DAYS); for (int i = 0; i < array.length(); i++) { JSONObject obj = (JSONObject) array.get(i); String latitude = obj.optString("y").toString(); String longitude = obj.optString("x").toString(); String date = obj.optString("date").substring(0,10); double lat = Double.parseDouble(latitude); double longi = Double.parseDouble(longitude); DateFormat formatter ; Date date_format; formatter = new SimpleDateFormat("yyyy-mm-dd"); try { date_format = formatter.parse(date); entry_time= date_format.getTime(); } catch (ParseException e){ e.printStackTrace(); } MyItem offsetItem = new MyItem(lat,longi); if (entry_time > thirty) { mClusterManager.addItem(offsetItem); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); Log.e(mLogTag, "GeoJSON file could not be read"); } return null; } @Override protected void onPostExecute(JSONObject jsonObject) { } } }
apache-2.0
siosio/intellij-community
platform/lang-api/src/com/intellij/codeInspection/ui/SingleCheckboxOptionsPanel.java
1190
/* * Copyright 2003-2021 Dave Griffith, Bas Leijdekkers * * 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.intellij.codeInspection.ui; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.openapi.util.NlsContexts; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class SingleCheckboxOptionsPanel extends InspectionOptionsPanel { public SingleCheckboxOptionsPanel(@NotNull @NlsContexts.Checkbox String label, @NotNull InspectionProfileEntry owner, @NonNls String property) { super(owner, label, property); } }
apache-2.0
firejack-open/Firejack-Platform
platform/src/main/java/net/firejack/platform/generate/beans/web/model/Model.java
9491
/* * 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 net.firejack.platform.generate.beans.web.model; import net.firejack.platform.core.utils.StringUtils; import net.firejack.platform.generate.beans.Base; import net.firejack.platform.generate.beans.Import; import net.firejack.platform.generate.beans.annotation.Properties; import net.firejack.platform.generate.beans.web.broker.Broker; import net.firejack.platform.generate.beans.web.js.ViewModel; import net.firejack.platform.generate.beans.web.model.column.Field; import net.firejack.platform.generate.beans.web.model.key.Key; import net.firejack.platform.generate.beans.web.report.Report; import net.firejack.platform.generate.beans.web.store.Method; import net.firejack.platform.generate.beans.web.store.MethodType; import net.firejack.platform.generate.beans.web.store.Store; import java.util.ArrayList; import java.util.List; @Properties(subpackage = "model", suffix = "Model") public class Model<T extends Model> extends Base { private ModelType type; private boolean abstracts; private boolean single; private boolean wsdl; private String table; private String unique; private String prefix; private String url; private String referenceHeading; private String referenceSubHeading; private String referenceDescription; private Key key; private T parent; private T owner; private List<T> children; private List<T> subclass; private List<Field> fields; private Model domain; private ViewModel view; private List<Report> reports; private Store store; private List<Broker> brokers; /***/ public Model() { } public Model(String lookup) { super(lookup); } public Model(Base base) { super(base); } public Model(Model model) { super(model); this.referenceHeading = model.referenceHeading; this.referenceSubHeading = model.referenceSubHeading; this.referenceDescription = model.referenceDescription; } /** * @param name * @param properties */ public Model(String name, Properties properties) { super(name, properties); } /** * @return */ public ModelType getType() { return type; } /** * @param type */ public void setType(ModelType type) { this.type = type; } /** * @param type * @return */ public boolean isType(ModelType type) { return this.type.equals(type); } /** * @return */ public boolean isSingle() { return single; } /** * @param single */ public void setSingle(boolean single) { this.single = single; } public boolean isWsdl() { return wsdl; } public void setWsdl(boolean wsdl) { this.wsdl = wsdl; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } public String getUnique() { return unique; } public void setUnique(String unique) { this.unique = unique; } public boolean isAbstracts() { return abstracts; } public void setAbstracts(boolean abstracts) { this.abstracts = abstracts; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getReferenceHeading() { return referenceHeading; } public void setReferenceHeading(String referenceHeading) { this.referenceHeading = referenceHeading; } public String getReferenceSubHeading() { return referenceSubHeading; } public void setReferenceSubHeading(String referenceSubHeading) { this.referenceSubHeading = referenceSubHeading; } public String getReferenceDescription() { return referenceDescription; } public void setReferenceDescription(String referenceDescription) { this.referenceDescription = referenceDescription; } /** * @return */ public boolean isExtended() { return parent != null; } public boolean isNested() { return owner != null; } public boolean isSubclasses() { return subclass != null && !subclass.isEmpty(); } /** * @return */ public T getParent() { return parent; } /** * @param parent */ public void setParent(T parent) { this.parent = parent; parent.addChild(this); } public T getOwner() { return owner; } public void setOwner(T owner) { this.owner = owner; } public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } /** * @return */ public List<T> getChildren() { return children; } private void addChild(T child) { if (this.children == null) { this.children = new ArrayList<T>(); } this.children.add(child); } /** * @return */ public boolean isEmptyChild() { return this.children == null; } public List<T> getSubclass() { return subclass; } public void setSubclass(List<T> subclass) { this.subclass = subclass; } public void addSubclasses(T model) { if (subclass == null) subclass = new ArrayList<T>(); subclass.add(model); } /** * @return */ public List<Field> getFields() { return fields; } public void setFields(List<Field> fields) { this.fields = fields; } /** * @param field */ public void addField(Field field) { if (this.fields == null) { this.fields = new ArrayList<Field>(); } this.fields.add(field); } public Field findField(String column) { if (fields != null) { for (Field field : fields) { if (field.getColumn().equals(column)) { return field; } } } return null; } /** * @return */ public Model getDomain() { return domain; } /** * @param domain */ public void setDomain(Model domain) { this.domain = domain; } public ViewModel getView() { return view; } public void setView(ViewModel view) { this.view = view; } /** * @return */ public Store getStore() { return store; } /** * @param store */ public void setStore(Store store) { this.store = store; } public List<Report> getReports() { return reports; } public void setReports(List<Report> reports) { this.reports = reports; } public void addReport(Report report) { if (this.reports == null) this.reports = new ArrayList<Report>(); this.reports.add(report); } /** * @return */ public List<Broker> getBrokers() { return brokers; } /** * @param broker */ public void addBroker(Broker broker) { if (this.brokers == null) { this.brokers = new ArrayList<Broker>(); } this.brokers.add(broker); } /** * @param name * @return */ public Method findStoreMethod(String name) { MethodType type = MethodType.find(name); if (type == null) return null; if (store != null) { return store.find(type); } return null; } public String getDomainLookup() { if (StringUtils.isBlank(classPath)) { return projectPath; } else { return projectPath + DOT + classPath; } } public void addImport(Import anImport) { if (Model.class.isAssignableFrom(anImport.getClass()) && ((Model) anImport).isNested()) { return; } if (isNested()) owner.addImport(anImport); else super.addImport(anImport); } }
apache-2.0
skalscheuer/jvaultconnector
src/main/java/de/stklcode/jvault/connector/model/response/embedded/SecretMetadata.java
3327
/* * Copyright 2016-2020 Stefan Kalscheuer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.stklcode.jvault.connector.model.response.embedded; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Map; /** * Embedded metadata for Key-Value v2 secrets. * * @author Stefan Kalscheuer * @since 0.8 */ @JsonIgnoreProperties(ignoreUnknown = true) public final class SecretMetadata { private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSX"); @JsonProperty("created_time") private String createdTimeString; @JsonProperty("current_version") private Integer currentVersion; @JsonProperty("max_versions") private Integer maxVersions; @JsonProperty("oldest_version") private Integer oldestVersion; @JsonProperty("updated_time") private String updatedTime; @JsonProperty("versions") private Map<Integer, VersionMetadata> versions; /** * @return Time of secret creation as raw string representation. */ public String getCreatedTimeString() { return createdTimeString; } /** * @return Time of secret creation. */ public ZonedDateTime getCreatedTime() { if (createdTimeString != null && !createdTimeString.isEmpty()) { try { return ZonedDateTime.parse(createdTimeString, TIME_FORMAT); } catch (DateTimeParseException e) { // Ignore. } } return null; } /** * @return Current version number. */ public Integer getCurrentVersion() { return currentVersion; } /** * @return Maximum number of versions. */ public Integer getMaxVersions() { return maxVersions; } /** * @return Oldest available version number. */ public Integer getOldestVersion() { return oldestVersion; } /** * @return Time of secret update as raw string representation. */ public String getUpdatedTimeString() { return updatedTime; } /** * @return Time of secret update.. */ public ZonedDateTime getUpdatedTime() { if (updatedTime != null && !updatedTime.isEmpty()) { try { return ZonedDateTime.parse(updatedTime, TIME_FORMAT); } catch (DateTimeParseException e) { // Ignore. } } return null; } /** * @return Version of the entry. */ public Map<Integer, VersionMetadata> getVersions() { return versions; } }
apache-2.0
usgin/usgin-geoportal
src/com/esri/gpt/control/webharvest/client/arcims/ArcImsRecordsAdapter.java
2302
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.gpt.control.webharvest.client.arcims; import com.esri.gpt.framework.resource.api.Resource; import com.esri.gpt.framework.resource.api.SourceUri; import com.esri.gpt.framework.resource.common.CommonPublishable; import com.esri.gpt.framework.util.ReadOnlyIterator; import java.io.IOException; import java.util.Collection; import java.util.Iterator; /** * ArcIMS records adapter. */ class ArcImsRecordsAdapter implements Iterable<Resource> { /** service proxy */ private ArcImsProxy proxy; /** collection of record source URI's */ private Collection<SourceUri> records; /** * Creates instance of the adapter. * @param proxy service proxy. * @param records collection of records source URI's */ public ArcImsRecordsAdapter(ArcImsProxy proxy, Collection<SourceUri> records) { if (proxy == null) throw new IllegalArgumentException("No proxy provided."); this.proxy = proxy; this.records = records; } public Iterator<Resource> iterator() { return new ArcImsRecordsIterator(); } /** * ArcIMS records iterator. */ private class ArcImsRecordsIterator extends ReadOnlyIterator<Resource> { /** iterator */ private Iterator<SourceUri> iterator = records.iterator(); public boolean hasNext() { return iterator.hasNext(); } public Resource next() { return new CommonPublishable() { private SourceUri uri = iterator.next(); public SourceUri getSourceUri() { return uri; } public String getContent() throws IOException { return proxy.read(uri.asString()); } }; } } }
apache-2.0
tkurz/media-fragments-uri
src/main/java/com/github/tkurz/media/ontology/exception/NotComparableException.java
175
package com.github.tkurz.media.ontology.exception; /** * ... * <p/> * Author: Thomas Kurz (tkurz@apache.org) */ public class NotComparableException extends Exception { }
apache-2.0
consulo/consulo-java
java-impl/src/main/java/com/siyeh/ipp/trivialif/ExpandBooleanIntention.java
4264
/* * Copyright 2003-2012 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ipp.trivialif; import javax.annotation.Nonnull; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.siyeh.ipp.base.Intention; import com.siyeh.ipp.base.PsiElementPredicate; import com.siyeh.ipp.psiutils.ErrorUtil; import org.jetbrains.annotations.NonNls; public class ExpandBooleanIntention extends Intention { @Override @Nonnull public PsiElementPredicate getElementPredicate() { return new ExpandBooleanPredicate(); } @Override public void processIntention(@Nonnull PsiElement element) throws IncorrectOperationException { final PsiStatement containingStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class); if (containingStatement == null) { return; } if (ExpandBooleanPredicate.isBooleanAssignment(containingStatement)) { final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement)containingStatement; final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)assignmentStatement.getExpression(); final PsiExpression rhs = assignmentExpression.getRExpression(); if (rhs == null) { return; } final PsiExpression lhs = assignmentExpression.getLExpression(); if (ErrorUtil.containsDeepError(lhs) || ErrorUtil.containsDeepError(rhs)) { return; } final String rhsText = rhs.getText(); final String lhsText = lhs.getText(); final PsiJavaToken sign = assignmentExpression.getOperationSign(); final String signText = sign.getText(); final String conditionText; if (signText.length() == 2) { conditionText = lhsText + signText.charAt(0) + rhsText; } else { conditionText = rhsText; } @NonNls final String statement = "if(" + conditionText + ") " + lhsText + " = true; else " + lhsText + " = false;"; replaceStatement(statement, containingStatement); } else if (ExpandBooleanPredicate.isBooleanReturn(containingStatement)) { final PsiReturnStatement returnStatement = (PsiReturnStatement)containingStatement; final PsiExpression returnValue = returnStatement.getReturnValue(); if (returnValue == null) { return; } if (ErrorUtil.containsDeepError(returnValue)) { return; } final String valueText = returnValue.getText(); @NonNls final String statement = "if(" + valueText + ") return true; else return false;"; replaceStatement(statement, containingStatement); } else if (ExpandBooleanPredicate.isBooleanDeclaration(containingStatement)) { final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)containingStatement; final PsiElement declaredElement = declarationStatement.getDeclaredElements()[0]; if (!(declaredElement instanceof PsiLocalVariable)) { return; } final PsiLocalVariable variable = (PsiLocalVariable)declaredElement; final PsiExpression initializer = variable.getInitializer(); if (initializer == null) { return; } final String name = variable.getName(); @NonNls final String newStatementText = "if(" + initializer.getText() + ") " + name +"=true; else " + name + "=false;"; final PsiElementFactory factory = JavaPsiFacade.getElementFactory(containingStatement.getProject()); final PsiStatement newStatement = factory.createStatementFromText(newStatementText, containingStatement); declarationStatement.getParent().addAfter(newStatement, declarationStatement); initializer.delete(); } } }
apache-2.0
jexp/idea2
platform/lang-impl/src/com/intellij/lang/ASTFactory.java
4716
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package com.intellij.lang; import com.intellij.lexer.Lexer; import com.intellij.lexer.LexerUtil; import com.intellij.psi.TokenType; import com.intellij.psi.impl.source.CharTableImpl; import com.intellij.psi.impl.source.CodeFragmentElement; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.tree.*; import com.intellij.util.CharTable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class ASTFactory { public static final DefaultFactory DEFAULT = new DefaultFactory(); private static final CharTable WHITSPACES = new CharTableImpl(); @Nullable public abstract CompositeElement createComposite(IElementType type); @Nullable public LazyParseableElement createLazy(ILazyParseableElementType type, CharSequence text) { if (type instanceof IFileElementType) { return new FileElement(type, text); } return new LazyParseableElement(type, text); } @Nullable public abstract LeafElement createLeaf(IElementType type, CharSequence text); @NotNull public static LazyParseableElement lazy(ILazyParseableElementType type, CharSequence text) { ASTNode node = type.createNode(text); if (node != null) return (LazyParseableElement)node; if (type == TokenType.CODE_FRAGMENT) { return new CodeFragmentElement(null); } LazyParseableElement psi = factory(type).createLazy(type, text); return psi != null ? psi : DEFAULT.createLazy(type, text); } @Deprecated @NotNull public static LeafElement leaf(IElementType type, CharSequence fileText, int start, int end, CharTable table) { return leaf(type, table.intern(fileText, start, end)); } @NotNull public static LeafElement leaf(IElementType type, CharSequence text) { if (type == TokenType.WHITE_SPACE) { return new PsiWhiteSpaceImpl(text); } if (type instanceof ILeafElementType) { return (LeafElement)((ILeafElementType)type).createLeafNode(text); } final LeafElement customLeaf = factory(type).createLeaf(type, text); return customLeaf != null ? customLeaf : DEFAULT.createLeaf(type, text); } private static ASTFactory factory(IElementType type) { return LanguageASTFactory.INSTANCE.forLanguage(type.getLanguage()); } public static LeafElement whitespace(CharSequence text) { PsiWhiteSpaceImpl w = new PsiWhiteSpaceImpl(WHITSPACES.intern(text)); CodeEditUtil.setNodeGenerated(w, true); return w; } public static LeafElement leaf(IElementType type, CharSequence text, CharTable table) { return leaf(type, table.intern(text)); } public static LeafElement leaf(final Lexer lexer, final CharTable charTable) { return leaf(lexer.getTokenType(), LexerUtil.internToken(lexer, charTable)); } @NotNull public static CompositeElement composite(IElementType type) { if (type instanceof ICompositeElementType) { return (CompositeElement)((ICompositeElementType)type).createCompositeNode(); } if (type == TokenType.CODE_FRAGMENT) { return new CodeFragmentElement(null); } final CompositeElement customComposite = factory(type).createComposite(type); return customComposite != null ? customComposite : DEFAULT.createComposite(type); } private static class DefaultFactory extends ASTFactory { @Override @NotNull public CompositeElement createComposite(IElementType type) { if (type instanceof IFileElementType) { return new FileElement(type, null); } return new CompositeElement(type); } @Override @NotNull public LeafElement createLeaf(IElementType type, CharSequence text) { final Language lang = type.getLanguage(); final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(lang); if (parserDefinition != null) { if (parserDefinition.getCommentTokens().contains(type)) { return new PsiCommentImpl(type, text); } } return new LeafPsiElement(type, text); } } }
apache-2.0
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/core/util/mail/ui/MailTemplateAdminController.java
3376
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.core.util.mail.ui; import org.olat.core.CoreSpringFactory; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; import org.olat.core.util.Util; import org.olat.core.util.mail.MailManager; import org.olat.core.util.mail.MailModule; import org.olat.core.util.mail.MailUIFactory; /** * * Description:<br> * Customize the mail template * * <P> * Initial Date: 14 avr. 2011 <br> * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com */ public class MailTemplateAdminController extends FormBasicController { private TextElement templateEl; private final MailManager mailManager; public MailTemplateAdminController(UserRequest ureq, WindowControl wControl) { super(ureq, wControl, null, Util.createPackageTranslator(MailModule.class, ureq.getLocale())); mailManager = CoreSpringFactory.getImpl(MailManager.class); initForm(ureq); } @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { setFormTitle("mail.template.title"); setFormDescription("mail.template.description"); setFormContextHelp(MailUIFactory.class.getPackage().getName(), "mail-admin-template.html", "chelp.mail-admin-template.title"); String def = mailManager.getMailTemplate(); templateEl = uifactory.addTextAreaElement("mail.template", "mail.template", 10000, 25, 50, true, def, formLayout); final FormLayoutContainer buttonGroupLayout = FormLayoutContainer.createButtonLayout("buttonLayout", getTranslator()); buttonGroupLayout.setRootForm(mainForm); formLayout.add(buttonGroupLayout); uifactory.addFormSubmitButton("save", buttonGroupLayout); } @Override protected void doDispose() { // } @Override protected boolean validateFormLogic(UserRequest ureq) { boolean allOk = true; String value = templateEl.getValue(); templateEl.clearError(); if(value.length() <= 0) { templateEl.setErrorKey("", null); allOk = false; } return allOk & super.validateFormLogic(ureq); } @Override protected void formOK(UserRequest ureq) { String value = templateEl.getValue(); mailManager.setMailTemplate(value); getWindowControl().setInfo("saved"); } }
apache-2.0
rishabhnayak/ud839_Miwok-Starter-code
app/src/main/java/com/example/android/miwok/SeatAval/mainapp2/Stations/SeatTwoStnsSaver.java
2984
package com.example.android.miwok.SeatAval.mainapp2.Stations; import android.content.SharedPreferences; import com.google.gson.Gson; import java.util.ArrayList; public class SeatTwoStnsSaver implements Runnable { ArrayList<SeatTwoStnsClass> list =new ArrayList<SeatTwoStnsClass>(); SeatTwoStnsClass item; SharedPreferences sd; public SeatTwoStnsSaver(SharedPreferences sd, SeatTwoStnsClass item) { this.item=item; this.sd=sd; } @Override public void run() { Boolean elementRemoved=false; Gson gson = new Gson(); if(sd.getString("SeatTwoStnsSaver", "").equals("")) { System.out.println("Trains Saver is not there so creating SeatTwoStnsSaver and then adding"); list.add(item); System.out.println("element added :"+item); SharedPreferences.Editor prefsEditor = sd.edit(); String json = gson.toJson(new SeatTwoStnsSaverObject(list)); prefsEditor.putString("SeatTwoStnsSaver", json); prefsEditor.commit(); }else if(!sd.getString("SeatTwoStnsSaver", "").equals("")){ String json1 = sd.getString("SeatTwoStnsSaver", ""); System.out.println("here is json 1" + json1); SeatTwoStnsSaverObject obj = gson.fromJson(json1, SeatTwoStnsSaverObject.class); list=obj.getList(); System.out.println("list iterator on job..."); for(SeatTwoStnsClass item0:list){ if(item0.getFromStnCode().equals(item.getFromStnCode()) && item0.getToStnCode().equals(item.getToStnCode())){ list.remove(item0); elementRemoved=true; System.out.println("element removed :"+item.getFromStnCode()); list.add(item); System.out.println("element added :"+item); break; } } if(!elementRemoved) { if (list.size() > 4) { System.out.println("list greater than 4"); list.remove(0); list.add(item); System.out.println("element added :"+item); } else { System.out.println("list smaller than 4"); list.add(item); System.out.println("element added :"+item); } } SharedPreferences.Editor prefsEditor = sd.edit(); String json = gson.toJson(new SeatTwoStnsSaverObject(list)); prefsEditor.putString("SeatTwoStnsSaver", json); prefsEditor.commit(); System.out.println("creating SeatTwoStnsSaver in sd"); }else{ System.out.println("dont know what to do...."); } } }
apache-2.0
fedevelatec/asic-core
src/main/java/com/fedevela/core/asic/pojos/ChecklistCap.java
8852
package com.fedevela.core.asic.pojos; /** * Created by fvelazquez on 27/03/14. */ import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.codehaus.jackson.annotate.JsonIgnore; import org.hibernate.annotations.*; @Entity @Table(name = "CHECKLIST_CAP", catalog = "", schema = "PROD") @XmlRootElement public class ChecklistCap implements java.io.Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected ChecklistCapPK checklistCapPK; @Basic(optional = false) @Column(name = "SCLTCOD") private Integer scltcod; @Column(name = "FECHA_CAPTURA", insertable = true, updatable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaCaptura; @Column(name = "FECHA_MODIFICACION") @Temporal(TemporalType.TIMESTAMP) private Date fechaModificacion; @Column(name = "USUARIO_CAPTURA", insertable = true, updatable = false) private String usuarioCaptura; @Column(name = "FECHA") @Temporal(TemporalType.TIMESTAMP) private Date fecha; @Column(name = "CATEGORIA") private Integer categoria; @Column(name = "VALOR") private Integer valor; @Column(name = "OBSERVACIONES") private String observaciones; @Column(name = "DOCDEF") private Integer docdef; @Column(name = "CARACTERISTICA") private String caracteristica; @Column(name = "FECHA_UTIL") @Temporal(TemporalType.TIMESTAMP) private Date fechaUtil; @Lob @Column(name = "DATO") private String dato; @JoinColumn(name = "NUNICODOC", referencedColumnName = "NUNICODOC", insertable = false, updatable = false) @ManyToOne(optional = false) private CabeceraDoc cabeceraDoc; @OneToOne @JoinColumnsOrFormulas({ @JoinColumnOrFormula(column=@JoinColumn(name = "NUNICODOCT", referencedColumnName = "ETIQUETA", insertable = false, updatable = false)), @JoinColumnOrFormula(formula=@JoinFormula(value = "'T'", referencedColumnName = "TIPO"))}) @NotFound(action = NotFoundAction.IGNORE) private VwEtiqueta etiqueta; public ChecklistCap() { } public ChecklistCap(ChecklistCapPK checklistCapPK) { this.checklistCapPK = checklistCapPK; } public ChecklistCap(Long nunicodoc, Long nunicodoct, Short doccod) { this.checklistCapPK = new ChecklistCapPK(nunicodoc, nunicodoct, doccod); } /* public ChecklistCap(long nunicodoct) { this.nunicodoct = nunicodoct; } public ChecklistCap(long nunicodoct, long nunicodoc) { this.nunicodoct = nunicodoct; this.nunicodoc = nunicodoc; } * */ @XmlTransient public CabeceraDoc getCabeceraDoc() { return cabeceraDoc; } public void setCabeceraDoc(CabeceraDoc cabeceraDoc) { this.cabeceraDoc = cabeceraDoc; } public String getCaracteristica() { return caracteristica; } public void setCaracteristica(String caracteristica) { this.caracteristica = caracteristica; } public Integer getCategoria() { return categoria; } public void setCategoria(Integer categoria) { this.categoria = categoria; } public Integer getDocdef() { return docdef; } public void setDocdef(Integer docdef) { this.docdef = docdef; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public Date getFechaCaptura() { return fechaCaptura; } public void setFechaCaptura(Date fechaCaptura) { this.fechaCaptura = fechaCaptura; } public Date getFechaModificacion() { return fechaModificacion; } public void setFechaModificacion(Date fechaModificacion) { this.fechaModificacion = fechaModificacion; } public String getObservaciones() { return observaciones; } public void setObservaciones(String observaciones) { this.observaciones = observaciones; } public Integer getScltcod() { return scltcod; } public void setScltcod(Integer scltcod) { this.scltcod = scltcod; } public String getUsuarioCaptura() { return usuarioCaptura; } public void setUsuarioCaptura(String usuarioCaptura) { this.usuarioCaptura = usuarioCaptura; } public Integer getValor() { return valor; } public void setValor(Integer valor) { this.valor = valor; } @XmlTransient public ChecklistCapPK getChecklistCapPK() { return checklistCapPK; } public void setChecklistCapPK(ChecklistCapPK checklistCapPK) { this.checklistCapPK = checklistCapPK; } public Long getNunicodoc() { return checklistCapPK.getNunicodoc(); } public void setNunicodoc(Long nunicodoc) { if (checklistCapPK == null) { checklistCapPK = new ChecklistCapPK(); } checklistCapPK.setNunicodoc(nunicodoc); } public Long getNunicodoct() { return checklistCapPK.getNunicodoct(); } public void setNunicodoct(Long nunicodoct) { if (checklistCapPK == null) { checklistCapPK = new ChecklistCapPK(); } checklistCapPK.setNunicodoct(nunicodoct); } public Short getDoccod() { return checklistCapPK.getDoccod(); } public void setDoccod(Short doccod) { if (checklistCapPK == null) { checklistCapPK = new ChecklistCapPK(); } checklistCapPK.setDoccod(doccod); } public Date getFechaUtil() { return fechaUtil; } public void setFechaUtil(Date fechaUtil) { this.fechaUtil = fechaUtil; } public String getDato() { return dato; } public void setDato(String dato) { this.dato = dato; } @XmlTransient @JsonIgnore public VwEtiqueta getEtiqueta() { return etiqueta; } public void setEtiqueta(VwEtiqueta etiqueta) { this.etiqueta = etiqueta; } /** * Este codigo se queda comentado porque tenemos el error actualmente de * insertar T's duplicadas. * * @param obj * @return */ /*@Override public int hashCode() { int hash = 5; hash = 11 * hash + (this.checklistCapPK != null && this.checklistCapPK.getNunicodoct() != null ? this.checklistCapPK.getNunicodoct().hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ChecklistCap other = (ChecklistCap) obj; Long id = this.checklistCapPK == null ? null : this.checklistCapPK.getNunicodoct(); Long ot = other.checklistCapPK == null ? null : other.checklistCapPK.getNunicodoct(); if (id != ot && (id == null || !id.equals(ot))) { return false; } return true; } @Override public String toString() { return "ChecklistCap{" + "checklistCapPK=" + checklistCapPK + ", scltcod=" + scltcod + ", fechaCaptura=" + fechaCaptura + ", fechaModificacion=" + fechaModificacion + ", usuarioCaptura=" + usuarioCaptura + ", fecha=" + fecha + ", categoria=" + categoria + ", valor=" + valor + ", observaciones=" + observaciones + ", docdef=" + docdef + ", caracteristica=" + caracteristica + ", cabeceraDoc=" + cabeceraDoc + '}'; }*/ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ChecklistCap other = (ChecklistCap) obj; if (this.checklistCapPK != other.checklistCapPK && (this.checklistCapPK == null || !this.checklistCapPK.equals(other.checklistCapPK))) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 73 * hash + (this.checklistCapPK != null ? this.checklistCapPK.hashCode() : 0); return hash; } @Override public String toString() { return "ChecklistCap{" + "checklistCapPK=" + checklistCapPK + ", scltcod=" + scltcod + ", fechaCaptura=" + fechaCaptura + ", fechaModificacion=" + fechaModificacion + ", usuarioCaptura=" + usuarioCaptura + ", fecha=" + fecha + ", categoria=" + categoria + ", valor=" + valor + ", observaciones=" + observaciones + ", docdef=" + docdef + ", caracteristica=" + caracteristica + ", fechaUtil=" + fechaUtil + ", dato=" + dato + ", cabeceraDoc=" + cabeceraDoc + ", etiqueta=" + etiqueta + '}'; } }
apache-2.0
shenrh/UILayout
app/src/main/java/com/shenrh/layout/widget/CustomElement.java
6083
/* * 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.shenrh.layout.widget; import java.text.SimpleDateFormat; import java.util.Date; import android.content.res.Resources; import android.util.AttributeSet; import android.view.View.MeasureSpec; import android.view.ViewGroup.LayoutParams; import com.shenrh.canvas.ImageUIElement; import com.shenrh.canvas.TextUIElement; import com.shenrh.canvas.UIContext; import com.shenrh.canvas.UIElement; import com.shenrh.canvas.UIElementGroup; import com.shenrh.layout.R; public class CustomElement extends UIElementGroup { private ImageUIElement mProfileImage; private TextUIElement mAuthorText; private TextUIElement mMessageText; private ImageUIElement mPostImage; public CustomElement(UIContext host) { this(host, null); } public CustomElement(UIContext host, AttributeSet attrs) { super(host, attrs); final Resources res = getResources(); int padding = res.getDimensionPixelOffset(R.dimen.tweet_padding); setPadding(padding, padding, padding, padding); mAuthorText = new TextUIElement(host); mAuthorText.setTextColor(getResources().getColor(R.color.tweet_author_text_color)); mAuthorText.setTextSize(getResources().getDimensionPixelOffset(R.dimen.tweet_author_text_size)); mMessageText = new TextUIElement(host); mMessageText.setTextColor(getResources().getColor(R.color.tweet_message_text_color)); mMessageText.setTextSize(getResources().getDimensionPixelOffset(R.dimen.tweet_message_text_size)); mProfileImage = new ImageUIElement(host); mProfileImage.setLayoutParams(new LayoutParams(getResources().getDimensionPixelOffset(R.dimen.tweet_profile_image_size), getResources().getDimensionPixelOffset(R.dimen.tweet_profile_image_size))); mPostImage = new ImageUIElement(host); mPostImage.setLayoutParams(new LayoutParams(100, 100)); mPostImage.setBackgroundColor(0x3000ff00); addElement(mAuthorText); addElement(mMessageText);//, new MarginLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT) addElement(mProfileImage); addElement(mPostImage); setOnClickListener(new OnClickListener() { @Override public void onClick(UIElement uiElement) { System.out.println("CustomElement group is click."); chageTime(); } }); mPostImage.setOnClickListener(new OnClickListener() { @Override public void onClick(UIElement uiElement) { System.out.println("CustomElement mPostImage is click."); } }); } @Override public boolean setContext(UIContext host) { return super.setContext(host); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthUsed = 0; int heightUsed = 0; measureElementWithMargins(mProfileImage, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); widthUsed += getMeasuredWidthWithMargins(mProfileImage); measureElementWithMargins(mAuthorText, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); heightUsed += getMeasuredHeightWithMargins(mAuthorText); measureElementWithMargins(mMessageText, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); heightUsed += getMeasuredHeightWithMargins(mMessageText); measureElementWithMargins(mPostImage, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); heightUsed += getMeasuredHeightWithMargins(mPostImage); int heightSize = heightUsed + getPaddingTop() + getPaddingBottom(); setMeasuredDimension(widthSize, heightSize); // System.out.println("onMeasure " + widthSize + "X" + heightSize); } @Override public void onLayout(int l, int t, int r, int b) { final int paddingLeft = getPaddingLeft(); final int paddingTop = getPaddingTop(); int currentTop = paddingTop; layoutElement(mProfileImage, paddingLeft, currentTop, mProfileImage.getMeasuredWidth(), mProfileImage.getMeasuredHeight()); final int contentLeft = getWidthWithMargins(mProfileImage) + paddingLeft; final int contentWidth = r - l - contentLeft - getPaddingRight(); layoutElement(mAuthorText, contentLeft, currentTop, contentWidth, mAuthorText.getMeasuredHeight()); currentTop += getHeightWithMargins(mAuthorText); layoutElement(mMessageText, contentLeft, currentTop, contentWidth, mMessageText.getMeasuredHeight()); currentTop += getHeightWithMargins(mMessageText); layoutElement(mPostImage, paddingLeft, currentTop, mPostImage.getMeasuredWidth(), mPostImage.getMeasuredHeight()); currentTop += getHeightWithMargins(mPostImage); //System.out.println("onLayout " + mProfileImage.getMeasuredWidth() + "X" + mProfileImage.getMeasuredHeight()); } public void setData() { mAuthorText.setText("Hello"); chageTime(); mProfileImage.setImageResource(R.drawable.ic_launcher); mPostImage.setImageResource(R.drawable.tweet_reply); } public void chageTime() { long time = System.currentTimeMillis(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = new Date(time); mMessageText.setText("time:" + format.format(d1)); } }
apache-2.0
CSCSI/Triana
triana-toolboxes/math/src/main/java/math/functions/ATanCont.java
6235
package math.functions; import java.awt.Window; import java.awt.event.ActionEvent; import org.trianacode.gui.windows.ScrollerWindow; import org.trianacode.taskgraph.Unit; import triana.types.EmptyingType; import triana.types.Histogram; import triana.types.SampleSet; import triana.types.Spectrum; import triana.types.VectorType; import triana.types.util.Str; /** * A ATanCont unit to find the angle of a vector (or complex number) from two input sequences that represent the x and y * components of the vector, attempting to resolve ambiguities about the multiple of 2 Pi in the angle by maintaining * continuity. * * @author B.F. Schutz * @version 1.0 alpha 04 Oct 1997 */ public class ATanCont extends Unit { /** * The UnitWindow for ATanCont */ ScrollerWindow myWindow; /** * Initial angle parameter */ double phase = 0.0; /** * A useful constant */ double TwoPi = 2.0 * Math.PI; /** * This returns a <b>brief!</b> description of what the unit does. The text here is shown in a pop up window when * the user puts the mouse over the unit icon for more than a second. */ public String getPopUpDescription() { return "Finds the angle of a vector (or complex number) from two input sequences"; } /** * ********************************************* ** USER CODE of ATanCont goes here *** * ********************************************* */ public void process() { Object input, input2; double[] inputdataX = {0.0}; double[] inputdataY = {0.0}; input = getInputAtNode(0); if (input instanceof EmptyingType) { return; } Class inputClass = input.getClass(); //setOutputType(inputClass); input2 = getInputAtNode(1); if (input instanceof VectorType) { inputdataX = ((VectorType) input).getData(); inputdataY = ((VectorType) input2).getData(); } else if (input instanceof SampleSet) { inputdataX = ((SampleSet) input).data; inputdataY = ((SampleSet) input2).data; } else if (input instanceof Spectrum) { inputdataX = ((Spectrum) input).data; inputdataY = ((Spectrum) input2).data; } else if (input instanceof Histogram) { inputdataX = ((Histogram) input).data; inputdataY = ((Histogram) input2).data; } int sizeOfData = inputdataX.length; double[] outputdata = inputdataX; // IT, for effieciency new double[sizeOfData]; double lastAngle = Math.atan2(inputdataX[0], inputdataY[0]); double thisAngle, diffAngle; double jump = phase; for (int i = 1; i < sizeOfData; i++) { thisAngle = Math.atan2(inputdataX[i], inputdataY[i]); diffAngle = thisAngle - lastAngle; if (diffAngle > Math.PI) { jump = jump - TwoPi; } else if (diffAngle < -Math.PI) { jump = jump + TwoPi; } outputdata[i] = thisAngle + jump; lastAngle = thisAngle; } if (input instanceof VectorType) { VectorType output = new VectorType(outputdata); output(output); } else if (input instanceof SampleSet) { SampleSet output = new SampleSet( ((SampleSet) input).samplingFrequency(), outputdata); output(output); } else if (input instanceof Spectrum) { Spectrum output = new Spectrum( ((Spectrum) input).samplingFrequency(), outputdata); output(output); } else if (input instanceof Histogram) { Histogram output = new Histogram( ((Histogram) input).binLabel, ((Histogram) input).hLabel, ((Histogram) input).delimiters, outputdata); output(output); } } /** * Initialses information specific to ATanCont. */ public void init() { super.init(); // changeInputNodes(2); // setResizableInputs(false); // setResizableOutputs(true); // // This is to ensure that we receive arrays containing double-precision numbers // setRequireDoubleInputs(true); // setCanProcessDoubleArrays(true); setDefaultInputNodes(1); setMinimumInputNodes(1); setMaximumInputNodes(Integer.MAX_VALUE); setDefaultOutputNodes(1); setMinimumOutputNodes(1); setMaximumOutputNodes(Integer.MAX_VALUE); myWindow = new ScrollerWindow(this, "Initial angle in radians added to output"); myWindow.setValues(0.0, 2.0 * Math.PI, phase); } /** * Reset's ATanCont */ public void reset() { super.reset(); } /** * Saves ATanCont's parameters to the parameter file. */ // public void saveParameters() { // saveParameter("phase", phase); // } /** * Loads ATanCont's parameters of from the parameter file. */ public void setParameter(String name, String value) { phase = Str.strToDouble(value); } public String[] getInputTypes() { return new String[]{"triana.types.VectorType", "triana.types.SampleSet", "triana.types.Spectrum", "triana.types.Histogram"}; } public String[] getOutputTypes() { return new String[]{"triana.types.VectorType", "triana.types.SampleSet", "triana.types.Spectrum", "triana.types.Histogram"}; } /** * * @returns the location of the help file for this unit. */ public String getHelpFile() { return "ATanCont.html"; } /** * @return ATanCont's parameter window sp that Triana can move and display it. */ public Window getParameterWindow() { return myWindow; } /** * Captures the events thrown out by ATanCont. */ // public void actionPerformed(ActionEvent e) { // super.actionPerformed(e); // we need this // // //if (e.getSource() == myWindow.slider) { // // phase = myWindow.getValue(); // // } // } }
apache-2.0
gdutxiaoxu/FunAPP
Fun/src/main/java/com/xujun/funapp/widget/divider/DividerGridItemDecoration.java
6294
package com.xujun.funapp.widget.divider; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.LayoutManager; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; /** * @ explain:针对GridLayoutManger的分割线 * @ author:xujun on 2016-7-13 14:30 * @ email:gdutxiaoxu@163.com */ public class DividerGridItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[]{android.R.attr.listDivider}; private Drawable mDivider; public DividerGridItemDecoration(Context context) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { drawHorizontal(c, parent); drawVertical(c, parent); } private int getSpanCount(RecyclerView parent) { // 列数 int spanCount = -1; LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { spanCount = ((GridLayoutManager) layoutManager).getSpanCount(); } else if (layoutManager instanceof StaggeredGridLayoutManager) { spanCount = ((StaggeredGridLayoutManager) layoutManager) .getSpanCount(); } return spanCount; } public void drawHorizontal(Canvas c, RecyclerView parent) { int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getLeft() - params.leftMargin; final int right = child.getRight() + params.rightMargin + mDivider.getIntrinsicWidth(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawVertical(Canvas c, RecyclerView parent) { final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getTop() - params.topMargin; final int bottom = child.getBottom() + params.bottomMargin; final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicWidth(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } private boolean isLastColum(RecyclerView parent, int pos, int spanCount, int childCount) { LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { if ((pos + 1) % spanCount == 0) // 如果是最后一列,则不需要绘制右边 { return true; } } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); if (orientation == StaggeredGridLayoutManager.VERTICAL) { if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边 { return true; } } else { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一列,则不需要绘制右边 return true; } } return false; } private boolean isLastRaw(RecyclerView parent, int pos, int spanCount, int childCount) { LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一行,则不需要绘制底部 return true; } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); // StaggeredGridLayoutManager 且纵向滚动 if (orientation == StaggeredGridLayoutManager.VERTICAL) { childCount = childCount - childCount % spanCount; // 如果是最后一行,则不需要绘制底部 if (pos >= childCount) return true; // StaggeredGridLayoutManager 且横向滚动 } else { // 如果是最后一行,则不需要绘制底部 if ((pos + 1) % spanCount == 0) { return true; } } } return false; } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { int spanCount = getSpanCount(parent); int childCount = parent.getAdapter().getItemCount(); // 如果是最后一行,则不需要绘制底部 if (isLastRaw(parent, itemPosition, spanCount, childCount)) { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); // 如果是最后一列,则不需要绘制右边 } else if (isLastColum(parent, itemPosition, spanCount, childCount)) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight()); } } }
apache-2.0
evgenymatveev/Task
chapter_005/src/main/java/ru/ematveev/generic/User.java
262
package ru.ematveev.generic; /** * @author Matveev Evgeny. */ public class User extends Base { /** * Constructor the class. * * @param id unic id for every the Base element. */ public User(String id) { super(id); } }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_0283.java
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_0283 { }
apache-2.0
corbel-platform/corbel
rem-acl/src/test/java/io/corbel/resources/rem/acl/AclGetRemTest.java
10337
package io.corbel.resources.rem.acl; import static io.corbel.resources.rem.acl.AclTestUtils.getEntityWithoutAcl; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import java.util.Collections; import java.util.List; import java.util.Optional; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import com.google.gson.JsonObject; import io.corbel.lib.token.TokenInfo; import io.corbel.resources.rem.acl.exception.AclFieldNotPresentException; import io.corbel.resources.rem.model.AclPermission; import io.corbel.resources.rem.request.*; import io.corbel.resources.rem.service.AclResourcesService; import io.corbel.resources.rem.service.RemService; /** * @author Cristian del Cerro */ @RunWith(MockitoJUnitRunner.class) public class AclGetRemTest { private static final String USER_ID = "userId"; private static final String GROUP_ID = "groupId"; private static final String TYPE = "type"; private static final ResourceId RESOURCE_ID = new ResourceId("resourceId"); private static final String REQUESTED_DOMAIN_ID = "requestedDomainId"; private AclGetRem rem; @Mock private AclResourcesService aclResourcesService; @Mock private List<MediaType> acceptedMediaTypes; @Mock private RemService remService; @Mock private RequestParameters<ResourceParameters> resourceParameters; @Mock private RequestParameters<CollectionParameters> collectionParameters; @Mock private RequestParameters<RelationParameters> relationParameters; @Mock private TokenInfo tokenInfo; @Mock private Response getResponse; @Before public void setUp() throws Exception { when(getResponse.getStatus()).thenReturn(200); when(aclResourcesService.getResource(any(), eq(TYPE), eq(RESOURCE_ID), any(), any())).thenReturn(getResponse); rem = new AclGetRem(aclResourcesService); rem.setRemService(remService); when(tokenInfo.getUserId()).thenReturn(USER_ID); when(tokenInfo.getGroups()).thenReturn(Collections.singletonList(GROUP_ID)); when(resourceParameters.getTokenInfo()).thenReturn(tokenInfo); when(collectionParameters.getTokenInfo()).thenReturn(tokenInfo); when(relationParameters.getTokenInfo()).thenReturn(tokenInfo); when(collectionParameters.getRequestedDomain()).thenReturn(REQUESTED_DOMAIN_ID); when(resourceParameters.getRequestedDomain()).thenReturn(REQUESTED_DOMAIN_ID); when(relationParameters.getRequestedDomain()).thenReturn(REQUESTED_DOMAIN_ID); } @Test public void testGetResourceNoUserId() throws AclFieldNotPresentException { when(tokenInfo.getUserId()).thenReturn(null); when(resourceParameters.getTokenInfo()).thenReturn(tokenInfo); JsonObject entity = getEntityWithoutAcl(); JsonObject acl = new JsonObject(); acl.addProperty("ALL", "READ"); entity.add("_acl", acl); when(aclResourcesService.getResourceIfIsAuthorized(eq(REQUESTED_DOMAIN_ID), eq(tokenInfo), eq(TYPE), eq(RESOURCE_ID), eq(AclPermission.READ))) .thenReturn(Optional.of(entity)); Response response = rem.resource(TYPE, RESOURCE_ID, resourceParameters, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(200); } @Test(expected = WebApplicationException.class) public void testGetResourceNotFoundObject() throws AclFieldNotPresentException { when(getResponse.getStatus()).thenReturn(404); when(getResponse.getStatusInfo()).thenReturn(Response.Status.NOT_FOUND); doThrow(new WebApplicationException(getResponse)).when(aclResourcesService).getResourceIfIsAuthorized(eq(REQUESTED_DOMAIN_ID), eq(tokenInfo), eq(TYPE), eq(RESOURCE_ID), eq(AclPermission.READ)); try { rem.resource(TYPE, RESOURCE_ID, resourceParameters, null, Optional.empty()); } catch (WebApplicationException wae) { assertThat(wae.getResponse().getStatus()).isEqualTo(404); throw wae; } } @Test public void testGetResourceGetEntity() throws AclFieldNotPresentException { JsonObject entity = getEntityWithoutAcl(); JsonObject acl = new JsonObject(); acl.addProperty(USER_ID, "ADMIN"); entity.add("_acl", acl); when(aclResourcesService.getResourceIfIsAuthorized(eq(REQUESTED_DOMAIN_ID), eq(tokenInfo), eq(TYPE), eq(RESOURCE_ID), eq(AclPermission.READ))) .thenReturn(Optional.of(entity)); when(getResponse.getEntity()).thenReturn(entity); Response response = rem.resource(TYPE, RESOURCE_ID, resourceParameters, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getEntity()).isEqualTo(entity); } @Test public void testGetCollectionNoUserId() { JsonObject entity = getEntityWithoutAcl(); JsonObject acl = new JsonObject(); acl.addProperty("ALL", "READ"); entity.add("_acl", acl); CollectionParameters apiParameters = mock(CollectionParameters.class); when(collectionParameters.getAcceptedMediaTypes()).thenReturn(Collections.singletonList(MediaType.APPLICATION_JSON)); when(collectionParameters.getOptionalApiParameters()).thenReturn(Optional.of(apiParameters)); when(apiParameters.getQueries()).thenReturn(Optional.empty()); when(tokenInfo.getUserId()).thenReturn(null); when(collectionParameters.getTokenInfo()).thenReturn(tokenInfo); when(collectionParameters.getAcceptedMediaTypes()).thenReturn(Collections.singletonList(MediaType.APPLICATION_JSON)); when(aclResourcesService.getCollection(any(), eq(TYPE), eq(collectionParameters), any())).thenReturn(getResponse); when(getResponse.getEntity()).thenReturn(entity); Response response = rem.collection(TYPE, collectionParameters, null, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(200); } @Test public void testGetCollectionNoJsonMediaType() { Response response = rem.collection(TYPE, collectionParameters, null, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(405); } @Test public void testGetCollection() { JsonObject entity = getEntityWithoutAcl(); JsonObject acl = new JsonObject(); acl.addProperty(USER_ID, "ADMIN"); entity.add("_acl", acl); CollectionParameters apiParameters = mock(CollectionParameters.class); when(collectionParameters.getAcceptedMediaTypes()).thenReturn(Collections.singletonList(MediaType.APPLICATION_JSON)); when(collectionParameters.getOptionalApiParameters()).thenReturn(Optional.of(apiParameters)); when(apiParameters.getQueries()).thenReturn(Optional.empty()); when(aclResourcesService.getCollection(any(), eq(TYPE), eq(collectionParameters), any())).thenReturn(getResponse); when(getResponse.getEntity()).thenReturn(entity); Response response = rem.collection(TYPE, collectionParameters, null, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getEntity()).isEqualTo(entity); } @Test public void testGetCollectionWithPermissionForAllUsers() { JsonObject entity = getEntityWithoutAcl(); JsonObject acl = new JsonObject(); acl.addProperty("ALL", "READ"); entity.add("_acl", acl); CollectionParameters apiParameters = mock(CollectionParameters.class); when(collectionParameters.getAcceptedMediaTypes()).thenReturn(Collections.singletonList(MediaType.APPLICATION_JSON)); when(collectionParameters.getOptionalApiParameters()).thenReturn(Optional.of(apiParameters)); when(apiParameters.getQueries()).thenReturn(Optional.empty()); when(aclResourcesService.getCollection(any(), eq(TYPE), eq(collectionParameters), any())).thenReturn(getResponse); when(getResponse.getEntity()).thenReturn(entity); Response response = rem.collection(TYPE, collectionParameters, null, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getEntity()).isEqualTo(entity); } @Test public void testGetRelationWithWildcardInOrigin() { ResourceId resourceId = new ResourceId("_"); RelationParameters apiParameters = mock(RelationParameters.class); when(relationParameters.getOptionalApiParameters()).thenReturn(Optional.of(apiParameters)); when(apiParameters.getPredicateResource()).thenReturn(Optional.of("idDst")); Response response = rem.relation(TYPE, resourceId, TYPE, relationParameters, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(405); } @Test public void testGetRelation() throws AclFieldNotPresentException { JsonObject entity = getEntityWithoutAcl(); JsonObject acl = new JsonObject(); acl.addProperty(USER_ID, "ADMIN"); entity.add("_acl", acl); ResourceId resourceId = new ResourceId("idOrigin"); when(aclResourcesService.isAuthorized(eq(REQUESTED_DOMAIN_ID), eq(tokenInfo), eq(TYPE), eq(resourceId), eq(AclPermission.READ))).thenReturn(true); RelationParameters apiParameters = mock(RelationParameters.class); when(relationParameters.getOptionalApiParameters()).thenReturn(Optional.of(apiParameters)); when(apiParameters.getPredicateResource()).thenReturn(Optional.of("idDist")); when(aclResourcesService.getRelation(any(), eq(TYPE), eq(resourceId), eq(TYPE), eq(relationParameters), any())).thenReturn(getResponse); when(getResponse.getEntity()).thenReturn(entity); Response response = rem.relation(TYPE, resourceId, TYPE, relationParameters, Optional.empty(), Optional.empty()); assertThat(response.getStatus()).isEqualTo(200); } }
apache-2.0
cuba-platform/cuba
modules/core/test/com/haulmont/cuba/soft_delete/SoftDeleteMany2ManyTest.java
6809
/* * 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.soft_delete; import com.haulmont.cuba.core.EntityManager; import com.haulmont.cuba.core.Transaction; import com.haulmont.cuba.core.global.AppBeans; import com.haulmont.cuba.core.global.CommitContext; import com.haulmont.cuba.core.global.DataManager; import com.haulmont.cuba.core.global.DeletePolicyException; import com.haulmont.cuba.testmodel.many2many.Many2ManyA; import com.haulmont.cuba.testmodel.many2many.Many2ManyB; import com.haulmont.cuba.testsupport.TestContainer; import org.apache.commons.lang3.exception.ExceptionUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.Test; import java.util.HashSet; import static org.junit.jupiter.api.Assertions.*; public class SoftDeleteMany2ManyTest { @RegisterExtension public static TestContainer cont = TestContainer.Common.INSTANCE; private Many2ManyA many2ManyA, many2ManyA2, a1, a2; private Many2ManyB many2ManyB, many2ManyB2, b1, b2, b3; @BeforeEach public void setUp() throws Exception { DataManager dataManager = AppBeans.get(DataManager.class); many2ManyA = cont.metadata().create(Many2ManyA.class); many2ManyB = cont.metadata().create(Many2ManyB.class); many2ManyA.setCollectionOfB(new HashSet<>()); many2ManyA.getCollectionOfB().add(many2ManyB); dataManager.commit(new CommitContext(many2ManyA, many2ManyB)); many2ManyA2 = cont.metadata().create(Many2ManyA.class); many2ManyB2 = cont.metadata().create(Many2ManyB.class); many2ManyA2.setCollectionOfB2(new HashSet<>()); many2ManyA2.getCollectionOfB2().add(many2ManyB2); dataManager.commit(new CommitContext(many2ManyA2, many2ManyB2)); a1 = cont.metadata().create(Many2ManyA.class); a2 = cont.metadata().create(Many2ManyA.class); b1 = cont.metadata().create(Many2ManyB.class); b2 = cont.metadata().create(Many2ManyB.class); b3 = cont.metadata().create(Many2ManyB.class); a1.setCollectionOfB(new HashSet<>()); a1.getCollectionOfB().add(b1); a1.getCollectionOfB().add(b2); a2.setCollectionOfB(new HashSet<>()); a2.getCollectionOfB().add(b3); dataManager.commit(new CommitContext(a1, a2, b1, b2, b3)); } @AfterEach public void tearDown() throws Exception { cont.deleteRecord("TEST_MANY2MANY_AB_LINK", "A_ID", many2ManyA.getId(), a1.getId(), a2.getId()); cont.deleteRecord("TEST_MANY2MANY_AB_LINK2", "A_ID", many2ManyA2.getId()); cont.deleteRecord(many2ManyA, many2ManyB, many2ManyA2, many2ManyB2, a1, a2, b1, b2, b3); } @Test public void testMany2ManyUnlink() throws Exception { try (Transaction tx = cont.persistence().createTransaction()) { Many2ManyA a = cont.entityManager().find(Many2ManyA.class, this.many2ManyA.getId()); assertNotNull(a); assertFalse(a.getCollectionOfB().isEmpty()); assertEquals(many2ManyB, a.getCollectionOfB().iterator().next()); tx.commit(); } try (Transaction tx = cont.persistence().createTransaction()) { Many2ManyB b = cont.entityManager().find(Many2ManyB.class, this.many2ManyB.getId()); cont.entityManager().remove(b); tx.commit(); } try (Transaction tx = cont.persistence().createTransaction()) { Many2ManyA a = cont.entityManager().find(Many2ManyA.class, this.many2ManyA.getId()); assertNotNull(a); assertTrue(a.getCollectionOfB().isEmpty()); tx.commit(); } } @Test public void testMany2ManyDeny() throws Exception { try (Transaction tx = cont.persistence().createTransaction()) { Many2ManyA a = cont.entityManager().find(Many2ManyA.class, many2ManyA2.getId()); assertNotNull(a); assertFalse(a.getCollectionOfB2().isEmpty()); assertEquals(many2ManyB2, a.getCollectionOfB2().iterator().next()); tx.commit(); } try (Transaction tx = cont.persistence().createTransaction()) { Many2ManyA a = cont.entityManager().find(Many2ManyA.class, many2ManyA2.getId()); cont.entityManager().remove(a); tx.commit(); fail(); } catch (Exception e) { Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause == null) rootCause = e; if (!(rootCause instanceof DeletePolicyException)) rootCause.printStackTrace(); assertTrue(rootCause instanceof DeletePolicyException); } try (Transaction tx = cont.persistence().createTransaction()) { Many2ManyA a = cont.entityManager().find(Many2ManyA.class, many2ManyA2.getId()); assertNotNull(a); assertFalse(a.getCollectionOfB2().isEmpty()); assertEquals(many2ManyB2, a.getCollectionOfB2().iterator().next()); tx.commit(); } } /** * @see <a href="https://youtrack.haulmont.com/issue/PL-3452">PL-3452</a> */ @Test public void test_PL_3452() throws Exception { Many2ManyA a1; Many2ManyA a2; Many2ManyB b1; try (Transaction tx = cont.persistence().createTransaction()) { EntityManager em = cont.entityManager(); a1 = em.find(Many2ManyA.class, this.a1.getId()); assertNotNull(a1); assertEquals(2, a1.getCollectionOfB().size()); a2 = em.find(Many2ManyA.class, this.a2.getId()); assertNotNull(a2); assertEquals(1, a2.getCollectionOfB().size()); tx.commitRetaining(); em = cont.entityManager(); b1 = em.find(Many2ManyB.class, this.b1.getId()); em.remove(b1); tx.commitRetaining(); em = cont.entityManager(); a1 = em.find(Many2ManyA.class, this.a1.getId()); assertNotNull(a1); assertEquals(1, a1.getCollectionOfB().size()); tx.commit(); } } }
apache-2.0
XINCGer/DesignPattern
单例模式(Singleton)/多线程/Singleton.java
491
//¶àÏ̵߳¥Àýģʽ class Singleton { private static Singleton instance; //synchronized¼ÓËøÍ¬²½»á½µµÍЧÂÊ,ÕâÀïÏÈÅжÏÊÇ·ñΪ¿Õ //²»Îª¿ÕÔò²»ÐèÒª¼ÓËø,Ìá¸ß³ÌÐòЧÂÊ //²¹È« ¹¹ÔìÆ÷ private Singleton(){} public static Singleton getInstance (){ //²¹È« ´´½¨ÊµÀý if(instance ==null){ synchronized(Singleton.class){ if(instance ==null){ instance = new Singleton(); } } } return instance; } }
apache-2.0
afiantara/apache-wicket-1.5.7
src/wicket-core/src/main/java/org/apache/wicket/markup/parser/XmlPullParser.java
17718
/* * 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.wicket.markup.parser; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import org.apache.wicket.markup.parser.XmlTag.TagType; import org.apache.wicket.markup.parser.XmlTag.TextSegment; import org.apache.wicket.util.io.FullyBufferedReader; import org.apache.wicket.util.io.IOUtils; import org.apache.wicket.util.io.XmlReader; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.parse.metapattern.parsers.TagNameParser; import org.apache.wicket.util.parse.metapattern.parsers.VariableAssignmentParser; import org.apache.wicket.util.resource.ResourceStreamNotFoundException; import org.apache.wicket.util.string.Strings; /** * A fairly shallow markup pull parser which parses a markup string of a given type of markup (for * example, html, xml, vxml or wml) into ComponentTag and RawMarkup tokens. * * @author Jonathan Locke * @author Juergen Donnerstag */ public final class XmlPullParser implements IXmlPullParser { /** */ public static final String STYLE = "style"; /** */ public static final String SCRIPT = "script"; /** * Reads the xml data from an input stream and converts the chars according to its encoding * (<?xml ... encoding="..." ?>) */ private XmlReader xmlReader; /** * A XML independent reader which loads the whole source data into memory and which provides * convenience methods to access the data. */ private FullyBufferedReader input; /** temporary variable which will hold the name of the closing tag. */ private String skipUntilText; /** The last substring selected from the input */ private CharSequence lastText; /** Everything in between &lt;!DOCTYPE ... &gt; */ private CharSequence doctype; /** The type of what is in lastText */ private HttpTagType lastType = HttpTagType.NOT_INITIALIZED; /** The last tag found */ private XmlTag lastTag; /** * Construct. */ public XmlPullParser() { } public final String getEncoding() { return xmlReader.getEncoding(); } public final CharSequence getDoctype() { return doctype; } public final CharSequence getInputFromPositionMarker(final int toPos) { return input.getSubstring(toPos); } public final CharSequence getInput(final int fromPos, final int toPos) { return input.getSubstring(fromPos, toPos); } /** * Whatever will be in between the current index and the closing tag, will be ignored (and thus * treated as raw markup (text). This is useful for tags like 'script'. * * @throws ParseException */ private final void skipUntil() throws ParseException { // this is a tag with non-XHTML text as body - skip this until the // skipUntilText is found. final int startIndex = input.getPosition(); final int tagNameLen = skipUntilText.length(); int pos = input.getPosition() - 1; String endTagText = null; int lastPos = 0; while (!skipUntilText.equalsIgnoreCase(endTagText)) { pos = input.find("</", pos + 1); if ((pos == -1) || ((pos + (tagNameLen + 2)) >= input.size())) { throw new ParseException( skipUntilText + " tag not closed" + getLineAndColumnText(), startIndex); } lastPos = pos + 2; endTagText = input.getSubstring(lastPos, lastPos + tagNameLen).toString(); } input.setPosition(pos); lastText = input.getSubstring(startIndex, pos); lastType = HttpTagType.BODY; // Check that the tag is properly closed lastPos = input.find('>', lastPos + tagNameLen); if (lastPos == -1) { throw new ParseException(skipUntilText + " tag not closed" + getLineAndColumnText(), startIndex); } // Reset the state variable skipUntilText = null; } /** * * @return line and column number */ private String getLineAndColumnText() { return " (line " + input.getLineNumber() + ", column " + input.getColumnNumber() + ")"; } /** * @return XXX * @throws ParseException */ public final HttpTagType next() throws ParseException { // Reached end of markup file? if (input.getPosition() >= input.size()) { return HttpTagType.NOT_INITIALIZED; } if (skipUntilText != null) { skipUntil(); return lastType; } // Any more tags in the markup? final int openBracketIndex = input.find('<'); // Tag or Body? if (input.charAt(input.getPosition()) != '<') { // It's a BODY if (openBracketIndex == -1) { // There is no next matching tag. lastText = input.getSubstring(-1); input.setPosition(input.size()); lastType = HttpTagType.BODY; return lastType; } lastText = input.getSubstring(openBracketIndex); input.setPosition(openBracketIndex); lastType = HttpTagType.BODY; return lastType; } // Determine the line number input.countLinesTo(openBracketIndex); // Get index of closing tag and advance past the tag int closeBracketIndex = -1; if (openBracketIndex != -1 && openBracketIndex < input.size() - 1) { char nextChar = input.charAt(openBracketIndex + 1); if ((nextChar == '!') || (nextChar == '?')) closeBracketIndex = input.find('>', openBracketIndex); else closeBracketIndex = input.findOutOfQuotes('>', openBracketIndex); } if (closeBracketIndex == -1) { throw new ParseException("No matching close bracket at" + getLineAndColumnText(), input.getPosition()); } // Get the complete tag text lastText = input.getSubstring(openBracketIndex, closeBracketIndex + 1); // Get the tagtext between open and close brackets String tagText = lastText.subSequence(1, lastText.length() - 1).toString(); if (tagText.length() == 0) { throw new ParseException("Found empty tag: '<>' at" + getLineAndColumnText(), input.getPosition()); } // Type of the tag, to be determined next final TagType type; // If the tag ends in '/', it's a "simple" tag like <foo/> if (tagText.endsWith("/")) { type = TagType.OPEN_CLOSE; tagText = tagText.substring(0, tagText.length() - 1); } else if (tagText.startsWith("/")) { // The tag text starts with a '/', it's a simple close tag type = TagType.CLOSE; tagText = tagText.substring(1); } else { // It must be an open tag type = TagType.OPEN; // If open tag and starts with "s" like "script" or "style", than ... if ((tagText.length() > STYLE.length()) && ((tagText.charAt(0) == 's') || (tagText.charAt(0) == 'S'))) { final String lowerCase = tagText.substring(0, 6).toLowerCase(); if (lowerCase.startsWith(SCRIPT)) { // prepare to skip everything between the open and close tag skipUntilText = SCRIPT; } else if (lowerCase.startsWith(STYLE)) { // prepare to skip everything between the open and close tag skipUntilText = STYLE; } } } // Handle special tags like <!-- and <![CDATA ... final char firstChar = tagText.charAt(0); if ((firstChar == '!') || (firstChar == '?')) { specialTagHandling(tagText, openBracketIndex, closeBracketIndex); input.countLinesTo(openBracketIndex); TextSegment text = new TextSegment(lastText, openBracketIndex, input.getLineNumber(), input.getColumnNumber()); lastTag = new XmlTag(text, type); return lastType; } TextSegment text = new TextSegment(lastText, openBracketIndex, input.getLineNumber(), input.getColumnNumber()); XmlTag tag = new XmlTag(text, type); lastTag = tag; // Parse the tag text and populate tag attributes if (parseTagText(tag, tagText)) { // Move to position after the tag input.setPosition(closeBracketIndex + 1); lastType = HttpTagType.TAG; return lastType; } else { throw new ParseException("Malformed tag" + getLineAndColumnText(), openBracketIndex); } } /** * Handle special tags like <!-- --> or <![CDATA[..]]> or <?xml> * * @param tagText * @param openBracketIndex * @param closeBracketIndex * @throws ParseException */ protected void specialTagHandling(String tagText, final int openBracketIndex, int closeBracketIndex) throws ParseException { // Handle comments if (tagText.startsWith("!--")) { // downlevel-revealed conditional comments e.g.: <!--[if (gt IE9)|!(IE)]><!--> if (tagText.contains("![endif]--")) { lastType = HttpTagType.CONDITIONAL_COMMENT_ENDIF; // Move to position after the tag input.setPosition(closeBracketIndex + 1); return; } // Conditional comment? E.g. // "<!--[if IE]><a href='test.html'>my link</a><![endif]-->" if (tagText.startsWith("!--[if ") && tagText.endsWith("]")) { int pos = input.find("]-->", openBracketIndex + 1); if (pos == -1) { throw new ParseException("Unclosed conditional comment beginning at" + getLineAndColumnText(), openBracketIndex); } pos += 4; lastText = input.getSubstring(openBracketIndex, pos); // Actually it is no longer a comment. It is now // up to the browser to select the section appropriate. input.setPosition(closeBracketIndex + 1); lastType = HttpTagType.CONDITIONAL_COMMENT; } else { // Normal comment section. // Skip ahead to "-->". Note that you can not simply test for // tagText.endsWith("--") as the comment might contain a '>' // inside. int pos = input.find("-->", openBracketIndex + 1); if (pos == -1) { throw new ParseException("Unclosed comment beginning at" + getLineAndColumnText(), openBracketIndex); } pos += 3; lastText = input.getSubstring(openBracketIndex, pos); lastType = HttpTagType.COMMENT; input.setPosition(pos); } return; } // The closing tag of a conditional comment, e.g. // "<!--[if IE]><a href='test.html'>my link</a><![endif]--> // and also <!--<![endif]-->" if (tagText.equals("![endif]--")) { lastType = HttpTagType.CONDITIONAL_COMMENT_ENDIF; input.setPosition(closeBracketIndex + 1); return; } // CDATA sections might contain "<" which is not part of an XML tag. // Make sure escaped "<" are treated right if (tagText.startsWith("![")) { final String startText = (tagText.length() <= 8 ? tagText : tagText.substring(0, 8)); if (startText.toUpperCase().equals("![CDATA[")) { int pos1 = openBracketIndex; do { // Get index of closing tag and advance past the tag closeBracketIndex = findChar('>', pos1); if (closeBracketIndex == -1) { throw new ParseException("No matching close bracket at" + getLineAndColumnText(), input.getPosition()); } // Get the tagtext between open and close brackets tagText = input.getSubstring(openBracketIndex + 1, closeBracketIndex) .toString(); pos1 = closeBracketIndex + 1; } while (tagText.endsWith("]]") == false); // Move to position after the tag input.setPosition(closeBracketIndex + 1); lastText = tagText; lastType = HttpTagType.CDATA; return; } } if (tagText.charAt(0) == '?') { lastType = HttpTagType.PROCESSING_INSTRUCTION; // Move to position after the tag input.setPosition(closeBracketIndex + 1); return; } if (tagText.startsWith("!DOCTYPE")) { lastType = HttpTagType.DOCTYPE; // Get the tagtext between open and close brackets doctype = input.getSubstring(openBracketIndex + 1, closeBracketIndex); // Move to position after the tag input.setPosition(closeBracketIndex + 1); return; } // Move to position after the tag lastType = HttpTagType.SPECIAL_TAG; input.setPosition(closeBracketIndex + 1); } /** * @return MarkupElement */ public final XmlTag getElement() { return lastTag; } /** * @return The xml string from the last element */ public final CharSequence getString() { return lastText; } /** * @return The next XML tag * @throws ParseException */ public final XmlTag nextTag() throws ParseException { while (next() != HttpTagType.NOT_INITIALIZED) { switch (lastType) { case TAG : return lastTag; case BODY : break; case COMMENT : break; case CONDITIONAL_COMMENT : break; case CDATA : break; case PROCESSING_INSTRUCTION : break; case SPECIAL_TAG : break; } } return null; } /** * Find the char but ignore any text within ".." and '..' * * @param ch * The character to search * @param startIndex * Start index * @return -1 if not found, else the index */ private int findChar(final char ch, int startIndex) { char quote = 0; for (; startIndex < input.size(); startIndex++) { final char charAt = input.charAt(startIndex); if (quote != 0) { if (quote == charAt) { quote = 0; } } else if ((charAt == '"') || (charAt == '\'')) { quote = charAt; } else if (charAt == ch) { return startIndex; } } return -1; } /** * Parse the given string. * <p> * Note: xml character encoding is NOT applied. It is assumed the input provided does have the * correct encoding already. * * @param string * The input string * @throws IOException * Error while reading the resource * @throws ResourceStreamNotFoundException * Resource not found */ public void parse(final CharSequence string) throws IOException, ResourceStreamNotFoundException { parse(new ByteArrayInputStream(string.toString().getBytes()), null); } /** * Reads and parses markup from an input stream, using UTF-8 encoding by default when not * specified in XML declaration. * * @param in * The input stream to read and parse * @throws IOException * @throws ResourceStreamNotFoundException */ public void parse(final InputStream in) throws IOException, ResourceStreamNotFoundException { // When XML declaration does not specify encoding, it defaults to UTF-8 parse(in, "UTF-8"); } /** * Reads and parses markup from an input stream * * @param inputStream * The input stream to read and parse * @param encoding * The default character encoding of the input * @throws IOException */ public void parse(final InputStream inputStream, final String encoding) throws IOException { Args.notNull(inputStream, "inputStream"); try { xmlReader = new XmlReader(new BufferedInputStream(inputStream, 4000), encoding); input = new FullyBufferedReader(xmlReader); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(xmlReader); } } public final void setPositionMarker() { input.setPositionMarker(input.getPosition()); } public final void setPositionMarker(final int pos) { input.setPositionMarker(pos); } @Override public String toString() { return input.toString(); } /** * Parses the text between tags. For example, "a href=foo.html". * * @param tag * @param tagText * The text between tags * @return false in case of an error * @throws ParseException */ private boolean parseTagText(final XmlTag tag, final String tagText) throws ParseException { // Get the length of the tagtext final int tagTextLength = tagText.length(); // If we match tagname pattern final TagNameParser tagnameParser = new TagNameParser(tagText); if (tagnameParser.matcher().lookingAt()) { // Extract the tag from the pattern matcher tag.name = tagnameParser.getName(); tag.namespace = tagnameParser.getNamespace(); // Are we at the end? Then there are no attributes, so we just // return the tag int pos = tagnameParser.matcher().end(0); if (pos == tagTextLength) { return true; } // Extract attributes final VariableAssignmentParser attributeParser = new VariableAssignmentParser(tagText); while (attributeParser.matcher().find(pos)) { // Get key and value using attribute pattern String value = attributeParser.getValue(); // In case like <html xmlns:wicket> will the value be null if (value == null) { value = ""; } // Set new position to end of attribute pos = attributeParser.matcher().end(0); // Chop off double quotes or single quotes if (value.startsWith("\"") || value.startsWith("\'")) { value = value.substring(1, value.length() - 1); } // Trim trailing whitespace value = value.trim(); // Unescape value = Strings.unescapeMarkup(value).toString(); // Get key final String key = attributeParser.getKey(); // Put the attribute in the attributes hash if (null != tag.getAttributes().put(key, value)) { throw new ParseException("Same attribute found twice: " + key + getLineAndColumnText(), input.getPosition()); } // The input has to match exactly (no left over junk after // attributes) if (pos == tagTextLength) { return true; } } return true; } return false; } }
apache-2.0
m-m-m/multimedia
mmm-uit/mmm-uit-api/src/main/java/net/sf/mmm/ui/toolkit/api/view/UiElement.java
886
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.ui.toolkit.api.view; import net.sf.mmm.client.ui.api.attribute.AttributeWriteEnabled; import net.sf.mmm.client.ui.api.attribute.AttributeWriteSizeInPixel; import net.sf.mmm.client.ui.api.attribute.AttributeWriteTooltip; import net.sf.mmm.client.ui.api.attribute.AttributeWriteVisible; /** * This is the interface for a UI component. Such object is either a * {@link net.sf.mmm.ui.toolkit.api.view.widget.UiWidget widget} or a * {@link net.sf.mmm.ui.toolkit.api.view.composite.UiComposite composite} * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public interface UiElement extends UiNode, AttributeWriteVisible, AttributeWriteTooltip, AttributeWriteEnabled, AttributeWriteSizeInPixel { }
apache-2.0
manifold-systems/manifold
manifold-core-parent/manifold/src/main/java/manifold/api/util/JavacUtil.java
1176
/* * Copyright (c) 2020 - Manifold Systems 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 manifold.api.util; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.util.Context; import manifold.internal.javac.JavacPlugin; import javax.lang.model.SourceVersion; public class JavacUtil { public static SourceVersion getSourceVersion() { Context ctx = JavacPlugin.instance().getContext(); JavacProcessingEnvironment jpe = JavacProcessingEnvironment.instance( ctx ); return jpe.getSourceVersion(); } public static int getSourceNumber() { return getSourceVersion().ordinal(); } }
apache-2.0
campbe13/JavaSourceSamples360
labs/lab8/MovieRatings.java
1661
import java.util.Scanner; /** * implement average movie ratings method * * 360-420-DW Intro to Java * @author PMCampbell * @version today **/ public class MovieRatings { public static void main(String[] args) { double average; int ratings[][] = { {4,6,2,5}, {7,9,4}, {6,9,3,7}, {9,5,6,1,4}}; average = averageRatings(25, ratings); System.out.println("reviewer 25: " + average); average = averageRatings(-5, ratings); System.out.println("reviewer -5: " + average); average = averageRatings(1, ratings); System.out.println("reviewer 1: " + average); // over achiever show all reviewers for (int i = 0;i<ratings.length;i++) { System.out.printf("\nreviewer %d ratings %.2f ", i, averageRatings(i, ratings)); } } //main() /** * method to calculate average ratings, given a * movie reviewer * * @param int reviewer reviewer no (array index) * @param int [][] ratings array of review values * @return int average of all reviewers \ * or 0 if errir **/ public static double averageRatings(int reviewer, int ratings[][]) { double total=0; if (reviewer >= ratings.length || reviewer < 0) { // number of rows/reviewers // error condition return 0; } for (int movie=0; movie <ratings[reviewer].length; movie++) { // no of cols total += ratings[reviewer][movie]; } return total/ratings[reviewer].length; } // averageRatings() } // class
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-efs/src/main/java/com/amazonaws/services/elasticfilesystem/model/transform/ModifyMountTargetSecurityGroupsRequestProtocolMarshaller.java
2903
/* * 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.elasticfilesystem.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.elasticfilesystem.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ModifyMountTargetSecurityGroupsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ModifyMountTargetSecurityGroupsRequestProtocolMarshaller implements Marshaller<Request<ModifyMountTargetSecurityGroupsRequest>, ModifyMountTargetSecurityGroupsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/2015-02-01/mount-targets/{MountTargetId}/security-groups").httpMethodName(HttpMethodName.PUT).hasExplicitPayloadMember(false) .hasPayloadMembers(true).serviceName("AmazonElasticFileSystem").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public ModifyMountTargetSecurityGroupsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<ModifyMountTargetSecurityGroupsRequest> marshall(ModifyMountTargetSecurityGroupsRequest modifyMountTargetSecurityGroupsRequest) { if (modifyMountTargetSecurityGroupsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<ModifyMountTargetSecurityGroupsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, modifyMountTargetSecurityGroupsRequest); protocolMarshaller.startMarshalling(); ModifyMountTargetSecurityGroupsRequestMarshaller.getInstance().marshall(modifyMountTargetSecurityGroupsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
choodon/choodon-rpc
choodon-rpc-framework/src/main/java/com/choodon/rpc/framework/cluster/ha/HaStrategy.java
872
package com.choodon.rpc.framework.cluster.ha; import com.choodon.rpc.base.RPCCallback; import com.choodon.rpc.base.RPCFuture; import com.choodon.rpc.base.extension.Scope; import com.choodon.rpc.base.extension.Spi; import com.choodon.rpc.base.protocol.RPCRequest; import com.choodon.rpc.base.protocol.RPCResponse; import com.choodon.rpc.framework.cluster.loadbalance.LoadBalance; import com.choodon.rpc.framework.referer.Referer; import java.util.List; @Spi(scope = Scope.SINGLETON) public interface HaStrategy { RPCResponse syncCall(RPCRequest request, List<Referer> referers, LoadBalance loadBalance) throws Exception; RPCFuture asyncCall(RPCRequest request, List<Referer> referers, LoadBalance loadBalance) throws Exception; void callback(RPCRequest request, RPCCallback callBack, List<Referer> referers, LoadBalance loadBalance) throws Exception; }
apache-2.0