code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/* * Copyright 2014 Fitbur. * * 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.fitbur.docker.client.request.query; import com.fitbur.docker.client.DockerClient; import com.fitbur.docker.client.DockerClientException; import com.fitbur.docker.client.model.ContainerConfig; import com.fitbur.docker.client.model.CreateResponse; import com.fitbur.docker.client.request.BiQuery; import com.fitbur.docker.client.topic.ContainerTopic; import com.fitbur.docker.client.topic.event.ContainerEvent; import java.util.Map; import java.util.Optional; import javax.ws.rs.client.Entity; import static javax.ws.rs.client.Entity.entity; import javax.ws.rs.client.WebTarget; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import javax.ws.rs.core.Response; import org.jvnet.hk2.annotations.Service; /** * * @author Sharmarke Aden */ @Service public class CreateContainer implements BiQuery<ContainerConfig, CreateResponse> { @Override public CreateResponse execute(DockerClient client, Optional<ContainerConfig> createConfig) { WebTarget target = client.target() .path("containers") .path("create"); ContainerConfig configEntity = createConfig.get(); for (Map.Entry<String, Object> param : configEntity.getQueryParams().entrySet()) { target = target.queryParam(param.getKey(), param.getValue()); } Entity<ContainerConfig> entity = entity(configEntity, APPLICATION_JSON); Response response = target .request(APPLICATION_JSON) .post(entity); CreateResponse result; if (response.getStatus() < 400) { result = response.readEntity(CreateResponse.class); } else { throw new DockerClientException(response.readEntity(String.class)); } client.publish(new ContainerTopic(result.getId(), ContainerEvent.CREATED)); return result; } }
MagIciaNGTAO/docker-client
src/main/java/com/fitbur/docker/client/request/query/CreateContainer.java
Java
apache-2.0
2,473
package com.morgan.demo.mockdata; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; /** * 一个包含pageNumber个测试页面的FragmentPagerAdapter。 * * @author JiGuoChao * * @version 1.0 * * @date 2014-7-18 */ public class MockFragmentPagerAdapter extends FragmentPagerAdapter { private Context mContext; private int pageNumber = 3; // 生成Page的个数。 public MockFragmentPagerAdapter(Context context, FragmentManager fm) { super(fm); mContext = context; } @Override public Fragment getItem(int position) { return MockListFragment.instantiate(mContext, MockListFragment.class.getName()); } @Override public int getCount() { return pageNumber; } }
WanderingSeed/Common-Library-Demo
src/com/morgan/demo/mockdata/MockFragmentPagerAdapter.java
Java
apache-2.0
819
// Copyright 2007, 2010 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.internal; /** * Used as test when setting the order of properties in a {@link org.apache.tapestry5.beaneditor.BeanModel}. */ public class DataBean { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } }
agileowl/tapestry-5
tapestry-core/src/test/java/org/apache/tapestry5/internal/DataBean.java
Java
apache-2.0
1,335
package io.dropwizard.jersey.optional; import io.dropwizard.jersey.AbstractJerseyTest; import io.dropwizard.jersey.DropwizardResourceConfig; import io.dropwizard.jersey.MyMessage; import io.dropwizard.jersey.MyMessageParamConverterProvider; import io.dropwizard.jersey.params.UUIDParam; import org.glassfish.jersey.internal.util.collection.MultivaluedStringMap; import org.junit.Test; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Application; import javax.ws.rs.core.Form; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; public class OptionalFormParamResourceTest extends AbstractJerseyTest { @Override protected Application configure() { return DropwizardResourceConfig.forTesting() .register(OptionalFormParamResource.class) .register(MyMessageParamConverterProvider.class); } @Test public void shouldReturnDefaultMessageWhenMessageIsNotPresent() throws IOException { final String defaultMessage = "Default Message"; final Response response = target("/optional/message").request().post(Entity.form(new MultivaluedStringMap())); assertThat(response.readEntity(String.class)).isEqualTo(defaultMessage); } @Test public void shouldReturnMessageWhenMessageBlank() throws IOException { final Form form = new Form("message", ""); final Response response = target("/optional/message").request().post(Entity.form(form)); assertThat(response.readEntity(String.class)).isEqualTo(""); } @Test public void shouldReturnMessageWhenMessageIsPresent() throws IOException { final String customMessage = "Custom Message"; final Form form = new Form("message", customMessage); final Response response = target("/optional/message").request().post(Entity.form(form)); assertThat(response.readEntity(String.class)).isEqualTo(customMessage); } @Test public void shouldReturnDefaultMessageWhenMyMessageIsNotPresent() throws IOException { final String defaultMessage = "My Default Message"; final Response response = target("/optional/my-message").request().post(Entity.form(new MultivaluedStringMap())); assertThat(response.readEntity(String.class)).isEqualTo(defaultMessage); } @Test public void shouldReturnMyMessageWhenMyMessageIsPresent() throws IOException { final String myMessage = "My Message"; final Form form = new Form("mymessage", myMessage); final Response response = target("/optional/my-message").request().post(Entity.form(form)); assertThat(response.readEntity(String.class)).isEqualTo(myMessage); } @Test public void shouldThrowBadRequestExceptionWhenInvalidUUIDIsPresent() throws IOException { final String invalidUUID = "invalid-uuid"; final Form form = new Form("uuid", invalidUUID); final Response response = target("/optional/uuid").request().post(Entity.form(form)); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); } @Test public void shouldReturnDefaultUUIDWhenUUIDIsNotPresent() throws IOException { final String defaultUUID = "d5672fa8-326b-40f6-bf71-d9dacf44bcdc"; final Response response = target("/optional/uuid").request().post(Entity.form(new MultivaluedStringMap())); assertThat(response.readEntity(String.class)).isEqualTo(defaultUUID); } @Test public void shouldReturnUUIDWhenValidUUIDIsPresent() throws IOException { final String uuid = "fd94b00d-bd50-46b3-b42f-905a9c9e7d78"; final Form form = new Form("uuid", uuid); final Response response = target("/optional/uuid").request().post(Entity.form(form)); assertThat(response.readEntity(String.class)).isEqualTo(uuid); } @Path("/optional") public static class OptionalFormParamResource { @POST @Path("/message") public String getMessage(@FormParam("message") Optional<String> message) { return message.orElse("Default Message"); } @POST @Path("/my-message") public String getMyMessage(@FormParam("mymessage") Optional<MyMessage> myMessage) { return myMessage.orElse(new MyMessage("My Default Message")).getMessage(); } @POST @Path("/uuid") public String getUUID(@FormParam("uuid") Optional<UUIDParam> uuid) { return uuid.orElse(new UUIDParam("d5672fa8-326b-40f6-bf71-d9dacf44bcdc")).get().toString(); } } }
nickbabcock/dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/optional/OptionalFormParamResourceTest.java
Java
apache-2.0
4,743
package com.diamondq.common.jaxrs.model; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AbstractMethodJAXRSApplicationInfo implements JAXRSApplicationInfo { private static final Logger sLogger = LoggerFactory.getLogger(AbstractMethodJAXRSApplicationInfo.class); protected Set<Class<?>> mClasses; protected Set<Object> mSingletons; protected Map<String, Object> mProperties; public AbstractMethodJAXRSApplicationInfo() { mClasses = new HashSet<>(); mSingletons = new HashSet<>(); mProperties = new HashMap<>(); } /** * @see com.diamondq.common.jaxrs.model.JAXRSApplicationInfo#getClasses() */ @Override public Set<Class<?>> getClasses() { sLogger.trace("getClasses() from {}", this); return mClasses; } /** * @see com.diamondq.common.jaxrs.model.JAXRSApplicationInfo#getSingletons() */ @Override public Set<Object> getSingletons() { sLogger.trace("getSingletons() from {}", this); return mSingletons; } /** * @see com.diamondq.common.jaxrs.model.JAXRSApplicationInfo#getProperties() */ @Override public Map<String, Object> getProperties() { sLogger.trace("getProperties() from {}", this); return mProperties; } }
diamondq/dq-common-java
jaxrs/common-jaxrs.common/src/main/java/com/diamondq/common/jaxrs/model/AbstractMethodJAXRSApplicationInfo.java
Java
apache-2.0
1,401
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/8.5.11 * Generated at: 2017-05-04 09:09:44 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class macdinh_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(5); _jspx_dependants.put("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar", Long.valueOf(1493259754000L)); _jspx_dependants.put("jar:file:/root/tomcat/tomcat-8.5.11/webapps/engreview/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar!/META-INF/c.tld", Long.valueOf(1425978670000L)); _jspx_dependants.put("/footer.jsp", Long.valueOf(1493259754000L)); _jspx_dependants.put("/import.jsp", Long.valueOf(1493259754000L)); _jspx_dependants.put("/header.jsp", Long.valueOf(1493857769000L)); } private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody; private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); } public void _jspDestroy() { _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.release(); } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final java.lang.String _jspx_method = request.getMethod(); if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD"); return; } final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"); out.write("<html>\n"); out.write("<head>\n"); out.write("\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); out.write("<link rel=\"shortcut icon\" type=\"image/ico\" href=\"favicon.ico\" /> \n"); out.write("<script type=\"text/javascript\" src=\""); out.print(request.getContextPath()); out.write("/js/jquery.min.js\" ></script>\n"); out.write("<script type=\"text/javascript\" src=\""); out.print(request.getContextPath()); out.write("/js/Chart.js\" ></script>\n"); out.write("<script type=\"text/javascript\" src=\""); out.print(request.getContextPath()); out.write("/js/Chart.min.js\" ></script>\n"); out.write("<script type=\"text/javascript\" src=\""); out.print(request.getContextPath()); out.write("/js/src/Chart.Line.js\" ></script>\n"); out.write("\n"); out.write("\n"); out.write("<link rel=\"stylesheet\" href=\""); out.print(request.getContextPath()); out.write("/css/all.css\" >\n"); out.write("\n"); out.write(" "); out.write(" \n"); out.write("<title>Cài đặt mặc định</title>\n"); out.write("</head>\n"); out.write("<body>\n"); out.write("\t"); out.write("\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"); out.write("<html>\n"); out.write("<head> \n"); out.write("<style>\n"); out.write("ul {\n"); out.write(" margin: 0;\n"); out.write(" padding: 0;\n"); out.write(" overflow: hidden;\n"); out.write(" border: 1px solid #e7e7e7;\n"); out.write(" background-color: #f3f3f3;\n"); out.write(" list-style: none;\n"); out.write(" margin-top: 10px;\n"); out.write("}\n"); out.write(" \n"); out.write("li {\n"); out.write(" \tfloat: left; \n"); out.write("}\n"); out.write("\n"); out.write("li a {\n"); out.write(" display: block;\n"); out.write(" color: #666;\n"); out.write(" text-align: center;\n"); out.write(" padding: 5px 10px;\n"); out.write(" text-decoration: none;\n"); out.write("}\n"); out.write("\n"); out.write("li a:hover:not(.active) {\n"); out.write(" background-color: #ddd;\n"); out.write("}\n"); out.write("\n"); out.write("li a.active {\n"); out.write(" color: white;\n"); out.write(" background-color: #4CAF50;\n"); out.write("}\n"); out.write("</style>\n"); out.write("</head>\n"); out.write("<body>\n"); out.write("\t<ul>\n"); out.write(" <li><a id=\"home\" href=\""); out.print(request.getContextPath()); out.write("\">Home</a></li> \n"); out.write(" <li><a id=\"anhviet\" href=\""); out.print(request.getContextPath()); out.write("/anhviet\">Anh-Việt</a></li>\n"); out.write(" <li><a id=\"vietanh\" href=\""); out.print(request.getContextPath()); out.write("/vietanh\">Việt-Anh</a></li>\n"); out.write(" <li><a id=\"chitiet\" href=\""); out.print(request.getContextPath()); out.write("/chitiet\">Chi tiết</a></li>\n"); out.write(" <li><a id=\"toeic600\" href=\""); out.print(request.getContextPath()); out.write("/toeic600\">Toeic 600</a></li>\n"); out.write(" <li><a id=\"macdinh\" href=\""); out.print(request.getContextPath()); out.write("/macdinh\">Cài đặt</a></li>\n"); out.write(" <li><a id=\"homnay\" href=\""); out.print(request.getContextPath()); out.write("/homnay\">Hôm nay</a></li>\n"); out.write(" <li><a id=\"homqua\" href=\""); out.print(request.getContextPath()); out.write("/homqua\">Hôm qua</a></li>\n"); out.write(" <li><a id=\"homkia\" href=\""); out.print(request.getContextPath()); out.write("/homkia\">Hôm kia</a></li> \n"); out.write(" <li><a id=\"fibonaci\" href=\""); out.print(request.getContextPath()); out.write("/fibonaci\">Fibonaci</a></li>\n"); out.write(" <li><a id=\"ontap\" href=\""); out.print(request.getContextPath()); out.write("/ontap\">Ôn tập</a></li>\n"); out.write(" <li><a id=\"filter\" href=\""); out.print(request.getContextPath()); out.write("/chaofilter\">Chao Filter</a></li>\n"); out.write(" \n"); out.write(" <li><a id=\"theodoi\" href=\""); out.print(request.getContextPath()); out.write("/theodoi\">Theo dõi</a></li>\n"); out.write("</ul>\n"); out.write("</body>\n"); out.write("</html>"); out.write(" \n"); out.write("\t<hr>\n"); out.write("\t \n"); out.write("\t<!-- FORM NHAP TU VUNG -->\n"); out.write("\t<form action=\""); out.print(request.getContextPath()); out.write("/macdinh\" method=\"post\" >\n"); out.write("\t\t<table>\n"); out.write("\t\t\t<tr>\n"); out.write("\t\t\t\t<td>Mặc định từ loại:</td>\n"); out.write("\t\t\t\t<td><input id=\"tuloai\" name=\"tuloai\" type=\"text\" size=\"50\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${sessionScope.tuloai}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\" ></td>\n"); out.write("\t\t\t</tr>\n"); out.write("\t\t\t<tr>\n"); out.write("\t\t\t\t<td>Mặc định nơi học:</td>\n"); out.write("\t\t\t\t<td><input id=\"noihoc\" name=\"noihoc\" type=\"text\" size=\"50\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${sessionScope.noihoc}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\" ></td>\n"); out.write("\t\t\t</tr>\n"); out.write("\t\t\t<tr>\n"); out.write("\t\t\t\t<td>Mặc định ghi chú:</td>\n"); out.write("\t\t\t\t<td><input id=\"ghichu\" name=\"ghichu\" type=\"text\" size=\"50\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${sessionScope.ghichu}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\" ></td>\n"); out.write("\t\t\t</tr>\n"); out.write("\t\t\t<tr>\n"); out.write("\t\t\t\t<td> </td>\n"); out.write("\t\t\t\t<td> "); if (_jspx_meth_c_005fout_005f0(_jspx_page_context)) return; out.write(" </td>\n"); out.write("\t\t\t</tr>\n"); out.write("\t\t\t \n"); out.write("\t\t</table> \n"); out.write("\t\t<input type=\"submit\" >\n"); out.write("\t</form>\n"); out.write("\n"); out.write("\t<hr>\n"); out.write("\t"); out.write("\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"); out.write("<html>\n"); out.write("<head>\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); out.write("</head>\n"); out.write("<body>\n"); out.write("\tfoooter\n"); out.write("</body>\n"); out.write("</html>"); out.write("\n"); out.write("\n"); out.write("\t<script type=\"text/javascript\">\n"); out.write("\t\t$(document).ready(function() {\n"); out.write("\t\t\t$(\"#macdinh\").addClass(\"active\");\n"); out.write("\t\t});\n"); out.write("\t</script>\n"); out.write("</body>\n"); out.write("</html>\n"); out.write("\n"); out.write("\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_c_005fout_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_005fout_005f0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); boolean _jspx_th_c_005fout_005f0_reused = false; try { _jspx_th_c_005fout_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fout_005f0.setParent(null); // /macdinh.jsp(32,9) name = value type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fout_005f0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${daxong }", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); int _jspx_eval_c_005fout_005f0 = _jspx_th_c_005fout_005f0.doStartTag(); if (_jspx_th_c_005fout_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } _005fjspx_005ftagPool_005fc_005fout_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005fout_005f0); _jspx_th_c_005fout_005f0_reused = true; } finally { if (!_jspx_th_c_005fout_005f0_reused) { _jspx_th_c_005fout_005f0.release(); _jsp_getInstanceManager().destroyInstance(_jspx_th_c_005fout_005f0); } } return false; } }
ngocvantu/tomcat-8.5.11
work/Catalina/localhost/engreview/org/apache/jsp/macdinh_jsp.java
Java
apache-2.0
15,106
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.io.hfile; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseTestCase; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.KeyValue.Type; import org.apache.hadoop.hbase.KeyValueUtil; import org.apache.hadoop.hbase.Tag; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.io.hfile.HFile.Reader; import org.apache.hadoop.hbase.io.hfile.HFile.Writer; import org.apache.hadoop.hbase.nio.ByteBuff; import org.apache.hadoop.hbase.nio.MultiByteBuff; import org.apache.hadoop.hbase.testclassification.IOTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Writable; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; /** * test hfile features. * <p> * Copied from * <a href="https://issues.apache.org/jira/browse/HADOOP-3315">hadoop-3315 tfile</a>. * Remove after tfile is committed and use the tfile version of this class * instead.</p> */ @Category({IOTests.class, SmallTests.class}) public class TestHFile extends HBaseTestCase { private static final Log LOG = LogFactory.getLog(TestHFile.class); private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private static String ROOT_DIR = TEST_UTIL.getDataTestDir("TestHFile").toString(); private final int minBlockSize = 512; private static String localFormatter = "%010d"; private static CacheConfig cacheConf = null; private Map<String, Long> startingMetrics; @Before public void setUp() throws Exception { super.setUp(); } @After public void tearDown() throws Exception { super.tearDown(); } /** * Test empty HFile. * Test all features work reasonably when hfile is empty of entries. * @throws IOException */ @Test public void testEmptyHFile() throws IOException { if (cacheConf == null) cacheConf = new CacheConfig(conf); Path f = new Path(ROOT_DIR, getName()); HFileContext context = new HFileContextBuilder().withIncludesTags(false).build(); Writer w = HFile.getWriterFactory(conf, cacheConf).withPath(fs, f).withFileContext(context).create(); w.close(); Reader r = HFile.createReader(fs, f, cacheConf, conf); r.loadFileInfo(); assertNull(r.getFirstKey()); assertNull(r.getLastKey()); } /** * Create 0-length hfile and show that it fails */ @Test public void testCorrupt0LengthHFile() throws IOException { if (cacheConf == null) cacheConf = new CacheConfig(conf); Path f = new Path(ROOT_DIR, getName()); FSDataOutputStream fsos = fs.create(f); fsos.close(); try { Reader r = HFile.createReader(fs, f, cacheConf, conf); } catch (CorruptHFileException che) { // Expected failure return; } fail("Should have thrown exception"); } public static void truncateFile(FileSystem fs, Path src, Path dst) throws IOException { FileStatus fst = fs.getFileStatus(src); long len = fst.getLen(); len = len / 2 ; // create a truncated hfile FSDataOutputStream fdos = fs.create(dst); byte[] buf = new byte[(int)len]; FSDataInputStream fdis = fs.open(src); fdis.read(buf); fdos.write(buf); fdis.close(); fdos.close(); } /** * Create a truncated hfile and verify that exception thrown. */ @Test public void testCorruptTruncatedHFile() throws IOException { if (cacheConf == null) cacheConf = new CacheConfig(conf); Path f = new Path(ROOT_DIR, getName()); HFileContext context = new HFileContextBuilder().build(); Writer w = HFile.getWriterFactory(conf, cacheConf).withPath(this.fs, f) .withFileContext(context).create(); writeSomeRecords(w, 0, 100, false); w.close(); Path trunc = new Path(f.getParent(), "trucated"); truncateFile(fs, w.getPath(), trunc); try { Reader r = HFile.createReader(fs, trunc, cacheConf, conf); } catch (CorruptHFileException che) { // Expected failure return; } fail("Should have thrown exception"); } // write some records into the tfile // write them twice private int writeSomeRecords(Writer writer, int start, int n, boolean useTags) throws IOException { String value = "value"; KeyValue kv; for (int i = start; i < (start + n); i++) { String key = String.format(localFormatter, Integer.valueOf(i)); if (useTags) { Tag t = new Tag((byte) 1, "myTag1"); Tag[] tags = new Tag[1]; tags[0] = t; kv = new KeyValue(Bytes.toBytes(key), Bytes.toBytes("family"), Bytes.toBytes("qual"), HConstants.LATEST_TIMESTAMP, Bytes.toBytes(value + key), tags); writer.append(kv); } else { kv = new KeyValue(Bytes.toBytes(key), Bytes.toBytes("family"), Bytes.toBytes("qual"), Bytes.toBytes(value + key)); writer.append(kv); } } return (start + n); } private void readAllRecords(HFileScanner scanner) throws IOException { readAndCheckbytes(scanner, 0, 100); } // read the records and check private int readAndCheckbytes(HFileScanner scanner, int start, int n) throws IOException { String value = "value"; int i = start; for (; i < (start + n); i++) { ByteBuffer key = ByteBuffer.wrap(((KeyValue)scanner.getKey()).getKey()); ByteBuffer val = scanner.getValue(); String keyStr = String.format(localFormatter, Integer.valueOf(i)); String valStr = value + keyStr; KeyValue kv = new KeyValue(Bytes.toBytes(keyStr), Bytes.toBytes("family"), Bytes.toBytes("qual"), Bytes.toBytes(valStr)); byte[] keyBytes = new KeyValue.KeyOnlyKeyValue(Bytes.toBytes(key), 0, Bytes.toBytes(key).length).getKey(); assertTrue("bytes for keys do not match " + keyStr + " " + Bytes.toString(Bytes.toBytes(key)), Arrays.equals(kv.getKey(), keyBytes)); byte [] valBytes = Bytes.toBytes(val); assertTrue("bytes for vals do not match " + valStr + " " + Bytes.toString(valBytes), Arrays.equals(Bytes.toBytes(valStr), valBytes)); if (!scanner.next()) { break; } } assertEquals(i, start + n - 1); return (start + n); } private byte[] getSomeKey(int rowId) { KeyValue kv = new KeyValue(String.format(localFormatter, Integer.valueOf(rowId)).getBytes(), Bytes.toBytes("family"), Bytes.toBytes("qual"), HConstants.LATEST_TIMESTAMP, Type.Put); return kv.getKey(); } private void writeRecords(Writer writer, boolean useTags) throws IOException { writeSomeRecords(writer, 0, 100, useTags); writer.close(); } private FSDataOutputStream createFSOutput(Path name) throws IOException { //if (fs.exists(name)) fs.delete(name, true); FSDataOutputStream fout = fs.create(name); return fout; } /** * test none codecs * @param useTags */ void basicWithSomeCodec(String codec, boolean useTags) throws IOException { if (useTags) { conf.setInt("hfile.format.version", 3); } if (cacheConf == null) cacheConf = new CacheConfig(conf); Path ncTFile = new Path(ROOT_DIR, "basic.hfile." + codec.toString() + useTags); FSDataOutputStream fout = createFSOutput(ncTFile); HFileContext meta = new HFileContextBuilder() .withBlockSize(minBlockSize) .withCompression(HFileWriterImpl.compressionByName(codec)) .build(); Writer writer = HFile.getWriterFactory(conf, cacheConf) .withOutputStream(fout) .withFileContext(meta) .withComparator(CellComparator.COMPARATOR) .create(); LOG.info(writer); writeRecords(writer, useTags); fout.close(); FSDataInputStream fin = fs.open(ncTFile); Reader reader = HFile.createReaderFromStream(ncTFile, fs.open(ncTFile), fs.getFileStatus(ncTFile).getLen(), cacheConf, conf); System.out.println(cacheConf.toString()); // Load up the index. reader.loadFileInfo(); // Get a scanner that caches and that does not use pread. HFileScanner scanner = reader.getScanner(true, false); // Align scanner at start of the file. scanner.seekTo(); readAllRecords(scanner); int seekTo = scanner.seekTo(KeyValueUtil.createKeyValueFromKey(getSomeKey(50))); System.out.println(seekTo); assertTrue("location lookup failed", scanner.seekTo(KeyValueUtil.createKeyValueFromKey(getSomeKey(50))) == 0); // read the key and see if it matches ByteBuffer readKey = ByteBuffer.wrap(((KeyValue)scanner.getKey()).getKey()); assertTrue("seeked key does not match", Arrays.equals(getSomeKey(50), Bytes.toBytes(readKey))); scanner.seekTo(KeyValueUtil.createKeyValueFromKey(getSomeKey(0))); ByteBuffer val1 = scanner.getValue(); scanner.seekTo(KeyValueUtil.createKeyValueFromKey(getSomeKey(0))); ByteBuffer val2 = scanner.getValue(); assertTrue(Arrays.equals(Bytes.toBytes(val1), Bytes.toBytes(val2))); reader.close(); fin.close(); fs.delete(ncTFile, true); } @Test public void testTFileFeatures() throws IOException { testTFilefeaturesInternals(false); testTFilefeaturesInternals(true); } @Test protected void testTFilefeaturesInternals(boolean useTags) throws IOException { basicWithSomeCodec("none", useTags); basicWithSomeCodec("gz", useTags); } private void writeNumMetablocks(Writer writer, int n) { for (int i = 0; i < n; i++) { writer.appendMetaBlock("HFileMeta" + i, new Writable() { private int val; public Writable setVal(int val) { this.val = val; return this; } @Override public void write(DataOutput out) throws IOException { out.write(("something to test" + val).getBytes()); } @Override public void readFields(DataInput in) throws IOException { } }.setVal(i)); } } private void someTestingWithMetaBlock(Writer writer) { writeNumMetablocks(writer, 10); } private void readNumMetablocks(Reader reader, int n) throws IOException { for (int i = 0; i < n; i++) { ByteBuff actual = reader.getMetaBlock("HFileMeta" + i, false).getBufferWithoutHeader(); ByteBuffer expected = ByteBuffer.wrap(("something to test" + i).getBytes()); assertEquals( "failed to match metadata", Bytes.toStringBinary(expected), Bytes.toStringBinary(actual.array(), actual.arrayOffset() + actual.position(), actual.capacity())); } } private void someReadingWithMetaBlock(Reader reader) throws IOException { readNumMetablocks(reader, 10); } private void metablocks(final String compress) throws Exception { if (cacheConf == null) cacheConf = new CacheConfig(conf); Path mFile = new Path(ROOT_DIR, "meta.hfile"); FSDataOutputStream fout = createFSOutput(mFile); HFileContext meta = new HFileContextBuilder() .withCompression(HFileWriterImpl.compressionByName(compress)) .withBlockSize(minBlockSize).build(); Writer writer = HFile.getWriterFactory(conf, cacheConf) .withOutputStream(fout) .withFileContext(meta) .create(); someTestingWithMetaBlock(writer); writer.close(); fout.close(); FSDataInputStream fin = fs.open(mFile); Reader reader = HFile.createReaderFromStream(mFile, fs.open(mFile), this.fs.getFileStatus(mFile).getLen(), cacheConf, conf); reader.loadFileInfo(); // No data -- this should return false. assertFalse(reader.getScanner(false, false).seekTo()); someReadingWithMetaBlock(reader); fs.delete(mFile, true); reader.close(); fin.close(); } // test meta blocks for tfiles @Test public void testMetaBlocks() throws Exception { metablocks("none"); metablocks("gz"); } @Test public void testNullMetaBlocks() throws Exception { if (cacheConf == null) cacheConf = new CacheConfig(conf); for (Compression.Algorithm compressAlgo : HBaseTestingUtility.COMPRESSION_ALGORITHMS) { Path mFile = new Path(ROOT_DIR, "nometa_" + compressAlgo + ".hfile"); FSDataOutputStream fout = createFSOutput(mFile); HFileContext meta = new HFileContextBuilder().withCompression(compressAlgo) .withBlockSize(minBlockSize).build(); Writer writer = HFile.getWriterFactory(conf, cacheConf) .withOutputStream(fout) .withFileContext(meta) .create(); KeyValue kv = new KeyValue("foo".getBytes(), "f1".getBytes(), null, "value".getBytes()); writer.append(kv); writer.close(); fout.close(); Reader reader = HFile.createReader(fs, mFile, cacheConf, conf); reader.loadFileInfo(); assertNull(reader.getMetaBlock("non-existant", false)); } } /** * Make sure the ordinals for our compression algorithms do not change on us. */ public void testCompressionOrdinance() { assertTrue(Compression.Algorithm.LZO.ordinal() == 0); assertTrue(Compression.Algorithm.GZ.ordinal() == 1); assertTrue(Compression.Algorithm.NONE.ordinal() == 2); assertTrue(Compression.Algorithm.SNAPPY.ordinal() == 3); assertTrue(Compression.Algorithm.LZ4.ordinal() == 4); } @Test public void testGetShortMidpoint() { Cell left = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); Cell right = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); Cell mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) <= 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) <= 0); left = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("b"), Bytes.toBytes("a"), Bytes.toBytes("a")); mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) <= 0); left = CellUtil.createCell(Bytes.toBytes("g"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("i"), Bytes.toBytes("a"), Bytes.toBytes("a")); mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) <= 0); left = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("bbbbbbb"), Bytes.toBytes("a"), Bytes.toBytes("a")); mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) < 0); assertEquals(1, (int) mid.getRowLength()); left = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("a")); mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) <= 0); left = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("aaaaaaaa"), Bytes.toBytes("b")); mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) < 0); assertEquals(2, (int) mid.getFamilyLength()); left = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("aaaaaaaaa")); mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) < 0); assertEquals(2, (int) mid.getQualifierLength()); left = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("a"), Bytes.toBytes("a"), Bytes.toBytes("b")); mid = HFileWriterImpl.getMidpoint(CellComparator.COMPARATOR, left, right); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.COMPARATOR.compareKeyIgnoresMvcc(mid, right) <= 0); assertEquals(1, (int) mid.getQualifierLength()); // Assert that if meta comparator, it returns the right cell -- i.e. no // optimization done. left = CellUtil.createCell(Bytes.toBytes("g"), Bytes.toBytes("a"), Bytes.toBytes("a")); right = CellUtil.createCell(Bytes.toBytes("i"), Bytes.toBytes("a"), Bytes.toBytes("a")); mid = HFileWriterImpl.getMidpoint(CellComparator.META_COMPARATOR, left, right); assertTrue(CellComparator.META_COMPARATOR.compareKeyIgnoresMvcc(left, mid) < 0); assertTrue(CellComparator.META_COMPARATOR.compareKeyIgnoresMvcc(mid, right) == 0); /** * See HBASE-7845 */ byte[] rowA = Bytes.toBytes("rowA"); byte[] rowB = Bytes.toBytes("rowB"); byte[] family = Bytes.toBytes("family"); byte[] qualA = Bytes.toBytes("qfA"); byte[] qualB = Bytes.toBytes("qfB"); final CellComparator keyComparator = CellComparator.COMPARATOR; // verify that faked shorter rowkey could be generated long ts = 5; KeyValue kv1 = new KeyValue(Bytes.toBytes("the quick brown fox"), family, qualA, ts, Type.Put); KeyValue kv2 = new KeyValue(Bytes.toBytes("the who test text"), family, qualA, ts, Type.Put); Cell newKey = HFileWriterImpl.getMidpoint(keyComparator, kv1, kv2); assertTrue(keyComparator.compare(kv1, newKey) < 0); assertTrue((keyComparator.compare(kv2, newKey)) > 0); byte[] expectedArray = Bytes.toBytes("the r"); Bytes.equals(newKey.getRowArray(), newKey.getRowOffset(), newKey.getRowLength(), expectedArray, 0, expectedArray.length); // verify: same with "row + family + qualifier", return rightKey directly kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, 5, Type.Put); kv2 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, 0, Type.Put); assertTrue(keyComparator.compare(kv1, kv2) < 0); newKey = HFileWriterImpl.getMidpoint(keyComparator, kv1, kv2); assertTrue(keyComparator.compare(kv1, newKey) < 0); assertTrue((keyComparator.compare(kv2, newKey)) == 0); kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, -5, Type.Put); kv2 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, -10, Type.Put); assertTrue(keyComparator.compare(kv1, kv2) < 0); newKey = HFileWriterImpl.getMidpoint(keyComparator, kv1, kv2); assertTrue(keyComparator.compare(kv1, newKey) < 0); assertTrue((keyComparator.compare(kv2, newKey)) == 0); // verify: same with row, different with qualifier kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, 5, Type.Put); kv2 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualB, 5, Type.Put); assertTrue(keyComparator.compare(kv1, kv2) < 0); newKey = HFileWriterImpl.getMidpoint(keyComparator, kv1, kv2); assertTrue(keyComparator.compare(kv1, newKey) < 0); assertTrue((keyComparator.compare(kv2, newKey)) > 0); assertTrue(Arrays.equals(CellUtil.cloneFamily(newKey), family)); assertTrue(Arrays.equals(CellUtil.cloneQualifier(newKey), qualB)); assertTrue(newKey.getTimestamp() == HConstants.LATEST_TIMESTAMP); assertTrue(newKey.getTypeByte() == Type.Maximum.getCode()); // verify metaKeyComparator's getShortMidpointKey output final CellComparator metaKeyComparator = CellComparator.META_COMPARATOR; kv1 = new KeyValue(Bytes.toBytes("ilovehbase123"), family, qualA, 5, Type.Put); kv2 = new KeyValue(Bytes.toBytes("ilovehbase234"), family, qualA, 0, Type.Put); newKey = HFileWriterImpl.getMidpoint(metaKeyComparator, kv1, kv2); assertTrue(metaKeyComparator.compare(kv1, newKey) < 0); assertTrue((metaKeyComparator.compare(kv2, newKey) == 0)); // verify common fix scenario kv1 = new KeyValue(Bytes.toBytes("ilovehbase"), family, qualA, ts, Type.Put); kv2 = new KeyValue(Bytes.toBytes("ilovehbaseandhdfs"), family, qualA, ts, Type.Put); assertTrue(keyComparator.compare(kv1, kv2) < 0); newKey = HFileWriterImpl.getMidpoint(keyComparator, kv1, kv2); assertTrue(keyComparator.compare(kv1, newKey) < 0); assertTrue((keyComparator.compare(kv2, newKey)) > 0); expectedArray = Bytes.toBytes("ilovehbasea"); Bytes.equals(newKey.getRowArray(), newKey.getRowOffset(), newKey.getRowLength(), expectedArray, 0, expectedArray.length); // verify only 1 offset scenario kv1 = new KeyValue(Bytes.toBytes("100abcdefg"), family, qualA, ts, Type.Put); kv2 = new KeyValue(Bytes.toBytes("101abcdefg"), family, qualA, ts, Type.Put); assertTrue(keyComparator.compare(kv1, kv2) < 0); newKey = HFileWriterImpl.getMidpoint(keyComparator, kv1, kv2); assertTrue(keyComparator.compare(kv1, newKey) < 0); assertTrue((keyComparator.compare(kv2, newKey)) > 0); expectedArray = Bytes.toBytes("101"); Bytes.equals(newKey.getRowArray(), newKey.getRowOffset(), newKey.getRowLength(), expectedArray, 0, expectedArray.length); } }
juwi/hbase
hbase-server/src/test/java/org/apache/hadoop/hbase/io/hfile/TestHFile.java
Java
apache-2.0
23,403
package general; import input.InputHandler; import input.factories.InputHandlerFactory; import openrdffork.TupleExprWrapper; import org.apache.log4j.Logger; import output.OutputHandler; import output.factories.OutputHandlerFactory; import query.factories.QueryHandlerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author Julius Gonsior */ public class ParseOneDayWorker implements Runnable { /** * Define a static logger variable. */ private static final Logger logger = Logger.getLogger(ParseOneDayWorker.class); /** * The inputHandler to process from. */ private InputHandler inputHandler; /** * The output handler to process to. */ private OutputHandler outputHandler; /** * The day this worker is processing. */ private int day; /** * @param inputHandlerFactory The input handler factory to supply the input handler. * @param inputFile The file to read from. * @param outputHandlerFactory The output handler factory to supply the output handler. * @param outputFile The file to write to. * @param queryHandlerFactory The query handler factory to supply the query handler. * @param dayToSet The day being processed. * @param writeQueryTypes If the query types should be written or not. * @throws IOException If the input or output handler could not be created. */ public ParseOneDayWorker(InputHandlerFactory inputHandlerFactory, String inputFile, OutputHandlerFactory outputHandlerFactory, String outputFile, QueryHandlerFactory queryHandlerFactory, int dayToSet, Boolean writeQueryTypes) throws IOException { try { this.inputHandler = inputHandlerFactory.getInputHandler(inputFile); } catch (IOException e) { logger.warn("File " + inputFile + " could not be found."); throw e; } try { this.outputHandler = outputHandlerFactory.getOutputHandler(outputFile, queryHandlerFactory); } catch (FileNotFoundException e) { logger.error("File " + outputFile + "could not be created or written to.", e); throw e; } this.day = dayToSet; } @Override public void run() { logger.info("Start processing " + inputHandler.getInputFile()); outputHandler.setThreadNumber(day); try { inputHandler.parseTo(outputHandler, day); logger.info("Done processing " + inputHandler.getInputFile() + " to " + outputHandler.getOutputFile() + "."); } catch (IOException e) { logger.error("Error processing " + inputHandler.getInputFile() + " to " + outputHandler.getOutputFile() + ".", e); } } }
Wikidata/QueryAnalysis
src/main/java/general/ParseOneDayWorker.java
Java
apache-2.0
2,688
package cryodex.modules.armada.gui; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import cryodex.CryodexController; import cryodex.modules.Match; import cryodex.modules.Match.GameResult; import cryodex.modules.RoundPanel; import cryodex.modules.armada.ArmadaTournament; import cryodex.widget.ComponentUtils; import cryodex.widget.ConfirmationTextField; public class ArmadaRoundPanel extends RoundPanel { private static final long serialVersionUID = 1L; public ArmadaRoundPanel(ArmadaTournament t, List<Match> matches) { super(t, matches); } @Override public void buildGamePanel(JPanel panel, GridBagConstraints gbc, cryodex.modules.RoundPanel.GamePanel gamePanel) { GamePanel gp = (GamePanel) gamePanel; gbc.gridy++; gbc.gridx = 0; gbc.gridwidth = 2; gbc.anchor = GridBagConstraints.EAST; panel.add(gp.getPlayerTitle(), gbc); gbc.gridx = 2; gbc.gridwidth = 3; gbc.fill = GridBagConstraints.BOTH; panel.add(gp.getResultCombo(), gbc); if (gp.getMatch().getPlayer2() != null) { gbc.gridy++; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.NONE; gbc.gridx = 1; panel.add(gp.getPlayer1ScoreLabel(), gbc); gbc.gridx = 2; panel.add(gp.getPlayer1ScoreField(), gbc); gbc.gridx = 3; gbc.anchor = GridBagConstraints.WEST; panel.add(gp.getPlayer1ScoreField().getIndicator(), gbc); gbc.gridy++; gbc.gridwidth = 1; gbc.anchor = GridBagConstraints.EAST; gbc.gridx = 1; panel.add(gp.getPlayer2ScoreLabel(), gbc); gbc.gridx = 2; panel.add(gp.getPlayer2ScoreField(), gbc); gbc.gridx = 3; gbc.anchor = GridBagConstraints.WEST; panel.add(gp.getPlayer2ScoreField().getIndicator(), gbc); } } @Override public List<cryodex.modules.RoundPanel.GamePanel> getGamePanels(List<Match> matches) { List<RoundPanel.GamePanel> gamePanels = new ArrayList<RoundPanel.GamePanel>(); int counter = 0; for (Match match : matches) { counter++; GamePanel gp = new GamePanel(counter, match); gamePanels.add(gp); } return gamePanels; } private class GamePanel extends RoundPanel.GamePanel { private JComboBox<String> resultsCombo; private ConfirmationTextField player1Score; private ConfirmationTextField player2Score; private JLabel player1ScoreLabel; private JLabel player2ScoreLabel; public GamePanel(int tableNumber, Match match) { super(tableNumber, match); } private JLabel getPlayer1ScoreLabel() { if (player1ScoreLabel == null) { player1ScoreLabel = new JLabel(); } return player1ScoreLabel; } private JLabel getPlayer2ScoreLabel() { if (player2ScoreLabel == null) { player2ScoreLabel = new JLabel(); } return player2ScoreLabel; } private String[] getComboValues() { if (getMatch().getPlayer2() == null) { String[] values = { "Select a result", "BYE" }; return values; } else { String generic = "Select a result"; String[] values = { generic, "WIN - " + getMatch().getPlayer1().getName(), "WIN - " + getMatch().getPlayer2().getName(), getMatch().getPlayer1().getName() + " conceded", getMatch().getPlayer2().getName() + " conceded" }; return values; } } private JComboBox<String> getResultCombo() { if (resultsCombo == null) { resultsCombo = new JComboBox<String>(getComboValues()); resultsCombo.setRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; @Override public void paint(Graphics g) { setForeground(Color.BLACK); super.paint(g); } }); resultsCombo.addActionListener(GamePanel.this); } return resultsCombo; } public ConfirmationTextField getPlayer1ScoreField() { if (player1Score == null) { player1Score = new ConfirmationTextField(); player1Score.addFocusListener(GamePanel.this); ComponentUtils.forceSize(player1Score, 50, 25); } return player1Score; } public ConfirmationTextField getPlayer2ScoreField() { if (player2Score == null) { player2Score = new ConfirmationTextField(); player2Score.addFocusListener(GamePanel.this); ComponentUtils.forceSize(player2Score, 50, 25); } return player2Score; } public void setMatchPointsFromGUI() { // Set player 1 points Integer player1points = null; try { player1points = Integer.valueOf(player1Score.getText()); } catch (Exception e) { } getMatch().setPlayer1PointsDestroyed(player1points); // Set player 2 points Integer player2points = null; try { player2points = Integer.valueOf(player2Score.getText()); } catch (Exception e) { } getMatch().setPlayer2PointsDestroyed(player2points); } public void setMatchResultFromGUI() { switch (getResultCombo().getSelectedIndex()) { case 0: getMatch().setGame1Result(null); getMatch().setConcede(false); break; case 1: if (getMatch().isBye() == false) { getMatch().setGame1Result(GameResult.PLAYER_1_WINS); } getMatch().setConcede(false); break; case 2: getMatch().setGame1Result(GameResult.PLAYER_2_WINS); getMatch().setConcede(false); break; case 3: getMatch().setGame1Result(GameResult.PLAYER_2_WINS); getMatch().setConcede(true); break; case 4: getMatch().setGame1Result(GameResult.PLAYER_1_WINS); getMatch().setConcede(true); break; default: break; } } public void setGUIFromMatch() { if (getTournament().isMatchComplete(getMatch())) { if (getMatch().isBye()) { getResultCombo().setSelectedIndex(1); } else { if (getMatch().isConcede()) { if (getMatch().getWinner(1) == getMatch().getPlayer1()) { getResultCombo().setSelectedIndex(4); } else if (getMatch().getWinner(1) == getMatch().getPlayer2()) { getResultCombo().setSelectedIndex(3); } } else { if (getMatch().getWinner(1) == getMatch().getPlayer1()) { getResultCombo().setSelectedIndex(1); } else if (getMatch().getWinner(1) == getMatch().getPlayer2()) { getResultCombo().setSelectedIndex(2); } } } } if (getMatch().getPlayer2() != null) { if (getMatch().getPlayer1Points() != null) { getPlayer1ScoreField().setText(String.valueOf(getMatch().getPlayer1Points())); } if (getMatch().getPlayer2Points() != null) { getPlayer2ScoreField().setText(String.valueOf(getMatch().getPlayer2Points())); } } updateGUI(); } public void updateGUI() { String titleText = null; boolean showKillPoints = CryodexController.getOptions().isShowKillPoints(); boolean hideCompletedMatches = CryodexController.getOptions().isHideCompleted(); boolean visible = hideCompletedMatches == false || getTournament().isMatchComplete(getMatch()) == false; getPlayer1ScoreLabel().setVisible(visible && showKillPoints); getPlayer1ScoreField().setVisible(visible && showKillPoints); getPlayer2ScoreLabel().setVisible(visible && showKillPoints); getPlayer2ScoreField().setVisible(visible && showKillPoints); getPlayerTitle().setVisible(visible); getResultCombo().setVisible(visible); if (getMatch().getPlayer2() == null) { titleText = getMatch().getPlayer1().getName() + " has a BYE"; } else { titleText = getMatch().getPlayer1().getName() + " VS " + getMatch().getPlayer2().getName(); if (getMatch().isDuplicate()) { titleText = "(Duplicate)" + titleText; } if (CryodexController.getOptions().isShowTableNumbers()) { titleText = getTableNumber() + ": " + titleText; } getPlayer1ScoreLabel().setText(getMatch().getPlayer1().getName() + " score"); getPlayer2ScoreLabel().setText(getMatch().getPlayer2().getName() + " score"); } getPlayerTitle().setText(titleText); getResultCombo().setEnabled(true); } @Override public void setResultsCombo() { // No Function } @Override public void addToFocusPolicy(Vector<Component> order) { if (getMatch().getPlayer2() != null) { order.add(getPlayer1ScoreField()); order.add(getPlayer2ScoreField()); } } } }
Killerardvark/CryodexSource
src/main/java/cryodex/modules/armada/gui/ArmadaRoundPanel.java
Java
apache-2.0
10,494
/* * 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.util.Map; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.dynamodbv2.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteRequestMarshaller { private static final MarshallingInfo<Map> KEY_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Key").build(); private static final DeleteRequestMarshaller instance = new DeleteRequestMarshaller(); public static DeleteRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DeleteRequest deleteRequest, ProtocolMarshaller protocolMarshaller) { if (deleteRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteRequest.getKey(), KEY_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/transform/DeleteRequestMarshaller.java
Java
apache-2.0
1,937
package ru.job4j.tracker; import java.util.function.Consumer; /** * Реализовать события на внутренних классах. [#15201] * Интерфейс UserAction, в котором определены методы, общие для всех событий. * * @author imoskovtsev */ public interface UserAction { /** * Выполняем действие. * * @param input система ввода * @param tracker трекер задач */ void execute(Input input, ITracker tracker, Consumer<String> output); /** * Описание действия. * * @return String */ String info(); }
ilya-moskovtsev/imoskovtsev
intern/chapter_002_oop/src/main/java/ru/job4j/tracker/UserAction.java
Java
apache-2.0
695
package com.github.liaochong.ratel.tools.core.validator; import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.function.Supplier; /** * @author liaochong * @version V1.0 */ class Operations { /** * boolean通用操作 * * @param data 操作数据 * @param condition 条件操作 * @param operation 操作 * @param <E> 数据类型 * @param <T> 返回的异常类型 */ static <E, T extends RuntimeException> void booleanOperation(E data, Function<E, Boolean> condition, Supplier<T> operation) { if (condition.apply(data)) { throw operation.get(); } } /** * boolean通用操作 * * @param condition 条件操作 * @param operation 操作 * @param <T> 返回的异常类型 */ static <T extends RuntimeException> void booleanOperation(BooleanSupplier condition, Supplier<T> operation) { if (condition.getAsBoolean()) { throw operation.get(); } } }
liaochong/ratel-tools
ratel-tools-core/src/main/java/com/github/liaochong/ratel/tools/core/validator/Operations.java
Java
apache-2.0
1,058
package com.ctao.qhb; /** * Created by A Miracle on 2017/8/17. */ public class Statistics { public static final String OPEN_HONGBAO = "OPEN_HONGBAO"; // 拆红包 /** 事件统计*/ public static void event(String event) { } }
A-Miracle/QiangHongBao
app/src/main/java/com/ctao/qhb/Statistics.java
Java
apache-2.0
250
package com.cattong.weibo.impl.sina; import com.cattong.commons.http.auth.Authorization; import com.cattong.commons.oauth.config.OAuthConfigBase; public class SinaOAuthConfig extends OAuthConfigBase { private static final long serialVersionUID = -4059369499822415321L; public SinaOAuthConfig() { this.setAuthVersion(Authorization.AUTH_VERSION_OAUTH_2); this.setConsumerKey("834484950");//YiBo微博客户端 this.setConsumerSecret("ff6bb46717f98d7d360459abd0a654f9"); this.setCallbackUrl("http://www.yibo.me/authorize/getAccessToken.do"); // this.setConsumerKey("2849184197");//ipad // this.setConsumerSecret("7338acf99a00412983f255767c7643d0"); // this.setCallbackUrl("https://api.weibo.com/oauth2/default.html"); this.setRequestTokenUrl("https://api.weibo.com/oauth2/authorize"); this.setAuthorizeUrl("https://api.weibo.com/oauth2/authorize"); this.setAccessTokenUrl("https://api.weibo.com/oauth2/access_token"); } }
Terry-L/YiBo
YiBoLibrary/src/com/cattong/weibo/impl/sina/SinaOAuthConfig.java
Java
apache-2.0
948
package com.feelinko.feelinko.data.retrofitInterfaces; import com.feelinko.feelinko.data.model.Auth; import retrofit2.http.Body; import retrofit2.http.POST; import rx.Observable; /** * This interface will enable us to create the retrofit rest adaptor to authenticate the user. * * @version 1.0 */ public interface AuthApi { /** * The method to authenticate the user using his facebook account. * We will send the user's facebook access token and we will receive the user's server token and refresh token. * * @param req the request object containing the facebook access token * @return an rx Observable with the response object containing the response from the server * @see Auth.Request * @see Auth.Response */ @POST("facebook_login") Observable<Auth.Response> login(@Body Auth.Request req); }
miloch91/feelinko
app/src/main/java/com/feelinko/feelinko/data/retrofitInterfaces/AuthApi.java
Java
apache-2.0
853
package com.orctom.rmq; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; abstract class AbstractStore { private static final String ROOT_DIR = ".data"; private final Logger logger = LoggerFactory.getLogger(getClass()); String getPath(String id, String name) { String path = ROOT_DIR + File.separator + id + File.separator + name; logger.trace("Path for storage: {}", path); ensureDataDirExist(path); return path; } protected void ensureDataDirExist(String path) { File dataDir = new File(path).getParentFile(); if (dataDir.exists()) { return; } boolean created = dataDir.mkdirs(); logger.trace("Ensuring data dir existence, created: {}", created); } private String getDataDirPath(String id) { return ROOT_DIR + File.separator + id + File.separator; } }
orctom/rmq
src/main/java/com/orctom/rmq/AbstractStore.java
Java
apache-2.0
851
/** * The java robotium client, could be called by jython with * (change the charcode on windows cmd first with "chcp 437") * jython -Dpython.path=C:\jylib\android-2.3.3.jar;C:\jylib\robotium-client.jar;C:\jylib\robotium-solo.jar;C:\jylib\robotium-common.jar */ package com.jayway.android.robotium.remotesolo; import java.lang.reflect.Method; import java.util.ArrayList; import com.jayway.android.robotium.remotesolo.proxy.ClientProxyCreator; import com.jayway.android.robotium.solo.Solo; import junit.framework.Assert; import android.app.Activity; import android.app.Instrumentation.ActivityMonitor; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.ScrollView; import android.widget.SlidingDrawer; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.ToggleButton; public class RemoteSolo implements ISolo { private DeviceClientManager devices; /** * RemoteSolo constructor * * @param activityClass * the class of an Activity that will be instrumented */ public RemoteSolo(Class<?> activityClass) { devices = new DeviceClientManager(); devices.setTargetClass(activityClass); } public RemoteSolo(String activityClassName) { devices = new DeviceClientManager(); devices.setTargetClass(activityClassName); } /** * Adds devices for initiating connections. This can be called multiple * times if there are several devices/emulators used for remote testing. * * @param deviceSerialAZ * `~```` device/emulator serial number. The serial number can be * obtained using adb tool(adb devices). * @param pcPort * Port number on PC for establishing connection * @param devicePort * Port number on device/emulator for establishing connection */ public void addDevice(String deviceSerial, int pcPort, int devicePort) { devices.addDevice(deviceSerial, pcPort, devicePort); } public void addDevice(String deviceSerial, int pcPort) { devices.addDevice(deviceSerial, pcPort); } /** * Attempt to connect devices to corresponding server */ public void connect() { devices.connectAll(); } /** * Attempt to disconnect devices to corresponding server */ public void disconnect() throws RemoteException { devices.disconnectAllDevices(); } public void assertCurrentActivity(String message, String name) { try { invokeMethod("assertCurrentActivity", new Class<?>[] { String.class, String.class }, new Object[] { message, name }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } @SuppressWarnings("unchecked") public void assertCurrentActivity(String message, Class expectedClass) { try { invokeMethod("assertCurrentActivity", new Class<?>[] { String.class, Class.class }, new Object[] { message, expectedClass }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void assertCurrentActivity(String message, String name, boolean isNewInstance) { try { invokeMethod("assertCurrentActivity", new Class<?>[] { String.class, String.class, boolean.class }, new Object[] { message, name, isNewInstance }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } @SuppressWarnings("unchecked") public void assertCurrentActivity(String message, Class expectedClass, boolean isNewInstance) { try { invokeMethod("assertCurrentActivity", new Class<?>[] { String.class, Class.class, boolean.class }, new Object[] { message, expectedClass, isNewInstance }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void assertLowMemory() { try { invokeMethod("assertLowMemory", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clearEditText(int index) { try { invokeMethod("clearEditText", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } @SuppressWarnings("unchecked") public ArrayList<TextView> clickInList(int line) { try { return (ArrayList<TextView>) invokeMethod("clickInList", new Class<?>[] { int.class }, new Object[] { line }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<TextView> clickInList(int line, int listIndex) { try { return (ArrayList<TextView>) invokeMethod("clickInList", new Class<?>[] { int.class, int.class }, new Object[] { line, listIndex }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public void clickLongOnScreen(float x, float y) { try { invokeMethod("clickLongOnScreen", new Class<?>[] { float.class, float.class }, new Object[] { x, y }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickLongOnText(String text) { try { invokeMethod("clickLongOnText", new Class<?>[] { String.class }, new Object[] { text }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickLongOnText(String text, int match) { try { invokeMethod("clickLongOnText", new Class<?>[] { String.class, int.class }, new Object[] { text, match }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickLongOnTextAndPress(String text, int index) { try { invokeMethod("clickLongOnTextAndPress", new Class<?>[] { String.class, int.class }, new Object[] { text, index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickLongOnView(View view) { try { invokeMethod("clickLongOnView", new Class<?>[] { View.class }, new Object[] { view }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnButton(String name) { try { invokeMethod("clickOnButton", new Class<?>[] { String.class }, new Object[] { name }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnButton(int index) { try { invokeMethod("clickOnButton", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnCheckBox(int index) { try { invokeMethod("clickOnCheckBox", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnEditText(int index) { try { invokeMethod("clickOnEditText", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnImage(int index) { try { invokeMethod("clickOnImage", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnImageButton(int index) { try { invokeMethod("clickOnImageButton", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnMenuItem(String text) { try { invokeMethod("clickOnMenuItem", new Class<?>[] { String.class }, new Object[] { text }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnRadioButton(int index) { try { invokeMethod("clickOnRadioButton", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnScreen(float x, float y) { try { invokeMethod("clickOnScreen", new Class<?>[] { float.class, float.class }, new Object[] { x, y }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnText(String text) { try { invokeMethod("clickOnText", new Class<?>[] { String.class }, new Object[] { text }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnText(String text, int match) { try { invokeMethod("clickOnText", new Class<?>[] { String.class, int.class }, new Object[] { text, match }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnToggleButton(String name) { try { invokeMethod("clickOnToggleButton", new Class<?>[] { String.class }, new Object[] { name }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnView(View view) { try { invokeMethod("clickOnView", new Class<?>[] { View.class }, new Object[] { view }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void drag(float fromX, float toX, float fromY, float toY, int stepCount) { try { invokeMethod("drag", new Class<?>[] { float.class, float.class, float.class, float.class, int.class }, new Object[] { fromX, toX, fromY, toY, stepCount }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void enterText(int index, String text) { try { invokeMethod("enterText", new Class<?>[] { int.class, String.class }, new Object[] { index, text }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } @SuppressWarnings("unchecked") public ArrayList<Activity> getAllOpenedActivities() { try { return (ArrayList<Activity>) invokeMethod("getAllOpenedActivities", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public Button getButton(int index) { try { return (Button) invokeMethod("getButton", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public int getCurrenButtonsCount() { try { return Integer.parseInt(invokeMethod("getCurrenButtonsCount", new Class<?>[] {}).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return -1; } public Activity getCurrentActivity() { try { return (Activity) invokeMethod("getCurrentActivity", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<Button> getCurrentButtons() { try { return (ArrayList<Button>) invokeMethod("getCurrentButtons", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<CheckBox> getCurrentCheckBoxes() { try { return (ArrayList<CheckBox>) invokeMethod("getCurrentCheckBoxes", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<EditText> getCurrentEditTexts() { try { return (ArrayList<EditText>) invokeMethod("getCurrentEditTexts", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<GridView> getCurrentGridViews() { try { return (ArrayList<GridView>) invokeMethod("getCurrentGridViews", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<ImageButton> getCurrentImageButtons() { try { return (ArrayList<ImageButton>) invokeMethod( "getCurrentImageButtons", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<ImageView> getCurrentImageViews() { try { return (ArrayList<ImageView>) invokeMethod("getCurrentImageViews", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<ListView> getCurrentListViews() { try { return (ArrayList<ListView>) invokeMethod("getCurrentListViews", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<RadioButton> getCurrentRadioButtons() { try { return (ArrayList<RadioButton>) invokeMethod( "getCurrentRadioButtons", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<ScrollView> getCurrentScrollViews() { try { return (ArrayList<ScrollView>) invokeMethod( "getCurrentScrollViews", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<Spinner> getCurrentSpinners() { try { return (ArrayList<Spinner>) invokeMethod("getCurrentSpinners", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<TextView> getCurrentTextViews(View parent) { try { return (ArrayList<TextView>) invokeMethod("getCurrentTextViews", new Class<?>[] { View.class }, new Object[] { parent }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<ToggleButton> getCurrentToggleButtons() { try { return (ArrayList<ToggleButton>) invokeMethod( "getCurrentToggleButtons", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public EditText getEditText(int index) { try { return (EditText) invokeMethod("getEditText", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public View getTopParent(View view) { try { return (View) invokeMethod("getTopParent", new Class<?>[] { View.class }, new Object[] { view }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } @SuppressWarnings("unchecked") public ArrayList<View> getViews() { try { return (ArrayList<View>) invokeMethod("getViews", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public void goBack() { try { invokeMethod("goBack", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void goBackToActivity(String name) { try { invokeMethod("goBackToActivity", new Class<?>[] { String.class }, new Object[] { name }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public boolean isCheckBoxChecked(int index) { try { return Boolean.parseBoolean(invokeMethod("isCheckBoxChecked", new Class<?>[] { int.class }, new Object[] { index }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean isRadioButtonChecked(int index) { try { return Boolean.parseBoolean(invokeMethod("isRadioButtonChecked", new Class<?>[] { int.class }, new Object[] { index }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public void pressMenuItem(int index) { try { invokeMethod("pressMenuItem", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void pressSpinnerItem(int spinnerIndex, int itemIndex) { try { invokeMethod("pressSpinnerItem", new Class<?>[] { int.class, int.class }, new Object[] { spinnerIndex, itemIndex }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public boolean scrollDown() { try { return Boolean.parseBoolean(invokeMethod("scrollDown", new Class<?>[] {}).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean scrollDownList(int listIndex) { try { return Boolean.parseBoolean(invokeMethod("scrollDownList", new Class<?>[] { int.class }, new Object[] { listIndex }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public void scrollToSide(int side) { try { invokeMethod("scrollToSide", new Class<?>[] { int.class }, new Object[] { side }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public boolean scrollUp() { try { return Boolean.parseBoolean(invokeMethod("scrollUp", new Class<?>[] {}).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean scrollUpList(int listIndex) { try { return Boolean.parseBoolean(invokeMethod("scrollUpList", new Class<?>[] { int.class }, new Object[] { listIndex }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchButton(String search) { try { return Boolean.parseBoolean(invokeMethod("searchButton", new Class<?>[] { String.class }, new Object[] { search }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchButton(String search, int matches) { try { return Boolean.parseBoolean(invokeMethod("searchButton", new Class<?>[] { String.class, int.class }, new Object[] { search, matches }).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchEditText(String search) { try { return Boolean.parseBoolean(invokeMethod("searchEditText", new Class<?>[] { String.class }, new Object[] { search }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchText(String search) { try { return Boolean.parseBoolean(invokeMethod("searchText", new Class<?>[] { String.class }, new Object[] { search }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchText(String search, int matches) { try { return Boolean.parseBoolean(invokeMethod("searchText", new Class<?>[] { String.class, int.class }, new Object[] { search, matches }).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchText(String search, int matches, boolean scroll) { try { return Boolean.parseBoolean(invokeMethod("searchText", new Class<?>[] { String.class, int.class, boolean.class }, new Object[] { search, matches, scroll }).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchToggleButton(String search) { try { return Boolean.parseBoolean(invokeMethod("searchToggleButton", new Class<?>[] { String.class }, new Object[] { search }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean searchToggleButton(String search, int matches) { try { return Boolean.parseBoolean(invokeMethod("searchToggleButton", new Class<?>[] { String.class, int.class }, new Object[] { search, matches }).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public void sendKey(int key) { try { invokeMethod("sendKey", new Class<?>[] { int.class }, new Object[] { key }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void setActivityOrientation(int orientation) { try { invokeMethod("setActivityOrientation", new Class<?>[] { int.class }, new Object[] { orientation }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void sleep(int time) { try { invokeMethod("sleep", new Class<?>[] { int.class }, new Object[] { time }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public boolean waitForActivity(String name, int timeout) { try { return Boolean.parseBoolean(invokeMethod("waitForActivity", new Class<?>[] { String.class, int.class }, new Object[] { name, timeout }).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean waitForDialogToClose(long timeout) { try { return Boolean.parseBoolean(invokeMethod("waitForDialogToClose", new Class<?>[] { long.class }, new Object[] { timeout }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean waitForText(String text) { try { return Boolean.parseBoolean(invokeMethod("waitForText", new Class<?>[] { String.class }, new Object[] { text }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean waitForText(String text, int matches, long timeout) { try { return Boolean.parseBoolean(invokeMethod("waitForText", new Class<?>[] { String.class, int.class, long.class }, new Object[] { text, matches, timeout }).toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public boolean waitForText(String text, int matches, long timeout, boolean scroll) { try { return Boolean .parseBoolean(invokeMethod( "waitForText", new Class<?>[] { String.class, int.class, long.class, boolean.class }, new Object[] { text, matches, timeout, scroll }) .toString()); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return false; } public void finalize() throws Throwable { try { invokeMethod("finalize", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickLongOnText(String text, int match, boolean scroll) { try { invokeMethod("clickLongOnText", new Class<?>[] { String.class, int.class, boolean.class }, new Object[] { text, match, scroll }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnMenuItem(String text, boolean subMenu) { try { invokeMethod("clickOnMenuItem", new Class<?>[] { String.class, boolean.class }, new Object[] { text, subMenu }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public void clickOnText(String text, int matches, boolean scroll) { try { invokeMethod("clickOnText", new Class<?>[] { String.class, int.class, boolean.class }, new Object[] { text, matches, scroll }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } public ImageView getImage(int index) { try { return (ImageView) invokeMethod("getImage", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public ImageButton getImageButton(int index) { try { return (ImageButton) invokeMethod("getImageButton", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public String getString(int resId) { try { return (String) invokeMethod("getString", new Class<?>[] { int.class }, new Object[] { resId }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public TextView getText(int index) { try { return (TextView) invokeMethod("getText", new Class<?>[] { int.class }, new Object[] { index }); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } return null; } public void restartActivity() { try { invokeMethod("restartActivity", new Class<?>[] {}); } catch (Exception e) { Assert.fail(e.getCause().getMessage()); } } private Object invokeMethod(String methodToExecute, Class<?>[] argumentTypes, Object... arguments) throws Exception { // create Proxy object for solo class when needed Solo mSoloProxy = (Solo) ClientProxyCreator.createProxy(Solo.class); // the invoked method Method receivedMethod = mSoloProxy.getClass().getMethod( methodToExecute, argumentTypes); // invoke, should bubble up to the ClientInvocationHandler return receivedMethod.invoke(mSoloProxy, arguments); } // TODO need to implement them public boolean isSpinnerTextSelected(String text) { return false; } public boolean isSpinnerTextSelected(int index, String text) { return false; } public boolean isTextChecked(String text) { return false; } public boolean isCheckBoxChecked(String text) { return false; } public ActivityMonitor getActivityMonitor() { // TODO Auto-generated method stub return null; } public ArrayList<View> getViews(View parent) { // TODO Auto-generated method stub return null; } public void clearEditText(EditText editText) { // TODO Auto-generated method stub } public <T extends View> boolean waitForView(Class<T> viewClass) { // TODO Auto-generated method stub return false; } public <T extends View> boolean waitForView(Class<T> viewClass, int minimumNumberOfMatches, int timeout) { // TODO Auto-generated method stub return false; } public <T extends View> boolean waitForView(Class<T> viewClass, int minimumNumberOfMatches, int timeout, boolean scroll) { // TODO Auto-generated method stub return false; } public boolean searchButton(String text, boolean onlyVisible) { // TODO Auto-generated method stub return false; } public boolean searchButton(String text, int minimumNumberOfMatches, boolean onlyVisible) { // TODO Auto-generated method stub return false; } public boolean searchText(String text, boolean onlyVisible) { // TODO Auto-generated method stub return false; } public boolean searchText(String text, int minimumNumberOfMatches, boolean scroll, boolean onlyVisible) { // TODO Auto-generated method stub return false; } public void assertMemoryNotLow() { // TODO Auto-generated method stub } public void clickLongOnScreen(float x, float y, int time) { // TODO Auto-generated method stub } public void pressMenuItem(int index, int itemsPerRow) { // TODO Auto-generated method stub } public void clickLongOnView(View view, int time) { // TODO Auto-generated method stub } public void clickLongOnText(String text, int match, int time) { // TODO Auto-generated method stub } public ArrayList<TextView> clickLongInList(int line) { // TODO Auto-generated method stub return null; } public ArrayList<TextView> clickLongInList(int line, int index) { // TODO Auto-generated method stub return null; } public ArrayList<TextView> clickLongInList(int line, int index, int time) { // TODO Auto-generated method stub return null; } public void setDatePicker(int index, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub } public void setDatePicker(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub } public void setTimePicker(int index, int hour, int minute) { // TODO Auto-generated method stub } public void setTimePicker(TimePicker timePicker, int hour, int minute) { // TODO Auto-generated method stub } public void setProgressBar(int index, int progress) { // TODO Auto-generated method stub } public void setProgressBar(ProgressBar progressBar, int progress) { // TODO Auto-generated method stub } public void setSlidingDrawer(int index, int status) { // TODO Auto-generated method stub } public void setSlidingDrawer(SlidingDrawer slidingDrawer, int status) { // TODO Auto-generated method stub } public void enterText(EditText editText, String text) { // TODO Auto-generated method stub } public TextView getText(String text) { // TODO Auto-generated method stub return null; } public Button getButton(String text) { // TODO Auto-generated method stub return null; } public EditText getEditText(String text) { // TODO Auto-generated method stub return null; } public View getView(int id) { // TODO Auto-generated method stub return null; } public ArrayList<View> getCurrentViews() { // TODO Auto-generated method stub return null; } public ArrayList<DatePicker> getCurrentDatePickers() { // TODO Auto-generated method stub return null; } public ArrayList<TimePicker> getCurrentTimePickers() { // TODO Auto-generated method stub return null; } public ArrayList<SlidingDrawer> getCurrentSlidingDrawers() { // TODO Auto-generated method stub return null; } public ArrayList<ProgressBar> getCurrentProgressBars() { // TODO Auto-generated method stub return null; } public boolean isRadioButtonChecked(String text) { // TODO Auto-generated method stub return false; } public boolean isToggleButtonChecked(String text) { // TODO Auto-generated method stub return false; } public boolean isToggleButtonChecked(int index) { // TODO Auto-generated method stub return false; } }
cyberelf/robotium-remote
robotium-client/src/main/java/com/jayway/android/robotium/remotesolo/RemoteSolo.java
Java
apache-2.0
29,935
package com.vmware.reviewboard.domain; public class ReviewRequestDraftResponse extends BaseResponseEntity { public ReviewRequestDraft draft; }
vmware/workflowTools
serviceApis/src/main/java/com/vmware/reviewboard/domain/ReviewRequestDraftResponse.java
Java
apache-2.0
149
package com.htisolutions.poolref.services; import com.htisolutions.poolref.entities.UserDao; import java.util.ArrayList; import java.util.Comparator; import com.htisolutions.poolref.entities.User; import com.htisolutions.poolref.viewModels.LeaderBoardEntryViewModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.*; import java.util.*; @Service public class UserService { private UserDao userDao; @Autowired UserService(UserDao userDao) { this.userDao = userDao; } public Iterable<User> getUsers(){ Iterable<User> users = userDao.findAll(); List<User> listOfUsers = new ArrayList<>(); User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); for(User user : users){ if (!user.getId().equals(currentUser.getId())) { listOfUsers.add(user); } } Comparator<User> userComparator = Comparator .comparing((User e)-> e.getSurname().toUpperCase()); Collections.sort(listOfUsers, userComparator); listOfUsers.add(0, currentUser); return listOfUsers; } public Iterable<String> getUserNicknames(){ Iterable<User> users = getUsers(); ArrayList<String> userNicknameList= new ArrayList<String>(); for (User u : users) { userNicknameList.add(u.getNickname()); } Iterable<String> userNicknames = userNicknameList; return userNicknames; } public User getUserById(long id) { User user = userDao.findOne(id); return user; } public User getUserByNickname(String name) { User user = userDao.findByNickname(name); return user; } }
HTiSolutions/poolref
src/main/java/com/htisolutions/poolref/services/UserService.java
Java
apache-2.0
1,859
/* * Copyright 2009 Kantega AS * * 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 no.kantega.publishing.admin.administration.action; import no.kantega.commons.client.util.RequestParameters; import no.kantega.commons.exception.InvalidParameterException; import no.kantega.commons.exception.NotAuthorizedException; import no.kantega.commons.exception.SystemException; import no.kantega.publishing.api.cache.SiteCache; import no.kantega.publishing.api.content.ContentStatus; import no.kantega.publishing.api.model.Site; import no.kantega.publishing.common.cache.TemplateConfigurationCache; import no.kantega.publishing.common.data.*; import no.kantega.publishing.common.data.enums.AssociationType; import no.kantega.publishing.common.data.enums.ContentType; import no.kantega.publishing.common.exception.MissingTemplateException; import no.kantega.publishing.common.exception.RootExistsException; import no.kantega.publishing.common.service.ContentManagementService; import no.kantega.publishing.common.util.database.SQLHelper; import no.kantega.publishing.common.util.database.dbConnectionFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import org.springframework.web.servlet.view.RedirectView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; public class CreateRootAction extends AbstractController { private SiteCache siteCache; protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { RequestParameters param = new RequestParameters(request, "utf-8"); int siteId = param.getInt("siteId"); createRootPage(siteId, request); return new ModelAndView(new RedirectView("ListSites.action")); } public void createRootPage(int siteId, HttpServletRequest request) throws SQLException, RootExistsException, MissingTemplateException, SystemException, NotAuthorizedException { ContentManagementService aksessService = new ContentManagementService(request); Site site = siteCache.getSiteById(siteId); if (site == null) { throw new InvalidParameterException("siteId"); } Content content = new Content(); content.setAlias(site.getAlias()); content.setTitle(site.getName()); content.setType(ContentType.PAGE); // Legg til hovedknytning Association association = new Association(); association.setContentId(-1); association.setParentAssociationId(0); association.setSiteId(siteId); association.setAssociationtype(AssociationType.DEFAULT_POSTING_FOR_SITE); association.setCategory(new AssociationCategory(0)); content.addAssociation(association); // Hvis basen ikke inneholder noen sider for siten, kan hjemmesida opprettes try(Connection c = dbConnectionFactory.getConnection()) { ResultSet rs = SQLHelper.getResultSet(c, "select * from associations where SiteId = " + site.getId()); if (rs.next()) { throw new RootExistsException("Hjemmesiden er allerede opprettet"); } rs = SQLHelper.getResultSet(c, "select * from content where Alias = '" + site.getAlias() + "'"); if (rs.next()) { throw new RootExistsException("Finnes allerede en side med dette aliaset"); } // Find homepage String frontpageUrl = "/WEB-INF/jsp" + site.getAlias() +"index.jsp"; DisplayTemplate displayTemplate = null; // If a site has specified a display template id, try to look this template TemplateConfiguration templateConfiguration = TemplateConfigurationCache.getInstance().getTemplateConfiguration(); if (site.getPublicId() != null && site.getPublicId().length() > 0) { for(DisplayTemplate template : templateConfiguration.getDisplayTemplates()) { if(template.getPublicId().equalsIgnoreCase(site.getDisplayTemplateId())) { displayTemplate = template; break; } } } // No template specified or found, try to look a template in the folder specified by the alias if (displayTemplate == null) { for(DisplayTemplate template : templateConfiguration.getDisplayTemplates()) { if(frontpageUrl.equals(template.getView())) { displayTemplate = template; break; } } } if (displayTemplate == null) { throw new MissingTemplateException("Can't find display template for site " + site.getAlias()); } content.setDisplayTemplateId(displayTemplate.getId()); content.setContentTemplateId(displayTemplate.getContentTemplate().getId()); if (displayTemplate.getMetaDataTemplate() != null) { content.setMetaDataTemplateId(displayTemplate.getMetaDataTemplate().getId()); } aksessService.checkInContent(content, ContentStatus.PUBLISHED); } } public void setSiteCache(SiteCache siteCache) { this.siteCache = siteCache; } }
kantega/Flyt-cms
modules/core/src/main/java/no/kantega/publishing/admin/administration/action/CreateRootAction.java
Java
apache-2.0
6,011
package com.qiniu.pili.droid.shortvideo.demo.utils; import com.qiniu.pili.droid.shortvideo.PLCameraSetting; import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting; public class RecordSettings { public static final int DEFAULT_MIN_RECORD_DURATION = 3 * 1000; public static final int DEFAULT_MAX_RECORD_DURATION = 10 * 1000; public static final String[] PREVIEW_SIZE_RATIO_TIPS_ARRAY = { "4:3", "16:9" }; public static final String[] PREVIEW_SIZE_LEVEL_TIPS_ARRAY = { "120P", "240P", "360P", "480P", "720P", "960P", "1080P", "1200P", }; public static final String[] ENCODING_SIZE_LEVEL_TIPS_ARRAY = { "120x120", "160x120", "240x240", "320x240", "424x240", "352x352", "640x352", "360x360", "480x360", "640x360", "480x480", "640x480", "848x480", "544x544", "720x544", "720x720", "960x720", "1280x720", "1088x1088", "1440x1088" }; public static final String[] ENCODING_BITRATE_LEVEL_TIPS_ARRAY = { "500Kbps", "800Kbps", "1000Kbps", "1200Kbps", "1600Kbps", "2000Kbps", "2500Kbps", "4000Kbps", "8000Kbps" }; public static final PLCameraSetting.CAMERA_PREVIEW_SIZE_RATIO[] PREVIEW_SIZE_RATIO_ARRAY = { PLCameraSetting.CAMERA_PREVIEW_SIZE_RATIO.RATIO_4_3, PLCameraSetting.CAMERA_PREVIEW_SIZE_RATIO.RATIO_16_9 }; public static final PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL[] PREVIEW_SIZE_LEVEL_ARRAY = { PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_120P, PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_240P, PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_360P, PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_480P, PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_720P, PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_960P, PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_1080P, PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_1200P, }; public static final PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL[] ENCODING_SIZE_LEVEL_ARRAY = { /** * 120x120 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_120P_1, /** * 160x120 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_120P_2, /** * 240x240 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_240P_1, /** * 320x240 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_240P_2, /** * 424x240 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_240P_3, /** * 352x352 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_352P_1, /** * 640x352 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_352P_2, /** * 360x360 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_360P_1, /** * 480x360 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_360P_2, /** * 640x360 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_360P_3, /** * 480x480 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_1, /** * 640x480 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_2, /** * 848x480 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_3, /** * 544x544 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_544P_1, /** * 720x544 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_544P_2, /** * 720x720 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_720P_1, /** * 960x720 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_720P_2, /** * 1280x720 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_720P_3, /** * 1088x1088 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_1088P_1, /** * 1440x1088 */ PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_1088P_2, }; public static final int[] ENCODING_BITRATE_LEVEL_ARRAY = { 500 * 1000, 800 * 1000, 1000 * 1000, 1200 * 1000, 1600 * 1000, 2000 * 1000, 2500 * 1000, 4000 * 1000, 8000 * 1000, }; }
geeklok/PLDroidShortVideo
PLDroidShortVideoDemo/app/src/main/java/com/qiniu/pili/droid/shortvideo/demo/utils/RecordSettings.java
Java
apache-2.0
5,801
/** * Project Name:fox-enterprisemgmt * File Name:UserMgmtClient.java * Package Name:com.hpe.foxcloud.composite.enterprisemgmt.clients * Date:Oct 5, 201611:25:55 AM * Copyright (c) 2016, chenxj All Rights Reserved. */ package com.yy.cloud.api.admin.clients; import com.yy.cloud.common.data.GeneralContent; import com.yy.cloud.common.data.GeneralContentResult; import com.yy.cloud.common.data.GeneralPagingResult; import com.yy.cloud.common.data.GeneralResult; import com.yy.cloud.common.data.dto.sysbase.PasswordProfile; import com.yy.cloud.common.data.dto.sysbase.UserProfile; import com.yy.cloud.common.data.otd.sysbase.CommonKeyValue; import com.yy.cloud.common.data.otd.usermgmt.OrganizationItem; import com.yy.cloud.common.data.otd.usermgmt.UserDetailsItem; import com.yy.cloud.common.data.otd.usermgmt.UserItem; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; /** * ClassName:UserMgmtClient <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: Oct 5, 2016 11:25:55 AM <br/> * * @author chenxj * @see * @since JDK 1.8 */ @FeignClient("usermgmt") // @FeignClient(url = "http://localhost:9101", name = "usermgmt") public interface UserMgmtClient { /** * updateEnterpriseStatus:更新企业状态. <br/> * * @param _tenantId * @param _status * @return */ @RequestMapping(method = RequestMethod.PUT, value = "/tenant/{_tenantId}/status/{_status}") @ResponseBody GeneralResult updateEnterpriseStatus(@PathVariable("_tenantId") String _tenantId, @PathVariable("_status") Byte _status); /** * updateEnterpriseAdminStatus:更新企业管理员状态. <br/> * * @param _adminId * @param _status * @return */ @RequestMapping(method = RequestMethod.PUT, value = "/tenant/admin/{_adminId}/status/{_status}") @ResponseBody GeneralPagingResult<GeneralContent> updateEnterpriseAdminStatus(@PathVariable("_adminId") String _adminId, @PathVariable("_status") Byte _status); /** * deleteEnterpriseAdmin:删除某个企业管理员. <br/> * * @param _adminId * @return */ @RequestMapping(method = RequestMethod.DELETE, value = "/tenant/admin/{_adminId}") @ResponseBody GeneralPagingResult<GeneralContent> deleteEnterpriseAdmin(@PathVariable("_adminId") String _adminId); /** * 审批中心-待审批列表,根据部门ID 获取用户,返回结果中,key 为userid,value 为用户名 * * @param departmentId * @return */ @RequestMapping(value = "/authsec/approval/department/{departmentId}/users", method = RequestMethod.GET) GeneralContentResult<List<CommonKeyValue>> getUsersByDepartment(@PathVariable("departmentId") String departmentId); /** * 审批中心-待审批列表,获取审批人列表,key 为userid,value 为用户名 * * @return */ @RequestMapping(value = "/authsec/approval/approvers/department/{departmentId}", method = RequestMethod.GET) GeneralContentResult<List<CommonKeyValue>> getApprovers(@PathVariable("departmentId") String departmentId); /** * 获取当前用户所属机构下的所有企业 * * @return key 为企业id,value 为企业名称 */ @RequestMapping(method = RequestMethod.GET, value = "/authsec/enterprise/currentuser") GeneralContentResult<List<CommonKeyValue>> getCurrentUserEnterprises(); /** * 获取当前用户所属企业下的所有部门 * * @return key 为部门id,value 为部门名称 */ @RequestMapping(method = RequestMethod.GET, value = "/authsec/department/currentuser") GeneralContentResult<List<CommonKeyValue>> getCurrentUserDepartments(); /** * 根据企业获取部门 * * @return */ @RequestMapping(method = RequestMethod.GET, value = "/authsec/organization/enterprise/{enterprise_id}", produces = MediaType.APPLICATION_JSON_VALUE) GeneralContentResult<List<OrganizationItem>> getOrganizationsByEnterpriseId( @PathVariable("enterprise_id") String enterprise_id); @RequestMapping(value = "/authsec/user/{user_id}/password", method = RequestMethod.PUT) public GeneralResult resetPassword(@PathVariable("user_id") String _userId); /** * 获取所有部门信息 * * @return */ @RequestMapping(value = "/noauth/organizations", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "用户中心-获取部门") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ") }) public GeneralContentResult<List<OrganizationItem>> findAllorgnazation(); /** * 创建账号 * * @param _userProfile * @return */ @RequestMapping(value = "/noauth/user/account", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "用户中心-账户管理,ADM创建账号,本地") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ") }) public GeneralContentResult<String> createAdmUser(@RequestBody UserProfile _userProfile); @RequestMapping(value = "/authsec/user/current", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "用户中心-账户管理,查询当前账户") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ") }) public GeneralContentResult<UserDetailsItem> findCurrentUser(); @RequestMapping(value = "/authsec/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) GeneralPagingResult<List<UserItem>> findUsers(@RequestParam(value = "status", required = false) Byte _status, @RequestParam(value = "page") Integer _page, @RequestParam(value = "size") Integer _size); @RequestMapping(value = "/authsec/user/{user_id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) GeneralContentResult<UserDetailsItem> findUserById(@PathVariable("user_id") String _userId); @RequestMapping(value = "/authsec/users/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "用户中心-账户管理,通过用户名模糊查询账户") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ")}) public GeneralPagingResult<List<UserDetailsItem>> findUsersByUserName( @RequestParam(value = "userName", required = false) String _userName, @RequestParam(value = "page") Integer _page, @RequestParam(value = "size") Integer _size); @RequestMapping(value = "/authsec/user/{user_id}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "用户中心-账户管理,编辑账号,本地") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ") }) public GeneralResult modifyUser( @PathVariable("user_id") String _userId, @RequestBody UserProfile _userProfile); @RequestMapping(value = "/authsec/adm/user/{user_id}", method = RequestMethod.DELETE) @ApiOperation(value = "用户中心-账号管理,删除") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ") }) public GeneralResult deleteUser( @PathVariable("user_id") String _userId); @RequestMapping(value = "/authsec/users/organization/{organization_id}/page/{page}/size/{size}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "用户中心-账户管理,获得属于指定机构下所有用户") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ") }) public GeneralPagingResult<List<UserDetailsItem>> getMembersInOrganization( @PathVariable("organization_id") String _organizationId, @PathVariable(value = "page") Integer _page, @PathVariable(value = "size") Integer _size); @RequestMapping(value = "/authsec/user/password/modify", method = RequestMethod.PUT) @ApiOperation(value = "用户中心-账户管理,修改当前密码") @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", name = "Authorization", dataType = "String", required = true, value = "Token", defaultValue = "bearer ") }) public GeneralResult modifyPassword( @RequestBody PasswordProfile _passwordProfile); }
YY-ORG/yycloud
yy-api/yy-admin-api/src/main/java/com/yy/cloud/api/admin/clients/UserMgmtClient.java
Java
apache-2.0
9,844
/* * Copyright (C) 2014 Square, 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.squareup.okhttp.internal.huc; import com.squareup.okhttp.Handshake; import com.squareup.okhttp.Headers; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.OkUrlFactory; import com.squareup.okhttp.Protocol; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseBody; import com.squareup.okhttp.internal.SslContextBuilder; import com.squareup.okhttp.internal.Util; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.CacheResponse; import java.net.HttpURLConnection; import java.net.SecureCacheResponse; import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.Principal; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import okio.Buffer; import okio.BufferedSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for {@link JavaApiConverter}. */ public class JavaApiConverterTest { // $ openssl req -x509 -nodes -days 36500 -subj '/CN=localhost' -config ./cert.cnf \ // -newkey rsa:512 -out cert.pem private static final X509Certificate LOCAL_CERT = certificate("" + "-----BEGIN CERTIFICATE-----\n" + "MIIBWDCCAQKgAwIBAgIJANS1EtICX2AZMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV\n" + "BAMTCWxvY2FsaG9zdDAgFw0xMjAxMDIxOTA4NThaGA8yMTExMTIwOTE5MDg1OFow\n" + "FDESMBAGA1UEAxMJbG9jYWxob3N0MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPpt\n" + "atK8r4/hf4hSIs0os/BSlQLbRBaK9AfBReM4QdAklcQqe6CHsStKfI8pp0zs7Ptg\n" + "PmMdpbttL0O7mUboBC8CAwEAAaM1MDMwMQYDVR0RBCowKIIVbG9jYWxob3N0Lmxv\n" + "Y2FsZG9tYWlugglsb2NhbGhvc3SHBH8AAAEwDQYJKoZIhvcNAQEFBQADQQD0ntfL\n" + "DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G\n" + "X8YKH52fnHsCrhSD\n" + "-----END CERTIFICATE-----"); // openssl req -x509 -nodes -days 36500 -subj '/CN=*.0.0.1' -newkey rsa:512 -out cert.pem private static final X509Certificate SERVER_CERT = certificate("" + "-----BEGIN CERTIFICATE-----\n" + "MIIBkjCCATygAwIBAgIJAMdemqOwd/BEMA0GCSqGSIb3DQEBBQUAMBIxEDAOBgNV\n" + "BAMUByouMC4wLjEwIBcNMTAxMjIwMTY0NDI1WhgPMjExMDExMjYxNjQ0MjVaMBIx\n" + "EDAOBgNVBAMUByouMC4wLjEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAqY8c9Qrt\n" + "YPWCvb7lclI+aDHM6fgbJcHsS9Zg8nUOh5dWrS7AgeA25wyaokFl4plBbbHQe2j+\n" + "cCjsRiJIcQo9HwIDAQABo3MwcTAdBgNVHQ4EFgQUJ436TZPJvwCBKklZZqIvt1Yt\n" + "JjEwQgYDVR0jBDswOYAUJ436TZPJvwCBKklZZqIvt1YtJjGhFqQUMBIxEDAOBgNV\n" + "BAMUByouMC4wLjGCCQDHXpqjsHfwRDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB\n" + "BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt\n" + "fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n" + "-----END CERTIFICATE-----"); private static final SSLContext sslContext = SslContextBuilder.localhost(); private static final HostnameVerifier NULL_HOSTNAME_VERIFIER = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; private MockWebServer server; private OkHttpClient client; private HttpURLConnection connection; @Before public void setUp() throws Exception { server = new MockWebServer(); client = new OkHttpClient(); } @After public void tearDown() throws Exception { if (connection != null) { connection.disconnect(); } server.shutdown(); } @Test public void createOkResponse_fromOkHttpUrlConnection() throws Exception { testCreateOkResponseInternal(new OkHttpURLConnectionFactory(client), false /* isSecure */); } @Test public void createOkResponse_fromJavaHttpUrlConnection() throws Exception { testCreateOkResponseInternal(new JavaHttpURLConnectionFactory(), false /* isSecure */); } @Test public void createOkResponse_fromOkHttpsUrlConnection() throws Exception { testCreateOkResponseInternal(new OkHttpURLConnectionFactory(client), true /* isSecure */); } @Test public void createOkResponse_fromJavaHttpsUrlConnection() throws Exception { testCreateOkResponseInternal(new JavaHttpURLConnectionFactory(), true /* isSecure */); } private void testCreateOkResponseInternal(HttpURLConnectionFactory httpUrlConnectionFactory, boolean isSecure) throws Exception { String statusLine = "HTTP/1.1 200 Fantastic"; String body = "Nothing happens"; final URL serverUrl; MockResponse mockResponse = new MockResponse() .setStatus(statusLine) .addHeader("xyzzy", "baz") .setBody(body); if (isSecure) { serverUrl = configureHttpsServer( mockResponse); assertEquals("https", serverUrl.getProtocol()); } else { serverUrl = configureServer( mockResponse); assertEquals("http", serverUrl.getProtocol()); } connection = httpUrlConnectionFactory.open(serverUrl); if (isSecure) { HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection; httpsUrlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); httpsUrlConnection.setHostnameVerifier(NULL_HOSTNAME_VERIFIER); } connection.setRequestProperty("snake", "bird"); connection.connect(); Response response = JavaApiConverter.createOkResponse(serverUrl.toURI(), connection); // Check the response.request() Request request = response.request(); assertEquals(isSecure, request.isHttps()); assertEquals(serverUrl.toURI(), request.uri()); assertNull(request.body()); Headers okRequestHeaders = request.headers(); // In Java the request headers are unavailable for a connected HttpURLConnection. assertEquals(0, okRequestHeaders.size()); assertEquals("GET", request.method()); // Check the response assertEquals(Protocol.HTTP_1_1, response.protocol()); assertEquals(200, response.code()); assertEquals("Fantastic", response.message()); Headers okResponseHeaders = response.headers(); assertEquals("baz", okResponseHeaders.get("xyzzy")); if (isSecure) { Handshake handshake = response.handshake(); assertNotNull(handshake); HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection; assertNotNullAndEquals(httpsURLConnection.getCipherSuite(), handshake.cipherSuite()); assertEquals(httpsURLConnection.getLocalPrincipal(), handshake.localPrincipal()); assertNotNullAndEquals(httpsURLConnection.getPeerPrincipal(), handshake.peerPrincipal()); assertNotNull(httpsURLConnection.getServerCertificates()); assertEquals(Arrays.asList(httpsURLConnection.getServerCertificates()), handshake.peerCertificates()); assertNull(httpsURLConnection.getLocalCertificates()); } else { assertNull(response.handshake()); } assertEquals(body, response.body().string()); } @Test public void createOkResponse_fromCacheResponse() throws Exception { final String statusLine = "HTTP/1.1 200 Fantastic"; URI uri = new URI("http://foo/bar"); Request request = new Request.Builder().url(uri.toURL()).build(); CacheResponse cacheResponse = new CacheResponse() { @Override public Map<String, List<String>> getHeaders() throws IOException { Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put(null, Collections.singletonList(statusLine)); headers.put("xyzzy", Arrays.asList("bar", "baz")); return headers; } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream("HelloWorld".getBytes(StandardCharsets.UTF_8)); } }; Response response = JavaApiConverter.createOkResponse(request, cacheResponse); assertSame(request, response.request()); assertEquals(Protocol.HTTP_1_1, response.protocol()); assertEquals(200, response.code()); assertEquals("Fantastic", response.message()); Headers okResponseHeaders = response.headers(); assertEquals("baz", okResponseHeaders.get("xyzzy")); assertEquals("HelloWorld", response.body().string()); assertNull(response.handshake()); } @Test public void createOkResponse_fromSecureCacheResponse() throws Exception { final String statusLine = "HTTP/1.1 200 Fantastic"; final Principal localPrincipal = LOCAL_CERT.getSubjectX500Principal(); final List<Certificate> localCertificates = Arrays.<Certificate>asList(LOCAL_CERT); final Principal serverPrincipal = SERVER_CERT.getSubjectX500Principal(); final List<Certificate> serverCertificates = Arrays.<Certificate>asList(SERVER_CERT); URI uri = new URI("https://foo/bar"); Request request = new Request.Builder().url(uri.toURL()).build(); SecureCacheResponse cacheResponse = new SecureCacheResponse() { @Override public Map<String, List<String>> getHeaders() throws IOException { Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put(null, Collections.singletonList(statusLine)); headers.put("xyzzy", Arrays.asList("bar", "baz")); return headers; } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream("HelloWorld".getBytes(StandardCharsets.UTF_8)); } @Override public String getCipherSuite() { return "SuperSecure"; } @Override public List<Certificate> getLocalCertificateChain() { return localCertificates; } @Override public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException { return serverCertificates; } @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { return serverPrincipal; } @Override public Principal getLocalPrincipal() { return localPrincipal; } }; Response response = JavaApiConverter.createOkResponse(request, cacheResponse); assertSame(request, response.request()); assertEquals(Protocol.HTTP_1_1, response.protocol()); assertEquals(200, response.code()); assertEquals("Fantastic", response.message()); Headers okResponseHeaders = response.headers(); assertEquals("baz", okResponseHeaders.get("xyzzy")); assertEquals("HelloWorld", response.body().string()); Handshake handshake = response.handshake(); assertNotNull(handshake); assertNotNullAndEquals("SuperSecure", handshake.cipherSuite()); assertEquals(localPrincipal, handshake.localPrincipal()); assertEquals(serverPrincipal, handshake.peerPrincipal()); assertEquals(serverCertificates, handshake.peerCertificates()); assertEquals(localCertificates, handshake.localCertificates()); } @Test public void createOkRequest_nullRequestHeaders() throws Exception { URI uri = new URI("http://foo/bar"); Map<String,List<String>> javaRequestHeaders = null; Request request = JavaApiConverter.createOkRequest(uri, "POST", javaRequestHeaders); assertFalse(request.isHttps()); assertEquals(uri, request.uri()); assertNull(request.body()); Headers okRequestHeaders = request.headers(); assertEquals(0, okRequestHeaders.size()); assertEquals("POST", request.method()); } @Test public void createOkRequest_nonNullRequestHeaders() throws Exception { URI uri = new URI("https://foo/bar"); Map<String,List<String>> javaRequestHeaders = new HashMap<String, List<String>>(); javaRequestHeaders.put("Foo", Arrays.asList("Bar")); Request request = JavaApiConverter.createOkRequest(uri, "POST", javaRequestHeaders); assertTrue(request.isHttps()); assertEquals(uri, request.uri()); assertNull(request.body()); Headers okRequestHeaders = request.headers(); assertEquals(1, okRequestHeaders.size()); assertEquals("Bar", okRequestHeaders.get("Foo")); assertEquals("POST", request.method()); } // Older versions of OkHttp would store the "request line" as a header with a // null key. To support the Android usecase where an old version of OkHttp uses // a newer, Android-bundled, version of HttpResponseCache the null key must be // explicitly ignored. @Test public void createOkRequest_nullRequestHeaderKey() throws Exception { URI uri = new URI("https://foo/bar"); Map<String,List<String>> javaRequestHeaders = new HashMap<String, List<String>>(); javaRequestHeaders.put(null, Arrays.asList("GET / HTTP 1.1")); javaRequestHeaders.put("Foo", Arrays.asList("Bar")); Request request = JavaApiConverter.createOkRequest(uri, "POST", javaRequestHeaders); assertTrue(request.isHttps()); assertEquals(uri, request.uri()); assertNull(request.body()); Headers okRequestHeaders = request.headers(); assertEquals(1, okRequestHeaders.size()); assertEquals("Bar", okRequestHeaders.get("Foo")); assertEquals("POST", request.method()); } @Test public void createJavaUrlConnection_requestChangesForbidden() throws Exception { Response okResponse = createArbitraryOkResponse(); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); // Check an arbitrary (not complete) set of methods that can be used to modify the // request. try { httpUrlConnection.setRequestProperty("key", "value"); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.setFixedLengthStreamingMode(1234); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.setRequestMethod("PUT"); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.getHeaderFields().put("key", Collections.singletonList("value")); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.getOutputStream(); fail(); } catch (UnsupportedOperationException expected) { } } @Test public void createJavaUrlConnection_connectionChangesForbidden() throws Exception { Response okResponse = createArbitraryOkResponse(); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); try { httpUrlConnection.connect(); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.disconnect(); fail(); } catch (UnsupportedOperationException expected) { } } @Test public void createJavaUrlConnection_responseChangesForbidden() throws Exception { Response okResponse = createArbitraryOkResponse(); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); // Check an arbitrary (not complete) set of methods that can be used to access the response // body. try { httpUrlConnection.getInputStream(); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.getContent(); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.setFixedLengthStreamingMode(1234); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.setRequestMethod("PUT"); fail(); } catch (UnsupportedOperationException expected) { } try { httpUrlConnection.getHeaderFields().put("key", Collections.singletonList("value")); fail(); } catch (UnsupportedOperationException expected) { } } @Test public void createJavaUrlConnection_responseHeadersOk() throws Exception { ResponseBody responseBody = createResponseBody("BodyText"); Response okResponse = new Response.Builder() .request(createArbitraryOkRequest()) .protocol(Protocol.HTTP_1_1) .code(200) .message("Fantastic") .addHeader("A", "c") .addHeader("B", "d") .addHeader("A", "e") .addHeader("Content-Length", Long.toString(responseBody.contentLength())) .body(responseBody) .build(); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); assertEquals(200, httpUrlConnection.getResponseCode()); assertEquals("Fantastic", httpUrlConnection.getResponseMessage()); assertEquals(responseBody.contentLength(), httpUrlConnection.getContentLength()); // Check retrieval by string key. assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(null)); assertEquals("e", httpUrlConnection.getHeaderField("A")); // The RI and OkHttp supports case-insensitive matching for this method. assertEquals("e", httpUrlConnection.getHeaderField("a")); // Check retrieval using a Map. Map<String, List<String>> responseHeaders = httpUrlConnection.getHeaderFields(); assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), responseHeaders.get(null)); assertEquals(newSet("c", "e"), newSet(responseHeaders.get("A"))); // OkHttp supports case-insensitive matching here. The RI does not. assertEquals(newSet("c", "e"), newSet(responseHeaders.get("a"))); // Check the Map iterator contains the expected mappings. assertHeadersContainsMapping(responseHeaders, null, "HTTP/1.1 200 Fantastic"); assertHeadersContainsMapping(responseHeaders, "A", "c", "e"); assertHeadersContainsMapping(responseHeaders, "B", "d"); // Check immutability of the headers Map. try { responseHeaders.put("N", Arrays.asList("o")); fail("Modified an unmodifiable view."); } catch (UnsupportedOperationException expected) { } try { responseHeaders.get("A").add("f"); fail("Modified an unmodifiable view."); } catch (UnsupportedOperationException expected) { } // Check retrieval of headers by index. assertEquals(null, httpUrlConnection.getHeaderFieldKey(0)); assertEquals("HTTP/1.1 200 Fantastic", httpUrlConnection.getHeaderField(0)); // After header zero there may be additional entries provided at the beginning or end by the // implementation. It's probably important that the relative ordering of the headers is // preserved, particularly if there are multiple value for the same key. int i = 1; while (!httpUrlConnection.getHeaderFieldKey(i).equals("A")) { i++; } // Check the ordering of the headers set by app code. assertResponseHeaderAtIndex(httpUrlConnection, i++, "A", "c"); assertResponseHeaderAtIndex(httpUrlConnection, i++, "B", "d"); assertResponseHeaderAtIndex(httpUrlConnection, i++, "A", "e"); // There may be some additional headers provided by the implementation. while (httpUrlConnection.getHeaderField(i) != null) { assertNotNull(httpUrlConnection.getHeaderFieldKey(i)); i++; } // Confirm the correct behavior when the index is out-of-range. assertNull(httpUrlConnection.getHeaderFieldKey(i)); } private static void assertResponseHeaderAtIndex(HttpURLConnection httpUrlConnection, int headerIndex, String expectedKey, String expectedValue) { assertEquals(expectedKey, httpUrlConnection.getHeaderFieldKey(headerIndex)); assertEquals(expectedValue, httpUrlConnection.getHeaderField(headerIndex)); } private void assertHeadersContainsMapping(Map<String, List<String>> headers, String expectedKey, String... expectedValues) { assertTrue(headers.containsKey(expectedKey)); assertEquals(newSet(expectedValues), newSet(headers.get(expectedKey))); } @Test public void createJavaUrlConnection_accessibleRequestInfo_GET() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .get() .build(); Response okResponse = createArbitraryOkResponse(okRequest); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); assertEquals("GET", httpUrlConnection.getRequestMethod()); assertTrue(httpUrlConnection.getDoInput()); assertFalse(httpUrlConnection.getDoOutput()); } @Test public void createJavaUrlConnection_accessibleRequestInfo_POST() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .post(createRequestBody("PostBody")) .build(); Response okResponse = createArbitraryOkResponse(okRequest); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); assertEquals("POST", httpUrlConnection.getRequestMethod()); assertTrue(httpUrlConnection.getDoInput()); assertTrue(httpUrlConnection.getDoOutput()); } @Test public void createJavaUrlConnection_https_extraHttpsMethods() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .get() .url("https://secure/request") .build(); Handshake handshake = Handshake.get("SecureCipher", Arrays.<Certificate>asList(SERVER_CERT), Arrays.<Certificate>asList(LOCAL_CERT)); Response okResponse = createArbitraryOkResponse(okRequest).newBuilder() .handshake(handshake) .build(); HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) JavaApiConverter.createJavaUrlConnection(okResponse); assertEquals("SecureCipher", httpsUrlConnection.getCipherSuite()); assertEquals(SERVER_CERT.getSubjectX500Principal(), httpsUrlConnection.getPeerPrincipal()); assertArrayEquals(new Certificate[] { LOCAL_CERT }, httpsUrlConnection.getLocalCertificates()); assertArrayEquals(new Certificate[] { SERVER_CERT }, httpsUrlConnection.getServerCertificates()); assertEquals(LOCAL_CERT.getSubjectX500Principal(), httpsUrlConnection.getLocalPrincipal()); } @Test public void createJavaUrlConnection_https_forbiddenFields() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .url("https://secure/request") .build(); Response okResponse = createArbitraryOkResponse(okRequest); HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) JavaApiConverter.createJavaUrlConnection(okResponse); try { httpsUrlConnection.getHostnameVerifier(); fail(); } catch (UnsupportedOperationException expected) { } try { httpsUrlConnection.getSSLSocketFactory(); fail(); } catch (UnsupportedOperationException expected) { } } @Test public void createJavaCacheResponse_httpGet() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .url("http://insecure/request") .get() .build(); Response okResponse = createArbitraryOkResponse(okRequest).newBuilder() .protocol(Protocol.HTTP_1_1) .code(200) .message("Fantastic") .addHeader("key1", "value1_1") .addHeader("key2", "value2") .addHeader("key1", "value1_2") .body(null) .build(); CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse); assertFalse(javaCacheResponse instanceof SecureCacheResponse); Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders(); assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1")); assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null)); assertNull(javaCacheResponse.getBody()); } @Test public void createJavaCacheResponse_httpPost() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .url("http://insecure/request") .post(createRequestBody("RequestBody")) .build(); ResponseBody responseBody = createResponseBody("ResponseBody"); Response okResponse = createArbitraryOkResponse(okRequest).newBuilder() .protocol(Protocol.HTTP_1_1) .code(200) .message("Fantastic") .addHeader("key1", "value1_1") .addHeader("key2", "value2") .addHeader("key1", "value1_2") .body(responseBody) .build(); CacheResponse javaCacheResponse = JavaApiConverter.createJavaCacheResponse(okResponse); assertFalse(javaCacheResponse instanceof SecureCacheResponse); Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders(); assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1")); assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null)); assertEquals("ResponseBody", readAll(javaCacheResponse.getBody())); } @Test public void createJavaCacheResponse_httpsPost() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .url("https://secure/request") .post(createRequestBody("RequestBody") ) .build(); ResponseBody responseBody = createResponseBody("ResponseBody"); Handshake handshake = Handshake.get("SecureCipher", Arrays.<Certificate>asList(SERVER_CERT), Arrays.<Certificate>asList(LOCAL_CERT)); Response okResponse = createArbitraryOkResponse(okRequest).newBuilder() .protocol(Protocol.HTTP_1_1) .code(200) .message("Fantastic") .addHeader("key1", "value1_1") .addHeader("key2", "value2") .addHeader("key1", "value1_2") .body(responseBody) .handshake(handshake) .build(); SecureCacheResponse javaCacheResponse = (SecureCacheResponse) JavaApiConverter.createJavaCacheResponse(okResponse); Map<String, List<String>> javaHeaders = javaCacheResponse.getHeaders(); assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1")); assertEquals(Arrays.asList("HTTP/1.1 200 Fantastic"), javaHeaders.get(null)); assertEquals("ResponseBody", readAll(javaCacheResponse.getBody())); assertEquals(handshake.cipherSuite(), javaCacheResponse.getCipherSuite()); assertEquals(handshake.localCertificates(), javaCacheResponse.getLocalCertificateChain()); assertEquals(handshake.peerCertificates(), javaCacheResponse.getServerCertificateChain()); assertEquals(handshake.localPrincipal(), javaCacheResponse.getLocalPrincipal()); assertEquals(handshake.peerPrincipal(), javaCacheResponse.getPeerPrincipal()); } @Test public void extractJavaHeaders() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() .addHeader("key1", "value1_1") .addHeader("key2", "value2") .addHeader("key1", "value1_2") .build(); Map<String, List<String>> javaHeaders = JavaApiConverter.extractJavaHeaders(okRequest); assertEquals(Arrays.asList("value1_1", "value1_2"), javaHeaders.get("key1")); assertEquals(Arrays.asList("value2"), javaHeaders.get("key2")); } @Test public void extractOkHeaders() { Map<String, List<String>> javaResponseHeaders = new HashMap<String, List<String>>(); javaResponseHeaders.put(null, Arrays.asList("StatusLine")); javaResponseHeaders.put("key1", Arrays.asList("value1_1", "value1_2")); javaResponseHeaders.put("key2", Arrays.asList("value2")); Headers okHeaders = JavaApiConverter.extractOkHeaders(javaResponseHeaders); assertEquals(3, okHeaders.size()); // null entry should be stripped out assertEquals(Arrays.asList("value1_1", "value1_2"), okHeaders.values("key1")); assertEquals(Arrays.asList("value2"), okHeaders.values("key2")); } @Test public void extractStatusLine() { Map<String, List<String>> javaResponseHeaders = new HashMap<String, List<String>>(); javaResponseHeaders.put(null, Arrays.asList("StatusLine")); javaResponseHeaders.put("key1", Arrays.asList("value1_1", "value1_2")); javaResponseHeaders.put("key2", Arrays.asList("value2")); assertEquals("StatusLine", JavaApiConverter.extractStatusLine(javaResponseHeaders)); assertNull(JavaApiConverter.extractStatusLine(Collections.<String, List<String>>emptyMap())); } private URL configureServer(MockResponse mockResponse) throws Exception { server.enqueue(mockResponse); server.play(); return server.getUrl("/"); } private URL configureHttpsServer(MockResponse mockResponse) throws Exception { server.useHttps(sslContext.getSocketFactory(), false /* tunnelProxy */); server.enqueue(mockResponse); server.play(); return server.getUrl("/"); } private static <T> void assertNotNullAndEquals(T expected, T actual) { assertNotNull(actual); assertEquals(expected, actual); } private interface HttpURLConnectionFactory { public HttpURLConnection open(URL serverUrl) throws IOException; } private static class OkHttpURLConnectionFactory implements HttpURLConnectionFactory { protected final OkHttpClient client; private OkHttpURLConnectionFactory(OkHttpClient client) { this.client = client; } @Override public HttpURLConnection open(URL serverUrl) { return new OkUrlFactory(client).open(serverUrl); } } private static class JavaHttpURLConnectionFactory implements HttpURLConnectionFactory { @Override public HttpURLConnection open(URL serverUrl) throws IOException { return (HttpURLConnection) serverUrl.openConnection(); } } private static X509Certificate certificate(String certificate) { try { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate( new ByteArrayInputStream(certificate.getBytes(Util.UTF_8))); } catch (CertificateException e) { fail(); return null; } } private static <T> Set<T> newSet(T... elements) { return newSet(Arrays.asList(elements)); } private static <T> Set<T> newSet(List<T> elements) { return new LinkedHashSet<T>(elements); } private static Request createArbitraryOkRequest() { return new Request.Builder().url("http://arbitrary/url").build(); } private static Response createArbitraryOkResponse(Request request) { return new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(200) .message("Arbitrary") .build(); } private static Response createArbitraryOkResponse() { return createArbitraryOkResponse(createArbitraryOkRequest()); } private static RequestBody createRequestBody(String bodyText) { return RequestBody.create(MediaType.parse("text/plain"), bodyText); } private static ResponseBody createResponseBody(String bodyText) { final Buffer source = new Buffer().writeUtf8(bodyText); final long contentLength = source.size(); return new ResponseBody() { @Override public MediaType contentType() { return MediaType.parse("text/plain; charset=utf-8"); } @Override public long contentLength() { return contentLength; } @Override public BufferedSource source() { return source; } }; } private String readAll(InputStream in) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int value; while ((value = in.read()) != -1) { buffer.write(value); } in.close(); return buffer.toString("UTF-8"); } }
rohanpatel2602/okhttp
okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java
Java
apache-2.0
32,726
/* * Copyright 2013 Harald Wellmann * * 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.ops4j.pax.cdi.openwebbeans.impl.context; import java.util.concurrent.ConcurrentHashMap; import javax.enterprise.context.spi.Contextual; import org.apache.webbeans.context.AbstractContext; import org.apache.webbeans.context.creational.BeanInstanceBag; import org.ops4j.pax.cdi.api.ServiceScoped; /** * @author Harald Wellmann * */ public class ServiceContext extends AbstractContext { private static final long serialVersionUID = 1L; public ServiceContext() { super(ServiceScoped.class); } @Override public void setComponentInstanceMap() { componentInstanceMap = new ConcurrentHashMap<Contextual<?>, BeanInstanceBag<?>>(); } }
jharting/org.ops4j.pax.cdi
pax-cdi-openwebbeans/src/main/java/org/ops4j/pax/cdi/openwebbeans/impl/context/ServiceContext.java
Java
apache-2.0
1,291
package com.silverpop.engage.response; /** * Created by Lindsay Thurmond on 1/7/15. */ public class UpdateRecipientResponse { private static final String TAG = UpdateRecipientResponse.class.getName(); private EngageResponseXML responseXml; public UpdateRecipientResponse(String response) { this(new EngageResponseXML(response)); } public UpdateRecipientResponse(EngageResponseXML engageResponseXml) { responseXml = engageResponseXml; } public boolean isSuccess() { boolean isSuccess = responseXml.isSuccess(); return isSuccess; } public String getRecipientId(){ String recipientId = responseXml.getString("envelope.body.result.recipientid"); return recipientId; } }
Silverpop/mobile-connector-sdk-android
engage/src/main/java/com/silverpop/engage/response/UpdateRecipientResponse.java
Java
apache-2.0
763
/* * Copyright 2000-2012 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. */ package com.intellij.codeInsight.template.macro; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.template.*; import com.intellij.ide.actions.CopyReferenceUtil; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Nikolay Matveev */ public abstract class FilePathMacroBase extends Macro { @Override public Result calculateResult(Expression @NotNull [] params, ExpressionContext context) { Project project = context.getProject(); Editor editor = context.getEditor(); if (editor != null) { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file != null) { VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { return calculateResult(virtualFile, project); } } } return null; } @Nullable protected TextResult calculateResult(@NotNull VirtualFile virtualFile, @NotNull Project project) { return new TextResult(virtualFile.getName()); } public static class FileNameWithoutExtensionMacro extends FilePathMacroBase { @Override public String getName() { return "fileNameWithoutExtension"; } @Override public String getPresentableName() { return CodeInsightBundle.message("macro.file.name.without.extension"); } @Override protected TextResult calculateResult(@NotNull VirtualFile virtualFile, @NotNull Project project) { return new TextResult(virtualFile.getNameWithoutExtension()); } } public static class FileNameMacro extends FilePathMacroBase { @Override public String getName() { return "fileName"; } @Override public String getPresentableName() { return CodeInsightBundle.message("macro.file.name"); } @Override protected TextResult calculateResult(@NotNull VirtualFile virtualFile, @NotNull Project project) { return new TextResult(virtualFile.getName()); } } public static class FilePathMacro extends FilePathMacroBase { @Override public String getName() { return "filePath"; } @Override public String getPresentableName() { return "filePath()"; } @Override protected TextResult calculateResult(@NotNull VirtualFile virtualFile, @NotNull Project project) { return new TextResult(FileUtil.toSystemDependentName(virtualFile.getPath())); } } public static class FileRelativePathMacro extends FilePathMacroBase { @Override public String getName() { return "fileRelativePath"; } @Override public String getPresentableName() { return "fileRelativePath()"; } @Override protected TextResult calculateResult(@NotNull VirtualFile virtualFile, @NotNull Project project) { return new TextResult(FileUtil.toSystemDependentName(CopyReferenceUtil.getVirtualFileFqn(virtualFile, project))); } } }
leafclick/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/template/macro/FilePathMacroBase.java
Java
apache-2.0
3,821
package org.smarti18n.messages.v2; import org.junit.Before; import org.junit.Test; import org.smarti18n.api.v1.AngularMessagesApi; import org.smarti18n.api.v1.AngularMessagesApiImpl; import org.smarti18n.api.v1.ProjectsApi; import org.smarti18n.api.v1.ProjectsApiImpl; import org.smarti18n.api.v1.SpringMessagesApi; import org.smarti18n.api.v1.SpringMessagesApiImpl; import org.smarti18n.api.v2.MessagesApi; import org.smarti18n.api.v2.MessagesApiImpl; import org.smarti18n.messages.AbstractIntegrationTest; import org.smarti18n.models.MessageCreateDTO; import org.smarti18n.models.Project; import org.smarti18n.models.SingleMessageUpdateDTO; import org.smarti18n.models.UserCredentials; import org.smarti18n.models.UserCredentialsSupplier; import java.util.Locale; import static org.assertj.core.api.Java6Assertions.assertThat; public class ParentProject2IntegrationTest extends AbstractIntegrationTest { private static final String PARENT_PROJECT_ID = "parent_project_id"; private static final String CHILD_PROJECT_ID = "child_project_id"; private static final String MESSAGE_KEY = "message-key"; private static final String MESSAGE_TRANSLATION = "MESSAGE_TRANSLATION"; private MessagesApi messagesApi; private AngularMessagesApi angularMessagesApi; private SpringMessagesApi springMessagesApi; @Before public void setUp() throws Exception { final ProjectsApi projectsApi = new ProjectsApiImpl(this.restTemplate.getRestTemplate(), this.port, new UserCredentialsSupplier(UserCredentials.TEST)); this.messagesApi = new MessagesApiImpl(this.restTemplate.getRestTemplate(), this.port, new UserCredentialsSupplier(UserCredentials.TEST)); projectsApi.insert(PARENT_PROJECT_ID, null); final Project childProject = projectsApi.insert(CHILD_PROJECT_ID, PARENT_PROJECT_ID); this.angularMessagesApi = new AngularMessagesApiImpl(this.restTemplate.getRestTemplate(), this.port); this.springMessagesApi = new SpringMessagesApiImpl(this.restTemplate.getRestTemplate(), this.port, CHILD_PROJECT_ID, childProject.getSecret()); } @Test public void messagesInParent() { this.messagesApi.create(PARENT_PROJECT_ID, new MessageCreateDTO(MESSAGE_KEY)); this.messagesApi.update(PARENT_PROJECT_ID, MESSAGE_KEY, Locale.GERMAN.toLanguageTag(), new SingleMessageUpdateDTO(MESSAGE_TRANSLATION)); assertThat(this.messagesApi.findOne(CHILD_PROJECT_ID, MESSAGE_KEY)).isNull(); assertThat(this.messagesApi.findAll(CHILD_PROJECT_ID)).isEmpty(); assertThat(angularMessagesApi.getMessages(CHILD_PROJECT_ID, Locale.GERMAN)).containsOnlyKeys(MESSAGE_KEY); assertThat(springMessagesApi.findForSpringMessageSource()).containsKey(MESSAGE_KEY); } }
SmartI18N/SmartI18N
smarti18n/smarti18n-messages/src/test/java/org/smarti18n/messages/v2/ParentProject2IntegrationTest.java
Java
apache-2.0
2,769
package io.jasonsparc.chemistry; import android.view.View; import android.view.ViewGroup; /** * Created by jason on 07/07/2016. */ public interface ViewFactory { View createView(ViewGroup parent); }
jasonsparc/Chemistry
library/src/main/java/io/jasonsparc/chemistry/ViewFactory.java
Java
apache-2.0
205
package utils.cache.unsafeclient; import java.security.cert.CertificateException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.OkHttpClient; public class UnsafeOkHttpClient { public static OkHttpClient getUnsafeOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); OkHttpClient okHttpClient = builder.build(); return okHttpClient; } catch (Exception e) { throw new RuntimeException(e); } } }
heinigger/utils
thirdParty/applibrary/src/main/java/utils/cache/unsafeclient/UnsafeOkHttpClient.java
Java
apache-2.0
2,259
package com.chenql.multitaskdemo; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
chinglimchan/Demo2016
MultiTaskDemo/app/src/test/java/com/chenql/multitaskdemo/ExampleUnitTest.java
Java
apache-2.0
402
package org.simon.pascal.controller; import java.io.IOException; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.simon.pascal.report.ParseHtmlTable1; import org.simon.pascal.util.MyFileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.thymeleaf.context.Context; import org.thymeleaf.spring4.SpringTemplateEngine; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import com.google.gson.Gson; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.codec.Base64.OutputStream; @Controller public class DownloadController { @Autowired private SpringTemplateEngine templateEngine; /* * Download a file from * - inside project, located in resources folder. * - outside project, located in File system somewhere. */ @RequestMapping(value="/download/pdf", method = RequestMethod.GET) public void downloadFile(HttpServletResponse response, HttpServletRequest request) throws IOException, DocumentException { final String nameFile="hello"; String mimeType= "application/pdf"; response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("inline; filename=\"" +nameFile+"\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); byte[] bytes=ParseHtmlTable1.convertHtmlToPdf(getContent(request)); response.setContentLength(bytes.length); response.getOutputStream().write(bytes); } public String getContent(HttpServletRequest request) throws IOException{ final String z025="data:image/png;base64,"+MyFileUtils.generateBase64Image("static/images/z025.png"); final String z026="data:image/png;base64,"+MyFileUtils.generateBase64Image("static/images/z026.png"); final String z033="data:image/png;base64,"+MyFileUtils.generateBase64Image("static/images/z033.png"); final String baseUrl = request.getScheme() + // "http" "://" + // "://" request.getServerName() + // "myhost" ":" + // ":" request.getServerPort() + // "80" request.getContextPath(); // "/myContextPath" or "" if deployed in root context final Locale locale = Locale.forLanguageTag("fr"); final Context context = new Context(locale); context.setVariable("z025", z025); context.setVariable("z026", z026); context.setVariable("z033", z033); context.setVariable("baseUrl", baseUrl); final String content = templateEngine.process("book-origin", context); return content; } }
nsimonin1/allboot
src/main/java/org/simon/pascal/controller/DownloadController.java
Java
apache-2.0
3,564
/* * Copyright 2000-2015 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. */ package com.intellij.ide.script; import com.intellij.openapi.project.Project; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class IdeConsoleScriptBindings { public static final Binding<IDE> IDE = Binding.create("IDE", IDE.class); public static void ensureIdeIsBound(@Nullable Project project, @NotNull IdeScriptEngine engine) { IDE oldIdeBinding = IDE.get(engine); if (oldIdeBinding == null) { IDE.set(engine, new IDE(project, engine)); } } private IdeConsoleScriptBindings() { } public static class Binding<T> { private final String myName; private final Class<T> myClass; private Binding(@NotNull String name, @NotNull Class<T> clazz) { myName = name; myClass = clazz; } public void set(@NotNull IdeScriptEngine engine, T value) { engine.setBinding(myName, value); } public T get(@NotNull IdeScriptEngine engine) { return ObjectUtils.tryCast(engine.getBinding(myName), myClass); } static <T> Binding<T> create(@NotNull String name, @NotNull Class<T> clazz) { return new Binding<>(name, clazz); } } }
leafclick/intellij-community
platform/lang-impl/src/com/intellij/ide/script/IdeConsoleScriptBindings.java
Java
apache-2.0
1,799
package upc.eetac.edu.dsa.ejercicios8_11; /* * Copyright 2014 Ferran Díaz Martínez * * 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. */ public class CuentaAtras2 extends Thread implements Runnable { int conteo; public CuentaAtras2(String ID, int cuenta){ super(ID); conteo = cuenta; } public void run(){ try { for(int i = conteo; i>= 0; i--){ Thread.sleep(1000); System.out.println(i + " " + getName()); } } catch (InterruptedException e) { System.err.println("InterruptedException: " + e); } } }
ferrandiaz/ejercicios8-11
src/main/java/upc/eetac/edu/dsa/ejercicios8_11/CuentaAtras2.java
Java
apache-2.0
1,349
/* * Copyright 2013-2017 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.csharp.lang.psi.impl.source.resolve.handlers; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.ResolveResult; import com.intellij.psi.ResolveState; import com.intellij.util.Processor; import consulo.annotation.access.RequiredReadAction; import consulo.csharp.lang.psi.CSharpNamespaceDeclaration; import consulo.csharp.lang.psi.CSharpReferenceExpression; import consulo.csharp.lang.psi.CSharpUsingNamespaceStatement; import consulo.csharp.lang.psi.impl.source.resolve.CSharpResolveOptions; import consulo.csharp.lang.psi.impl.source.resolve.CSharpResolveResult; import consulo.csharp.lang.psi.impl.source.resolve.StubScopeProcessor; import consulo.dotnet.lang.psi.impl.BaseDotNetNamespaceAsElement; import consulo.dotnet.lang.psi.impl.stub.DotNetNamespaceStubUtil; import consulo.dotnet.psi.DotNetReferenceExpression; import consulo.dotnet.resolve.DotNetGenericExtractor; import consulo.dotnet.resolve.DotNetNamespaceAsElement; import consulo.dotnet.resolve.DotNetPsiSearcher; /** * @author VISTALL * @since 27.07.2015 */ public class QualifiedNamespaceKindProcessor implements KindProcessor { @RequiredReadAction @Override public void process(@Nonnull CSharpResolveOptions options, @Nonnull DotNetGenericExtractor defaultExtractor, @Nullable PsiElement forceQualifierElement, @Nonnull final Processor<ResolveResult> processor) { PsiElement element = options.getElement(); String qName = StringUtil.strip(element.getText(), CSharpReferenceExpression.DEFAULT_REF_FILTER); DotNetNamespaceAsElement namespace = null; PsiElement qualifier = options.getQualifier(); PsiElement parent = element.getParent(); if(!options.isCompletion()) { if(parent instanceof CSharpUsingNamespaceStatement) { DotNetNamespaceAsElement namespaceAsElement = ((CSharpUsingNamespaceStatement) parent).resolve(); if(namespaceAsElement != null) { processor.process(new CSharpResolveResult(namespaceAsElement)); } } else { namespace = DotNetPsiSearcher.getInstance(element.getProject()).findNamespace(qName, element.getResolveScope()); if(namespace != null) { processor.process(new CSharpResolveResult(namespace)); } } } else { processDefaultCompletion(processor, element, qualifier); if(parent instanceof CSharpUsingNamespaceStatement) { PsiElement parentOfStatement = parent.getParent(); if(parentOfStatement instanceof CSharpNamespaceDeclaration) { DotNetReferenceExpression namespaceReference = ((CSharpNamespaceDeclaration) parentOfStatement).getNamespaceReference(); if(namespaceReference != null) { PsiElement resolvedElement = namespaceReference.resolve(); if(resolvedElement instanceof DotNetNamespaceAsElement) { processNamespaceChildren(processor, element, (DotNetNamespaceAsElement) resolvedElement); } } } } } } @RequiredReadAction private void processDefaultCompletion(@Nonnull Processor<ResolveResult> processor, PsiElement element, PsiElement qualifier) { DotNetNamespaceAsElement namespace; String qualifiedText = ""; if(qualifier != null) { qualifiedText = StringUtil.strip(qualifier.getText(), CSharpReferenceExpression.DEFAULT_REF_FILTER); } namespace = DotNetPsiSearcher.getInstance(element.getProject()).findNamespace(qualifiedText, element.getResolveScope()); if(namespace == null) { return; } processNamespaceChildren(processor, element, namespace); } @RequiredReadAction private void processNamespaceChildren(@Nonnull final Processor<ResolveResult> processor, PsiElement element, DotNetNamespaceAsElement namespace) { StubScopeProcessor scopeProcessor = new StubScopeProcessor() { @RequiredReadAction @Override public boolean execute(@Nonnull PsiElement element, ResolveState state) { ProgressManager.checkCanceled(); if(element instanceof DotNetNamespaceAsElement) { if(StringUtil.equals(((DotNetNamespaceAsElement) element).getPresentableQName(), DotNetNamespaceStubUtil.ROOT_FOR_INDEXING)) { return true; } processor.process(new CSharpResolveResult(element)); } return true; } }; ResolveState state = ResolveState.initial(); state = state.put(BaseDotNetNamespaceAsElement.FILTER, DotNetNamespaceAsElement.ChildrenFilter.NONE); state = state.put(BaseDotNetNamespaceAsElement.RESOLVE_SCOPE, element.getResolveScope()); namespace.processDeclarations(scopeProcessor, state, null, element); } }
consulo/consulo-csharp
csharp-psi-impl/src/main/java/consulo/csharp/lang/psi/impl/source/resolve/handlers/QualifiedNamespaceKindProcessor.java
Java
apache-2.0
5,283
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * Copyright (C) 2017-2018 Alexander Fedorov ([email protected]) * * 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.jkiss.dbeaver.debug.core.model; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.core.model.IStreamsProxy; import org.jkiss.dbeaver.debug.core.DebugUtils; import java.util.HashMap; import java.util.Map; public class DatabaseProcess implements IProcess { private final ILaunch launch; private final String name; private final Map<String, String> attributes = new HashMap<>(); private boolean terminated = false; public DatabaseProcess(ILaunch launch, String name) { this.launch = launch; this.name = name; launch.addProcess(this); } @Override public <T> T getAdapter(Class<T> adapter) { return null; } @Override public boolean canTerminate() { return !terminated; } @Override public boolean isTerminated() { return terminated; } @Override public void terminate() throws DebugException { if (!terminated) { terminated = true; launch.removeProcess(this); DebugUtils.fireTerminate(this); } } @Override public String getLabel() { return name; } @Override public ILaunch getLaunch() { return launch; } @Override public IStreamsProxy getStreamsProxy() { return null; } @Override public void setAttribute(String key, String value) { attributes.put(key, value); } @Override public String getAttribute(String key) { return attributes.get(key); } @Override public int getExitValue() throws DebugException { return 0; } }
Sargul/dbeaver
plugins/org.jkiss.dbeaver.debug.core/src/org/jkiss/dbeaver/debug/core/model/DatabaseProcess.java
Java
apache-2.0
2,470
package com.nes.processor.commands.impl; import com.nes.processor.ALU; import com.nes.processor.commands.AbstractCommand; /** * @author Dmitry */ public class Php extends AbstractCommand { @Override public byte execute(ALU alu, byte input) { byte status = alu.getAluFlags().getFlagByte(); status=(byte)(status|0x10); alu.pushToStack(status); return 0; } }
Otaka/mydifferentprojects
nes-java/src/com/nes/processor/commands/impl/Php.java
Java
apache-2.0
425
package com.fxx.library.widget.shape; import android.content.Context; import android.util.AttributeSet; import com.fxx.library.widget.shape.shader.CircleShader; import com.fxx.library.widget.shape.shader.ShaderHelper; /** * 圆形的ImageView */ public class CircularImageView extends ShaderImageView{ private CircleShader shader; public CircularImageView(Context context) { super(context); } public CircularImageView(Context context, AttributeSet attrs) { super(context, attrs); } public CircularImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public ShaderHelper createImageViewHelper() { shader = new CircleShader(); return shader; } public float getBorderRadius() { if(shader != null) { return shader.getBorderRadius(); } return 0; } public void setBorderRadius(final float borderRadius) { if(shader != null) { shader.setBorderRadius(borderRadius); invalidate(); } } }
fangxingxuan/Widget
library/src/main/java/com/fxx/library/widget/shape/CircularImageView.java
Java
apache-2.0
1,118
package de.javapro.netcms.frontend.wicket.pages; import org.apache.wicket.behavior.SimpleAttributeModifier; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.Model; import com.datazuul.commons.cms.backend.NetCMSRepository; import com.datazuul.commons.cms.domain.DomainName; import com.datazuul.commons.cms.domain.Image; import de.javapro.framework.logging.LoggerFacade; import de.javapro.netcms.frontend.wicket.FileResource; import de.javapro.netcms.frontend.wicket.SignInSession; import de.javapro.webapps.wicket.components.imagepopup.ImagePopupLink; /** * @author ralf * */ public class ViewImagePage extends AppBasePage { private static LoggerFacade LOG = LoggerFacade.getInstance(ViewImagePage.class); /** * Default constructor */ public ViewImagePage() { } public ViewImagePage(final Image pImage) { LOG.enterPage(); setDefaultModel(new CompoundPropertyModel(pImage)); // link to original final ImagePopupLink lnkOriginal = new ImagePopupLink("lnkOriginal", new Model(pImage)); add(lnkOriginal); // preview image final DomainName dn = ((SignInSession) getSession()).getDomainName(); final org.apache.wicket.markup.html.image.Image preview = new org.apache.wicket.markup.html.image.Image( "imgPreview", new FileResource(NetCMSRepository.getInstance().getPreviewFile(dn, pImage))); if (pImage.getTitle() != null) { preview.add(new SimpleAttributeModifier("alt", pImage.getTitle())); } lnkOriginal.add(preview); // title add(new Label("lblTitle", pImage.getTitle())); add(new Label("title")); add(new Label("description")); } }
datazuul/com.datazuul.webapps--netcms
src/main/java/de/javapro/netcms/frontend/wicket/pages/ViewImagePage.java
Java
apache-2.0
1,686
package com.sherpasteven.sscte; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.Toast; import com.sherpasteven.sscte.Models.CurrentProfile; import com.sherpasteven.sscte.Models.ISerializer; import com.sherpasteven.sscte.Models.LocalProfileSerializer; import com.sherpasteven.sscte.Models.Model; import com.sherpasteven.sscte.Models.Profile; import com.sherpasteven.sscte.Models.ProfileSynchronizer; import com.sherpasteven.sscte.Models.SearchSingleton; import com.sherpasteven.sscte.Models.SynchronizeSingleton; import com.sherpasteven.sscte.Models.User; import com.sherpasteven.sscte.Views.IView; import com.sherpasteven.sscte.Views.SlidingTabLayout; import com.sherpasteven.sscte.Views.ViewPagerAdapter; public class InventoryActivity extends ActionBarActivity implements IView<Model>{ // Declaring Your View and Variables Toolbar toolbar; ViewPager pager; ViewPagerAdapter adapter; SlidingTabLayout tabs; CharSequence Titles[]={"Inventory","Trades","Friends"}; int Numboftabs = 3; private Profile currentprofile; private User currentuser; private void setLocalProfile(Profile profile) { ISerializer<Profile> serializer = new LocalProfileSerializer(); serializer.Serialize(profile, this); } @Override protected void onPause(){ super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onResume(){ super.onResume(); ProfileSynchronizer profileSynchronizer = SynchronizeSingleton.GetSynchronize(this); profileSynchronizer.SynchronizeProfile(); } /** (not Javadoc) * @see android.app.Activity#onStart() */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ProfileSynchronizer profileSynchronizer = SynchronizeSingleton.GetSynchronize(this); profileSynchronizer.addView(this); setContentView(R.layout.activity_inventory); currentprofile = CurrentProfile.getCurrentProfile().getProfile(this); if (currentprofile == null) { Toast.makeText(getApplicationContext(), "No profile loaded, returning to main page", Toast.LENGTH_LONG).show(); Intent myIntent = new Intent(this, SplashPage.class); startActivity(myIntent); finish(); } else { currentuser = currentprofile.getUser(); } toolbar = (Toolbar) findViewById(R.id.tool_bar); setSupportActionBar(toolbar); /* if (android.os.Build.VERSION.SDK_INT >= 21) { // attempt for conditional run changeToolbarColor(); }*/ // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs. adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs,currentuser); // Assigning ViewPager View and setting the adapter pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(adapter); // Assiging the Sliding Tab Layout View tabs = (SlidingTabLayout) findViewById(R.id.tabs); tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width // Setting Custom Color for the Scroll bar indicator of the Tab View tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.orange_main); } }); // Setting the ViewPager For the SlidingTabsLayout tabs.setViewPager(pager); } /** * Changes the toolbar color on the main page. * @return true */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public boolean changeToolbarColor() { // Creating The Toolbar and setting it as the Toolbar for the activity toolbar = (Toolbar) findViewById(R.id.tool_bar); setSupportActionBar(toolbar); Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark)); return true; } /** * Generates hamburger menu options. * @param menu Menu item to be created. * @return true */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_inventory, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()) ); return true; } /** * OnSelect options for option selected from hamburger menu. * @param item Item selected by user. * @return true */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent1 = new Intent(this, SettingsActivity.class); this.startActivity(intent1); } else if (id == R.id.action_profile) { Intent intent2 = new Intent(this, ProfileActivity.class); this.startActivity(intent2); } return super.onOptionsItemSelected(item); } /** * Updates the activity based on raised condition. * @param model Updates inventory based on model response. */ //@Override //public void Update(Model model) { //} /** * Controller code to set intent switch. * Currently unused. */ public void NavigateToFriendsActivity() {} @Override public void Update(Model model) { if (model instanceof ProfileSynchronizer) { ProfileSynchronizer profileSynchronizer = SynchronizeSingleton.GetSynchronize(this); profileSynchronizer.UpdateProfile(); } } @Override public void startActivity(Intent intent) { // check if search intent if (Intent.ACTION_SEARCH.equals(intent.getAction())) { SearchSingleton.getSearchSingleton().setInventory(CurrentProfile.getCurrentProfile().getProfile(this).getUser().getInventory().getCards()); } super.startActivity(intent); } public ImageButton getAddButton() { return (ImageButton)findViewById(R.id.btnAddItem); } }
CMPUT301F15T07/TradingApp
SSCTE/app/src/main/java/com/sherpasteven/sscte/InventoryActivity.java
Java
apache-2.0
7,511
package com.baidubce.services.route.model; import com.baidubce.auth.BceCredentials; import com.baidubce.model.AbstractBceRequest; /** * Created by zhangjing60 on 17/8/2. */ public class CreateRouteRequest extends AbstractBceRequest { /** * The API version number */ private String version; /** * An ASCII string whose length is less than 64. * * The request will be idempotent if clientToken is provided. * If the clientToken is not specified by the user, a random String generated by default algorithm will be used. * See more detail at * */ private String clientToken; /** * The id of the route table */ private String routeTableId; /** * The source address which can be 0.0.0.0/0, otherwise, the traffic source of the routing table must belong * to a subnet under the VPC. When the source address is user-defined, the customer segment needs to be within * the existing subnet segment */ private String sourceAddress; /** * The destination address which can be 0.0.0.0/0, otherwise, the destination address cannot be overlapped with * this VPC's cidr (except for the destination segment or the VPC's CIDR is 0.0.0.0/0) */ private String destinationAddress; /** * next hop id * when the nexthopType is "defaultGateway",this field can be empty */ private String nexthopId; /** * route type * The Bcc type is "custom"; * the VPN type is "VPN"; * the NAT type is "NAT"; * the local gateway type is "defaultGateway"" */ private String nexthopType; /** * The option param to describe the route table */ private String description; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getClientToken() { return clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; } public String getSourceAddress() { return sourceAddress; } public void setSourceAddress(String sourceAddress) { this.sourceAddress = sourceAddress; } public String getDestinationAddress() { return destinationAddress; } public void setDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; } public String getNexthopId() { return nexthopId; } public void setNexthopId(String nexthopId) { this.nexthopId = nexthopId; } public String getNexthopType() { return nexthopType; } public void setNexthopType(String nexthopType) { this.nexthopType = nexthopType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRouteTableId() { return routeTableId; } public void setRouteTableId(String routeTableId) { this.routeTableId = routeTableId; } public CreateRouteRequest withVersion(String version) { this.version = version; return this; } /** * Configure optional client token for the request. The request will be idempotent if client token is provided. * If the clientToken is not specified by the user, a random String generated by default algorithm will be used. * * @param clientToken An ASCII string whose length is less than 64. * See more detail at * * @return CreateSubnetRequest with specific clientToken */ public CreateRouteRequest withClientToken(String clientToken) { this.clientToken = clientToken; return this; } /** * configure route table id for the request * @param routeTableId the id of the route table * @return CreateRouteRequest with routeTableId */ public CreateRouteRequest withRouteTableId(String routeTableId) { this.routeTableId = routeTableId; return this; } /** * configure source address for the request * @param sourceAddress the source address * @return CreateRouteRequest with source address */ public CreateRouteRequest withSourceAddress(String sourceAddress) { this.sourceAddress = sourceAddress; return this; } /** * configure destination address for the request * @param destinationAddress the destination address * @return CreateRouteRequest with destination address */ public CreateRouteRequest withDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; return this; } /** * configure next hop id for the request * @param nexthopId the next hop id * @return CreateRouteRequest with the nexthopId */ public CreateRouteRequest withNextHopId(String nexthopId) { this.nexthopId = nexthopId; return this; } /** * configure next hop type for the request * @param nexthopType the route type: BCC-"custom", VPN-"vpn", NAT-"nat" * @return CreateRouteRequest with the nexthopType */ public CreateRouteRequest withNextHopType(String nexthopType) { this.nexthopType = nexthopType; return this; } /** * configure description for the request * @param description the description for the route table * @return CreateRouteRequest with the description */ public CreateRouteRequest withDescription(String description) { this.description = description; return this; } /** * Configure request credential for the request. * * @param credentials a valid instance of BceCredentials. * @return CreateRouteRequest with credentials. */ @Override public CreateRouteRequest withRequestCredentials(BceCredentials credentials) { return null; } }
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/route/model/CreateRouteRequest.java
Java
apache-2.0
6,071
/* * Copyright 2016-present Facebook, 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.facebook.buck.apple; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; import com.facebook.buck.cxx.CxxLink; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer; import com.facebook.buck.rules.FakeSourcePath; import com.facebook.buck.rules.SourceWithFlags; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.args.Arg; import com.facebook.buck.shell.Genrule; import com.facebook.buck.shell.GenruleBuilder; import com.facebook.buck.util.environment.Platform; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import org.hamcrest.Matchers; import org.junit.Test; public class AppleLibraryDescriptionTest { @Test public void linkerFlagsLocationMacro() throws Exception { assumeThat(Platform.detect(), is(Platform.MACOS)); BuildRuleResolver resolver = new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); Genrule dep = (Genrule) GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:dep")) .setOut("out") .build(resolver); AppleLibraryBuilder builder = new AppleLibraryBuilder(BuildTargetFactory.newInstance("//:rule#shared,default")) .setLinkerFlags(ImmutableList.of("--linker-script=$(location //:dep)")) .setSrcs( ImmutableSortedSet.of( SourceWithFlags.of(new FakeSourcePath("foo.c")))); assertThat( builder.findImplicitDeps(), Matchers.hasItem(dep.getBuildTarget())); BuildRule binary = builder.build(resolver); assertThat(binary, Matchers.instanceOf(CxxLink.class)); assertThat( Arg.stringify(((CxxLink) binary).getArgs()), Matchers.hasItem(String.format("--linker-script=%s", dep.getAbsoluteOutputFilePath()))); assertThat( binary.getDeps(), Matchers.hasItem(dep)); } }
illicitonion/buck
test/com/facebook/buck/apple/AppleLibraryDescriptionTest.java
Java
apache-2.0
2,758
package com.evangel.property; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * 家乡属性 * * Created by bysocket on 17/04/2017. */ @Component @ConfigurationProperties(prefix = "home") public class HomeProperties { /** * 省份 */ private String province; /** * 城市 */ private String city; /** * 描述 */ private String desc; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } @Override public String toString() { return "HomeProperties{" + "province='" + province + '\'' + ", city='" + city + '\'' + ", desc='" + desc + '\'' + '}'; } }
T5750/maven-archetype-templates
SpringBoot/springboot-properties/src/main/java/com/evangel/property/HomeProperties.java
Java
apache-2.0
950
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.json; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; class InstanceCoercer extends TypeCoercer<Object> { private final JsonTypeCoercer coercer; InstanceCoercer(JsonTypeCoercer coercer) { this.coercer = Objects.requireNonNull(coercer); } @Override public boolean test(Class aClass) { // If the class doesn't have a no-arg constructor, abandon hope return getConstructor(aClass) != null; } @Override public BiFunction<JsonInput, PropertySetting, Object> apply(Type type) { Constructor<?> constructor = getConstructor(type); return (jsonInput, setter) -> { try { Object instance = constructor.newInstance(); Map<String, TypeAndWriter> allWriters; switch (setter) { case BY_FIELD: allWriters = getFieldWriters(constructor); break; case BY_NAME: allWriters = getBeanWriters(constructor); break; default: throw new JsonException("Cannot determine how to find fields: " + setter); } jsonInput.beginObject(); while (jsonInput.hasNext()) { String key = jsonInput.nextName(); TypeAndWriter writer = allWriters.get(key); if (writer == null) { jsonInput.skipValue(); continue; } Object value = coercer.coerce(jsonInput, writer.type, setter); writer.writer.accept(instance, value); } jsonInput.endObject(); return instance; } catch (ReflectiveOperationException e) { throw new JsonException(e); } }; } private Map<String, TypeAndWriter> getFieldWriters(Constructor<?> constructor) { List<Field> fields = new LinkedList<>(); for (Class current = constructor.getDeclaringClass(); current != Object.class; current = current.getSuperclass()) { fields.addAll(Arrays.asList(current.getDeclaredFields())); } return fields.stream() .filter(field -> !Modifier.isFinal(field.getModifiers())) .filter(field -> !Modifier.isTransient(field.getModifiers())) .peek(field -> field.setAccessible(true)) .collect( Collectors.toMap( Field::getName, field -> { TypeAndWriter tw = new TypeAndWriter(); tw.type = field.getGenericType(); tw.writer = (instance, value) -> { try { field.set(instance, value); } catch (IllegalAccessException e) { throw new JsonException(e); } }; return tw; })); } private Map<String, TypeAndWriter> getBeanWriters(Constructor<?> constructor) { return Stream.of( SimplePropertyDescriptor.getPropertyDescriptors(constructor.getDeclaringClass())) .filter(desc -> desc.getWriteMethod() != null) .collect( Collectors.toMap( SimplePropertyDescriptor::getName, desc -> { TypeAndWriter tw = new TypeAndWriter(); tw.type = desc.getWriteMethod().getGenericParameterTypes()[0]; tw.writer = (instance, value) -> { Method method = desc.getWriteMethod(); method.setAccessible(true); try { method.invoke(instance, value); } catch (ReflectiveOperationException e) { throw new JsonException(e); } }; return tw; })); } private Constructor<?> getConstructor(Type type) { Class target = null; if (type instanceof Class) { target = (Class) type; } else if (type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); if (rawType instanceof Class) { target = (Class) rawType; } } if (target == null) { throw new JsonException("Cannot determine base class"); } try { @SuppressWarnings("unchecked") Constructor<?> constructor = target.getConstructor(); constructor.setAccessible(true); return constructor; } catch (ReflectiveOperationException e) { throw new JsonException(e); } } private class TypeAndWriter { public Type type; public BiConsumer<Object, Object> writer; } }
mach6/selenium
java/client/src/org/openqa/selenium/json/InstanceCoercer.java
Java
apache-2.0
5,803
//CHECKSTYLERULE:OFF: FileLength /* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.querydsl.sql; import static com.querydsl.core.Target.*; import static com.querydsl.sql.Constants.*; import static org.junit.Assert.*; import java.io.IOException; import java.math.BigDecimal; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import org.joda.time.*; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import com.mysema.commons.lang.CloseableIterator; import com.mysema.commons.lang.Pair; import com.querydsl.core.*; import com.querydsl.core.group.Group; import com.querydsl.core.group.GroupBy; import com.querydsl.core.testutil.ExcludeIn; import com.querydsl.core.testutil.IncludeIn; import com.querydsl.core.testutil.Serialization; import com.querydsl.core.types.*; import com.querydsl.core.types.dsl.*; import com.querydsl.sql.domain.*; public class SelectBase extends AbstractBaseTest { private static final Expression<?>[] NO_EXPRESSIONS = new Expression[0]; private final QueryExecution standardTest = new QueryExecution(Module.SQL, Connections.getTarget()) { @Override protected Fetchable<?> createQuery() { return testQuery().from(employee, employee2); } @Override protected Fetchable<?> createQuery(Predicate filter) { return testQuery().from(employee, employee2).where(filter).select(employee.firstname); } }; private <T> T firstResult(Expression<T> expr) { return query().select(expr).fetchFirst(); } private Tuple firstResult(Expression<?>... exprs) { return query().select(exprs).fetchFirst(); } @Test public void aggregate_list() { int min = 30000, avg = 65000, max = 160000; // fetch assertEquals(min, query().from(employee).select(employee.salary.min()).fetch().get(0).intValue()); assertEquals(avg, query().from(employee).select(employee.salary.avg()).fetch().get(0).intValue()); assertEquals(max, query().from(employee).select(employee.salary.max()).fetch().get(0).intValue()); } @Test public void aggregate_uniqueResult() { int min = 30000, avg = 65000, max = 160000; // fetchOne assertEquals(min, query().from(employee).select(employee.salary.min()).fetchOne().intValue()); assertEquals(avg, query().from(employee).select(employee.salary.avg()).fetchOne().intValue()); assertEquals(max, query().from(employee).select(employee.salary.max()).fetchOne().intValue()); } @Test @ExcludeIn(ORACLE) @SkipForQuoted public void alias() { expectedQuery = "select e.ID as id from EMPLOYEE e"; query().from().select(employee.id.as(employee.id)).from(employee).fetch(); } @Test @ExcludeIn({MYSQL, ORACLE}) @SkipForQuoted public void alias_quotes() { expectedQuery = "select e.FIRSTNAME as \"First Name\" from EMPLOYEE e"; query().from(employee).select(employee.firstname.as("First Name")).fetch(); } @Test @IncludeIn(MYSQL) @SkipForQuoted public void alias_quotes_MySQL() { expectedQuery = "select e.FIRSTNAME as `First Name` from EMPLOYEE e"; query().from(employee).select(employee.firstname.as("First Name")).fetch(); } @Test @IncludeIn(ORACLE) @SkipForQuoted public void alias_quotes_Oracle() { expectedQuery = "select e.FIRSTNAME \"First Name\" from EMPLOYEE e"; query().from(employee).select(employee.firstname.as("First Name")); } @Test public void all() { for (Expression<?> expr : survey.all()) { Path<?> path = (Path<?>) expr; assertEquals(survey, path.getMetadata().getParent()); } } private void arithmeticTests(NumberExpression<Integer> one, NumberExpression<Integer> two, NumberExpression<Integer> three, NumberExpression<Integer> four) { assertEquals(1, firstResult(one).intValue()); assertEquals(2, firstResult(two).intValue()); assertEquals(4, firstResult(four).intValue()); assertEquals(3, firstResult(one.subtract(two).add(four)).intValue()); assertEquals(-5, firstResult(one.subtract(two.add(four))).intValue()); assertEquals(-1, firstResult(one.add(two).subtract(four)).intValue()); assertEquals(-1, firstResult(one.add(two.subtract(four))).intValue()); assertEquals(12, firstResult(one.add(two).multiply(four)).intValue()); assertEquals(2, firstResult(four.multiply(one).divide(two)).intValue()); assertEquals(6, firstResult(four.divide(two).multiply(three)).intValue()); assertEquals(1, firstResult(four.divide(two.multiply(two))).intValue()); } @Test public void arithmetic() { NumberExpression<Integer> one = Expressions.numberTemplate(Integer.class, "(1.0)"); NumberExpression<Integer> two = Expressions.numberTemplate(Integer.class, "(2.0)"); NumberExpression<Integer> three = Expressions.numberTemplate(Integer.class, "(3.0)"); NumberExpression<Integer> four = Expressions.numberTemplate(Integer.class, "(4.0)"); arithmeticTests(one, two, three, four); // the following one doesn't work with integer arguments assertEquals(2, firstResult(four.multiply(one.divide(two))).intValue()); } @Test public void arithmetic2() { NumberExpression<Integer> one = Expressions.ONE; NumberExpression<Integer> two = Expressions.TWO; NumberExpression<Integer> three = Expressions.THREE; NumberExpression<Integer> four = Expressions.FOUR; arithmeticTests(one, two, three, four); } @Test public void arithmetic_mod() { NumberExpression<Integer> one = Expressions.numberTemplate(Integer.class, "(1)"); NumberExpression<Integer> two = Expressions.numberTemplate(Integer.class, "(2)"); NumberExpression<Integer> three = Expressions.numberTemplate(Integer.class, "(3)"); NumberExpression<Integer> four = Expressions.numberTemplate(Integer.class, "(4)"); assertEquals(4, firstResult(four.mod(three).add(three)).intValue()); assertEquals(1, firstResult(four.mod(two.add(one))).intValue()); assertEquals(0, firstResult(four.mod(two.multiply(one))).intValue()); assertEquals(2, firstResult(four.add(one).mod(three)).intValue()); } @Test @IncludeIn(POSTGRESQL) // TODO generalize array literal projections public void array() { Expression<Integer[]> expr = Expressions.template(Integer[].class, "'{1,2,3}'::int[]"); Integer[] result = firstResult(expr); assertEquals(3, result.length); assertEquals(1, result[0].intValue()); assertEquals(2, result[1].intValue()); assertEquals(3, result[2].intValue()); } @Test @IncludeIn(POSTGRESQL) // TODO generalize array literal projections public void array2() { Expression<int[]> expr = Expressions.template(int[].class, "'{1,2,3}'::int[]"); int[] result = firstResult(expr); assertEquals(3, result.length); assertEquals(1, result[0]); assertEquals(2, result[1]); assertEquals(3, result[2]); } @Test @ExcludeIn({DERBY, HSQLDB}) public void array_null() { Expression<Integer[]> expr = Expressions.template(Integer[].class, "null"); assertNull(firstResult(expr)); } @Test public void array_projection() { List<String[]> results = query().from(employee).select( new ArrayConstructorExpression<String>(String[].class, employee.firstname)).fetch(); assertFalse(results.isEmpty()); for (String[] result : results) { assertNotNull(result[0]); } } @Test public void beans() { List<Beans> rows = query().from(employee, employee2).select(new QBeans(employee, employee2)).fetch(); assertFalse(rows.isEmpty()); for (Beans row : rows) { assertEquals(Employee.class, row.get(employee).getClass()); assertEquals(Employee.class, row.get(employee2).getClass()); } } @Test public void between() { // 11-13 assertEquals(Arrays.asList(11, 12, 13), query().from(employee).where(employee.id.between(11, 13)).orderBy(employee.id.asc()) .select(employee.id).fetch()); } @Test @ExcludeIn({ORACLE, CUBRID, FIREBIRD, DB2, DERBY, SQLSERVER, SQLITE, TERADATA}) public void boolean_all() { assertTrue(query().from(employee).select(SQLExpressions.all(employee.firstname.isNotNull())).fetchOne()); } @Test @ExcludeIn({ORACLE, CUBRID, FIREBIRD, DB2, DERBY, SQLSERVER, SQLITE, TERADATA}) public void boolean_any() { assertTrue(query().from(employee).select(SQLExpressions.any(employee.firstname.isNotNull())).fetchOne()); } @Test public void case_() { NumberExpression<Float> numExpression = employee.salary.floatValue().divide(employee2.salary.floatValue()).multiply(100.1); NumberExpression<Float> numExpression2 = employee.id.when(0).then(0.0F).otherwise(numExpression); assertEquals(Arrays.asList(87, 90, 88, 87, 83, 80, 75), query().from(employee, employee2) .where(employee.id.eq(employee2.id.add(1))) .orderBy(employee.id.asc(), employee2.id.asc()) .select(numExpression2.floor().intValue()).fetch()); } @Test public void casts() throws SQLException { NumberExpression<?> num = employee.id; List<Expression<?>> exprs = new ArrayList<>(); add(exprs, num.byteValue(), MYSQL); add(exprs, num.doubleValue()); add(exprs, num.floatValue()); add(exprs, num.intValue()); add(exprs, num.longValue(), MYSQL); add(exprs, num.shortValue(), MYSQL); add(exprs, num.stringValue(), DERBY); for (Expression<?> expr : exprs) { for (Object o : query().from(employee).select(expr).fetch()) { assertEquals(expr.getType(), o.getClass()); } } } @Test public void coalesce() { Coalesce<String> c = new Coalesce<String>(employee.firstname, employee.lastname).add("xxx"); assertEquals(Collections.emptyList(), query().from(employee).where(c.getValue().eq("xxx")).select(employee.id).fetch()); } @Test public void compact_join() { // verbose assertEquals(8, query().from(employee) .innerJoin(employee2) .on(employee.superiorId.eq(employee2.id)) .select(employee.id, employee2.id).fetch().size()); // compact assertEquals(8, query().from(employee) .innerJoin(employee.superiorIdKey, employee2) .select(employee.id, employee2.id).fetch().size()); } @Test public void complex_boolean() { BooleanExpression first = employee.firstname.eq("Mike").and(employee.lastname.eq("Smith")); BooleanExpression second = employee.firstname.eq("Joe").and(employee.lastname.eq("Divis")); assertEquals(2, query().from(employee).where(first.or(second)).fetchCount()); assertEquals(0, query().from(employee).where( employee.firstname.eq("Mike"), employee.lastname.eq("Smith").or(employee.firstname.eq("Joe")), employee.lastname.eq("Divis") ).fetchCount()); } @Test public void complex_subQuery() { // alias for the salary NumberPath<BigDecimal> sal = Expressions.numberPath(BigDecimal.class, "sal"); // alias for the subquery PathBuilder<BigDecimal> sq = new PathBuilder<BigDecimal>(BigDecimal.class, "sq"); // query execution query().from( query().from(employee) .select(employee.salary.add(employee.salary).add(employee.salary).as(sal)).as(sq) ).select(sq.get(sal).avg(), sq.get(sal).min(), sq.get(sal).max()).fetch(); } @Test public void constructor_projection() { for (IdName idAndName : query().from(survey).select(new QIdName(survey.id, survey.name)).fetch()) { assertNotNull(idAndName); assertNotNull(idAndName.getId()); assertNotNull(idAndName.getName()); } } @Test public void constructor_projection2() { List<SimpleProjection> projections = query().from(employee).select( Projections.constructor(SimpleProjection.class, employee.firstname, employee.lastname)).fetch(); assertFalse(projections.isEmpty()); for (SimpleProjection projection : projections) { assertNotNull(projection); } } private double cot(double x) { return Math.cos(x) / Math.sin(x); } private double coth(double x) { return Math.cosh(x) / Math.sinh(x); } @Test public void count_with_pK() { assertEquals(10, query().from(employee).fetchCount()); } @Test public void count_without_pK() { assertEquals(10, query().from(QEmployeeNoPK.employee).fetchCount()); } @Test public void count2() { assertEquals(10, query().from(employee).select(employee.count()).fetchFirst().intValue()); } @Test @SkipForQuoted @ExcludeIn(ORACLE) public void count_all() { expectedQuery = "select count(*) as rc from EMPLOYEE e"; NumberPath<Long> rowCount = Expressions.numberPath(Long.class, "rc"); assertEquals(10, query().from(employee).select(Wildcard.count.as(rowCount)).fetchOne().intValue()); } @Test @SkipForQuoted @IncludeIn(ORACLE) public void count_all_Oracle() { expectedQuery = "select count(*) rc from EMPLOYEE e"; NumberPath<Long> rowCount = Expressions.numberPath(Long.class, "rc"); assertEquals(10, query().from(employee).select(Wildcard.count.as(rowCount)).fetchOne().intValue()); } @Test public void count_distinct_with_pK() { assertEquals(10, query().from(employee).distinct().fetchCount()); } @Test public void count_distinct_without_pK() { assertEquals(10, query().from(QEmployeeNoPK.employee).distinct().fetchCount()); } @Test public void count_distinct2() { query().from(employee).select(employee.countDistinct()).fetchFirst(); } @Test public void custom_projection() { List<Projection> tuples = query().from(employee).select( new QProjection(employee.firstname, employee.lastname)).fetch(); assertFalse(tuples.isEmpty()); for (Projection tuple : tuples) { assertNotNull(tuple.get(employee.firstname)); assertNotNull(tuple.get(employee.lastname)); assertNotNull(tuple.getExpr(employee.firstname)); assertNotNull(tuple.getExpr(employee.lastname)); } } @Test @ExcludeIn({CUBRID, DB2, DERBY, HSQLDB, POSTGRESQL, SQLITE, TERADATA}) public void dates() { long ts = ((long) Math.floor(System.currentTimeMillis() / 1000)) * 1000; long tsDate = new org.joda.time.LocalDate(ts).toDateMidnight().getMillis(); long tsTime = new org.joda.time.LocalTime(ts).getMillisOfDay(); List<Object> data = new ArrayList<>(); data.add(Constants.date); data.add(Constants.time); data.add(new java.util.Date(ts)); data.add(new java.util.Date(tsDate)); data.add(new java.util.Date(tsTime)); data.add(new java.sql.Timestamp(ts)); data.add(new java.sql.Timestamp(tsDate)); data.add(new java.sql.Date(110, 0, 1)); data.add(new java.sql.Date(tsDate)); data.add(new java.sql.Time(0, 0, 0)); data.add(new java.sql.Time(12, 30, 0)); data.add(new java.sql.Time(23, 59, 59)); //data.add(new java.sql.Time(tsTime)); data.add(new DateTime(ts)); data.add(new DateTime(tsDate)); data.add(new DateTime(tsTime)); data.add(new LocalDateTime(ts)); data.add(new LocalDateTime(tsDate)); data.add(new LocalDateTime(2014, 3, 30, 2, 0)); data.add(new LocalDate(2010, 1, 1)); data.add(new LocalDate(ts)); data.add(new LocalDate(tsDate)); data.add(new LocalTime(0, 0, 0)); data.add(new LocalTime(12, 30, 0)); data.add(new LocalTime(23, 59, 59)); data.add(new LocalTime(ts)); data.add(new LocalTime(tsTime)); java.time.Instant javaInstant = java.time.Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS); java.time.LocalDateTime javaDateTime = java.time.LocalDateTime.ofInstant(javaInstant, java.time.ZoneId.of("Z")); java.time.LocalDate javaDate = javaDateTime.toLocalDate(); java.time.LocalTime javaTime = javaDateTime.toLocalTime(); data.add(javaInstant); //java.time.Instant data.add(javaDateTime); //java.time.LocalDateTime data.add(javaDate); //java.time.LocalDate data.add(javaTime); //java.time.LocalTime data.add(javaDateTime.atOffset(java.time.ZoneOffset.UTC)); //java.time.OffsetDateTime data.add(javaTime.atOffset(java.time.ZoneOffset.UTC)); //java.time.OffsetTime data.add(javaDateTime.atZone(java.time.ZoneId.of("Z"))); //java.time.ZonedDateTime Map<Object, Object> failures = new IdentityHashMap<>(); for (Object dt : data) { Object dt2 = firstResult(Expressions.constant(dt)); if (!dt.equals(dt2)) { failures.put(dt, dt2); } } if (!failures.isEmpty()) { for (Map.Entry<Object, Object> entry : failures.entrySet()) { System.out.println(entry.getKey().getClass().getName() + ": " + entry.getKey() + " != " + entry.getValue()); } Assert.fail("Failed with " + failures); } } @Test @Ignore // FIXME @ExcludeIn({CUBRID, DB2, DERBY, HSQLDB, POSTGRESQL, SQLITE, TERADATA}) public void dates_cST() { TimeZone tz = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("CST")); // -6:00 dates(); } finally { TimeZone.setDefault(tz); } } @Test @Ignore // FIXME @ExcludeIn({CUBRID, DB2, DERBY, HSQLDB, POSTGRESQL, SQLITE, TERADATA}) public void dates_iOT() { TimeZone tz = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("IOT")); // +6:00 dates(); } finally { TimeZone.setDefault(tz); } } @Test @ExcludeIn({CUBRID, SQLITE, TERADATA}) public void dates_literals() { if (configuration.getUseLiterals()) { dates(); } } @Test @ExcludeIn({SQLITE}) public void date_add() { SQLQuery<?> query = query().from(employee); Date date1 = query.select(employee.datefield).fetchFirst(); Date date2 = query.select(SQLExpressions.addYears(employee.datefield, 1)).fetchFirst(); Date date3 = query.select(SQLExpressions.addMonths(employee.datefield, 1)).fetchFirst(); Date date4 = query.select(SQLExpressions.addDays(employee.datefield, 1)).fetchFirst(); assertTrue(date2.getTime() > date1.getTime()); assertTrue(date3.getTime() > date1.getTime()); assertTrue(date4.getTime() > date1.getTime()); } @Test @ExcludeIn({SQLITE}) public void date_add_Timestamp() { List<Expression<?>> exprs = new ArrayList<>(); DateTimeExpression<java.util.Date> dt = Expressions.currentTimestamp(); add(exprs, SQLExpressions.addYears(dt, 1)); add(exprs, SQLExpressions.addMonths(dt, 1), ORACLE); add(exprs, SQLExpressions.addDays(dt, 1)); add(exprs, SQLExpressions.addHours(dt, 1), TERADATA); add(exprs, SQLExpressions.addMinutes(dt, 1), TERADATA); add(exprs, SQLExpressions.addSeconds(dt, 1), TERADATA); for (Expression<?> expr : exprs) { assertNotNull(firstResult(expr)); } } @Test @ExcludeIn({DB2, SQLITE, TERADATA}) public void date_diff() { QEmployee employee2 = new QEmployee("employee2"); SQLQuery<?> query = query().from(employee).orderBy(employee.id.asc()); SQLQuery<?> query2 = query().from(employee, employee2) .orderBy(employee.id.asc(), employee2.id.desc()); List<DatePart> dps = new ArrayList<>(); add(dps, DatePart.year); add(dps, DatePart.month); add(dps, DatePart.week); add(dps, DatePart.day); add(dps, DatePart.hour, HSQLDB); add(dps, DatePart.minute, HSQLDB); add(dps, DatePart.second, HSQLDB); LocalDate localDate = new LocalDate(1970, 1, 10); Date date = new Date(localDate.toDateMidnight().getMillis()); for (DatePart dp : dps) { int diff1 = query.select(SQLExpressions.datediff(dp, date, employee.datefield)).fetchFirst(); int diff2 = query.select(SQLExpressions.datediff(dp, employee.datefield, date)).fetchFirst(); int diff3 = query2.select(SQLExpressions.datediff(dp, employee.datefield, employee2.datefield)).fetchFirst(); assertEquals(diff1, -diff2); } Timestamp timestamp = new Timestamp(new java.util.Date().getTime()); for (DatePart dp : dps) { query.select(SQLExpressions.datediff(dp, Expressions.currentTimestamp(), timestamp)).fetchOne(); } } // TDO Date_diff with timestamps @Test @ExcludeIn({DB2, HSQLDB, SQLITE, TERADATA}) public void date_diff2() { SQLQuery<?> query = query().from(employee).orderBy(employee.id.asc()); LocalDate localDate = new LocalDate(1970, 1, 10); Date date = new Date(localDate.toDateMidnight().getMillis()); int years = query.select(SQLExpressions.datediff(DatePart.year, date, employee.datefield)).fetchFirst(); int months = query.select(SQLExpressions.datediff(DatePart.month, date, employee.datefield)).fetchFirst(); // weeks int days = query.select(SQLExpressions.datediff(DatePart.day, date, employee.datefield)).fetchFirst(); int hours = query.select(SQLExpressions.datediff(DatePart.hour, date, employee.datefield)).fetchFirst(); int minutes = query.select(SQLExpressions.datediff(DatePart.minute, date, employee.datefield)).fetchFirst(); int seconds = query.select(SQLExpressions.datediff(DatePart.second, date, employee.datefield)).fetchFirst(); assertEquals(949363200, seconds); assertEquals(15822720, minutes); assertEquals(263712, hours); assertEquals(10988, days); assertEquals(361, months); assertEquals(30, years); } @Test @ExcludeIn({SQLITE}) // FIXME public void date_trunc() { DateTimeExpression<java.util.Date> expr = DateTimeExpression.currentTimestamp(); List<DatePart> dps = new ArrayList<>(); add(dps, DatePart.year); add(dps, DatePart.month); add(dps, DatePart.week, DERBY, FIREBIRD, SQLSERVER); add(dps, DatePart.day); add(dps, DatePart.hour); add(dps, DatePart.minute); add(dps, DatePart.second); for (DatePart dp : dps) { firstResult(SQLExpressions.datetrunc(dp, expr)); } } @Test @ExcludeIn({SQLITE, TERADATA}) // FIXME public void date_trunc2() { DateTimeExpression<DateTime> expr = DateTimeExpression.currentTimestamp(DateTime.class); Tuple tuple = firstResult( expr, SQLExpressions.datetrunc(DatePart.year, expr), SQLExpressions.datetrunc(DatePart.month, expr), SQLExpressions.datetrunc(DatePart.day, expr), SQLExpressions.datetrunc(DatePart.hour, expr), SQLExpressions.datetrunc(DatePart.minute, expr), SQLExpressions.datetrunc(DatePart.second, expr)); DateTime date = tuple.get(expr); DateTime toYear = tuple.get(SQLExpressions.datetrunc(DatePart.year, expr)); DateTime toMonth = tuple.get(SQLExpressions.datetrunc(DatePart.month, expr)); DateTime toDay = tuple.get(SQLExpressions.datetrunc(DatePart.day, expr)); DateTime toHour = tuple.get(SQLExpressions.datetrunc(DatePart.hour, expr)); DateTime toMinute = tuple.get(SQLExpressions.datetrunc(DatePart.minute, expr)); DateTime toSecond = tuple.get(SQLExpressions.datetrunc(DatePart.second, expr)); assertEquals(date.getZone(), toYear.getZone()); assertEquals(date.getZone(), toMonth.getZone()); assertEquals(date.getZone(), toDay.getZone()); assertEquals(date.getZone(), toHour.getZone()); assertEquals(date.getZone(), toMinute.getZone()); assertEquals(date.getZone(), toSecond.getZone()); // year assertEquals(date.getYear(), toYear.getYear()); assertEquals(date.getYear(), toMonth.getYear()); assertEquals(date.getYear(), toDay.getYear()); assertEquals(date.getYear(), toHour.getYear()); assertEquals(date.getYear(), toMinute.getYear()); assertEquals(date.getYear(), toSecond.getYear()); // month assertEquals(1, toYear.getMonthOfYear()); assertEquals(date.getMonthOfYear(), toMonth.getMonthOfYear()); assertEquals(date.getMonthOfYear(), toDay.getMonthOfYear()); assertEquals(date.getMonthOfYear(), toHour.getMonthOfYear()); assertEquals(date.getMonthOfYear(), toMinute.getMonthOfYear()); assertEquals(date.getMonthOfYear(), toSecond.getMonthOfYear()); // day assertEquals(1, toYear.getDayOfMonth()); assertEquals(1, toMonth.getDayOfMonth()); assertEquals(date.getDayOfMonth(), toDay.getDayOfMonth()); assertEquals(date.getDayOfMonth(), toHour.getDayOfMonth()); assertEquals(date.getDayOfMonth(), toMinute.getDayOfMonth()); assertEquals(date.getDayOfMonth(), toSecond.getDayOfMonth()); // hour assertEquals(0, toYear.getHourOfDay()); assertEquals(0, toMonth.getHourOfDay()); assertEquals(0, toDay.getHourOfDay()); assertEquals(date.getHourOfDay(), toHour.getHourOfDay()); assertEquals(date.getHourOfDay(), toMinute.getHourOfDay()); assertEquals(date.getHourOfDay(), toSecond.getHourOfDay()); // minute assertEquals(0, toYear.getMinuteOfHour()); assertEquals(0, toMonth.getMinuteOfHour()); assertEquals(0, toDay.getMinuteOfHour()); assertEquals(0, toHour.getMinuteOfHour()); assertEquals(date.getMinuteOfHour(), toMinute.getMinuteOfHour()); assertEquals(date.getMinuteOfHour(), toSecond.getMinuteOfHour()); // second assertEquals(0, toYear.getSecondOfMinute()); assertEquals(0, toMonth.getSecondOfMinute()); assertEquals(0, toDay.getSecondOfMinute()); assertEquals(0, toHour.getSecondOfMinute()); assertEquals(0, toMinute.getSecondOfMinute()); assertEquals(date.getSecondOfMinute(), toSecond.getSecondOfMinute()); } @Test public void dateTime() { SQLQuery<?> query = query().from(employee).orderBy(employee.id.asc()); assertEquals(Integer.valueOf(10), query.select(employee.datefield.dayOfMonth()).fetchFirst()); assertEquals(Integer.valueOf(2), query.select(employee.datefield.month()).fetchFirst()); assertEquals(Integer.valueOf(2000), query.select(employee.datefield.year()).fetchFirst()); assertEquals(Integer.valueOf(200002), query.select(employee.datefield.yearMonth()).fetchFirst()); } @Test public void dateTime_to_date() { firstResult(SQLExpressions.date(DateTimeExpression.currentTimestamp())); } private double degrees(double x) { return x * 180.0 / Math.PI; } @Test public void distinct_count() { long count1 = query().from(employee).distinct().fetchCount(); long count2 = query().from(employee).distinct().fetchCount(); assertEquals(count1, count2); } @Test public void distinct_list() { List<Integer> lengths1 = query().from(employee).distinct().select(employee.firstname.length()).fetch(); List<Integer> lengths2 = query().from(employee).distinct().select(employee.firstname.length()).fetch(); assertEquals(lengths1, lengths2); } @Test public void duplicate_columns() { assertEquals(10, query().from(employee) .select(employee.id, employee.id).fetch().size()); } @Test public void duplicate_columns_In_Subquery() { QEmployee employee2 = new QEmployee("e2"); assertEquals(10, query().from(employee).where( query().from(employee2) .where(employee2.id.eq(employee.id)) .select(employee2.id, employee2.id).exists()).fetchCount()); } @Test public void factoryExpression_in_groupBy() { Expression<Employee> empBean = Projections.bean(Employee.class, employee.id, employee.superiorId); assertTrue(query().from(employee).groupBy(empBean).select(empBean).fetchFirst() != null); } @Test @ExcludeIn({H2, SQLITE, DERBY, CUBRID, MYSQL}) public void full_join() throws SQLException { assertEquals(18, query().from(employee).fullJoin(employee2) .on(employee.superiorIdKey.on(employee2)) .select(employee.id, employee2.id).fetch().size()); } @Test public void getResultSet() throws IOException, SQLException { ResultSet results = query().select(survey.id, survey.name).from(survey).getResults(); while (results.next()) { assertNotNull(results.getObject(1)); assertNotNull(results.getObject(2)); } results.close(); } @Test public void groupBy_superior() { SQLQuery<?> qry = query() .from(employee) .innerJoin(employee._superiorIdKey, employee2); QTuple subordinates = Projections.tuple(employee2.id, employee2.firstname, employee2.lastname); Map<Integer, Group> results = qry.transform( GroupBy.groupBy(employee.id).as(employee.firstname, employee.lastname, GroupBy.map(employee2.id, subordinates))); assertEquals(2, results.size()); // Mike Smith Group group = results.get(1); assertEquals("Mike", group.getOne(employee.firstname)); assertEquals("Smith", group.getOne(employee.lastname)); Map<Integer, Tuple> emps = group.getMap(employee2.id, subordinates); assertEquals(4, emps.size()); assertEquals("Steve", emps.get(12).get(employee2.firstname)); // Mary Smith group = results.get(2); assertEquals("Mary", group.getOne(employee.firstname)); assertEquals("Smith", group.getOne(employee.lastname)); emps = group.getMap(employee2.id, subordinates); assertEquals(4, emps.size()); assertEquals("Mason", emps.get(21).get(employee2.lastname)); } @Test public void groupBy_yearMonth() { assertEquals(Collections.singletonList(10L), query().from(employee) .groupBy(employee.datefield.yearMonth()) .orderBy(employee.datefield.yearMonth().asc()) .select(employee.id.count()).fetch()); } @Test @ExcludeIn({H2, DB2, DERBY, ORACLE, SQLSERVER}) public void groupBy_validate() { NumberPath<BigDecimal> alias = Expressions.numberPath(BigDecimal.class, "alias"); assertEquals(8, query().from(employee) .groupBy(alias) .select(employee.salary.multiply(100).as(alias), employee.salary.avg()).fetch().size()); } @Test @ExcludeIn({FIREBIRD}) public void groupBy_count() { List<Integer> ids = query().from(employee).groupBy(employee.id).select(employee.id).fetch(); long count = query().from(employee).groupBy(employee.id).fetchCount(); QueryResults<Integer> results = query().from(employee).groupBy(employee.id) .limit(1).select(employee.id).fetchResults(); assertEquals(10, ids.size()); assertEquals(10, count); assertEquals(1, results.getResults().size()); assertEquals(10, results.getTotal()); } @Test @ExcludeIn({FIREBIRD, SQLSERVER, TERADATA}) public void groupBy_Distinct_count() { List<Integer> ids = query().from(employee).groupBy(employee.id).distinct().select(Expressions.ONE).fetch(); QueryResults<Integer> results = query().from(employee).groupBy(employee.id) .limit(1).distinct().select(Expressions.ONE).fetchResults(); assertEquals(1, ids.size()); assertEquals(1, results.getResults().size()); assertEquals(1, results.getTotal()); } @Test @ExcludeIn({FIREBIRD}) public void having_count() { //Produces empty resultset https://github.com/querydsl/querydsl/issues/1055 query().from(employee) .innerJoin(employee2).on(employee.id.eq(employee2.id)) .groupBy(employee.id) .having(Wildcard.count.eq(4L)) .select(employee.id, employee.firstname).fetchResults(); } @SuppressWarnings("unchecked") @Test(expected = IllegalArgumentException.class) public void illegalUnion() throws SQLException { SubQueryExpression<Integer> sq1 = query().from(employee).select(employee.id.max()); SubQueryExpression<Integer> sq2 = query().from(employee).select(employee.id.max()); assertEquals(0, query().from(employee).union(sq1, sq2).list().size()); } @Test public void in() { assertEquals(2, query().from(employee) .where(employee.id.in(Arrays.asList(1, 2))) .select(employee).fetch().size()); } @Test @ExcludeIn({DERBY, FIREBIRD, SQLITE, SQLSERVER, TERADATA}) public void in_long_list() { List<Integer> ids = new ArrayList<>(); for (int i = 0; i < 20000; i++) { ids.add(i); } assertEquals( query().from(employee).fetchCount(), query().from(employee).where(employee.id.in(ids)).fetchCount()); } @Test @ExcludeIn({DERBY, FIREBIRD, SQLITE, SQLSERVER, TERADATA}) public void notIn_long_list() { List<Integer> ids = new ArrayList<>(); for (int i = 0; i < 20000; i++) { ids.add(i); } assertEquals(0, query().from(employee).where(employee.id.notIn(ids)).fetchCount()); } @Test public void in_empty() { assertEquals(0, query().from(employee).where(employee.id.in(Collections.emptyList())).fetchCount()); } @Test @ExcludeIn(DERBY) public void in_null() { assertEquals(1, query().from(employee).where(employee.id.in(1, null)).fetchCount()); } @Test @ExcludeIn({MYSQL, TERADATA}) public void in_subqueries() { QEmployee e1 = new QEmployee("e1"); QEmployee e2 = new QEmployee("e2"); assertEquals(2, query().from(employee).where(employee.id.in( query().from(e1).where(e1.firstname.eq("Mike")).select(e1.id), query().from(e2).where(e2.firstname.eq("Mary")).select(e2.id) )).fetchCount()); } @Test public void notIn_empty() { long count = query().from(employee).fetchCount(); assertEquals(count, query().from(employee).where(employee.id.notIn(Collections.emptyList())).fetchCount()); } @Test public void inner_join() throws SQLException { assertEquals(8, query().from(employee).innerJoin(employee2) .on(employee.superiorIdKey.on(employee2)) .select(employee.id, employee2.id).fetch().size()); } @Test public void inner_join_2Conditions() { assertEquals(8, query().from(employee).innerJoin(employee2) .on(employee.superiorIdKey.on(employee2)) .on(employee2.firstname.isNotNull()) .select(employee.id, employee2.id).fetch().size()); } @Test public void join() throws Exception { for (String name : query().from(survey, survey2) .where(survey.id.eq(survey2.id)).select(survey.name).fetch()) { assertNotNull(name); } } @Test public void joins() throws SQLException { for (Tuple row : query().from(employee).innerJoin(employee2) .on(employee.superiorId.eq(employee2.superiorId)) .where(employee2.id.eq(10)) .select(employee.id, employee2.id).fetch()) { assertNotNull(row.get(employee.id)); assertNotNull(row.get(employee2.id)); } } @Test public void left_join() throws SQLException { assertEquals(10, query().from(employee).leftJoin(employee2) .on(employee.superiorIdKey.on(employee2)) .select(employee.id, employee2.id).fetch().size()); } @Test public void like() { assertEquals(0, query().from(employee).where(employee.firstname.like("\\")).fetchCount()); assertEquals(0, query().from(employee).where(employee.firstname.like("\\\\")).fetchCount()); } @Test public void like_ignore_case() { assertEquals(3, query().from(employee).where(employee.firstname.likeIgnoreCase("%m%")).fetchCount()); } @Test @ExcludeIn(FIREBIRD) public void like_escape() { List<String> strs = Arrays.asList("%a", "a%", "%a%", "_a", "a_", "_a_", "[C-P]arsen", "a\nb"); for (String str : strs) { assertTrue(str, query() .from(employee) .where(Expressions.predicate(Ops.STRING_CONTAINS, Expressions.constant(str), Expressions.constant(str))).fetchCount() > 0); } } @Test @ExcludeIn({DB2, DERBY}) public void like_number() { assertEquals(5, query().from(employee) .where(employee.id.like("1%")).fetchCount()); } @Test public void limit() throws SQLException { assertEquals(Arrays.asList(23, 22, 21, 20), query().from(employee) .orderBy(employee.firstname.asc()) .limit(4).select(employee.id).fetch()); } @Test public void limit_and_offset() throws SQLException { assertEquals(Arrays.asList(20, 13, 10, 2), query().from(employee) .orderBy(employee.firstname.asc()) .limit(4).offset(3) .select(employee.id).fetch()); } @Test public void limit_and_offset_Group() { assertEquals(9, query().from(employee) .orderBy(employee.id.asc()) .limit(100).offset(1) .transform(GroupBy.groupBy(employee.id).as(employee)).size()); } @Test public void limit_and_offset_and_Order() { List<String> names2 = Arrays.asList("Helen","Jennifer","Jim","Joe"); assertEquals(names2, query().from(employee) .orderBy(employee.firstname.asc()) .limit(4).offset(2) .select(employee.firstname).fetch()); } @Test @IncludeIn(DERBY) public void limit_and_offset_In_Derby() throws SQLException { expectedQuery = "select e.ID from EMPLOYEE e offset 3 rows fetch next 4 rows only"; query().from(employee).limit(4).offset(3).select(employee.id).fetch(); // limit expectedQuery = "select e.ID from EMPLOYEE e fetch first 4 rows only"; query().from(employee).limit(4).select(employee.id).fetch(); // offset expectedQuery = "select e.ID from EMPLOYEE e offset 3 rows"; query().from(employee).offset(3).select(employee.id).fetch(); } @Test @IncludeIn(ORACLE) @SkipForQuoted public void limit_and_offset_In_Oracle() throws SQLException { if (configuration.getUseLiterals()) { return; } // limit expectedQuery = "select * from ( select e.ID from EMPLOYEE e ) where rownum <= ?"; query().from(employee).limit(4).select(employee.id).fetch(); // offset expectedQuery = "select * from ( select a.*, rownum rn from ( select e.ID from EMPLOYEE e ) a) where rn > ?"; query().from(employee).offset(3).select(employee.id).fetch(); // limit offset expectedQuery = "select * from ( select a.*, rownum rn from ( select e.ID from EMPLOYEE e ) a) where rn > 3 and rownum <= 4"; query().from(employee).limit(4).offset(3).select(employee.id).fetch(); } @Test @ExcludeIn({ORACLE, DB2, DERBY, FIREBIRD, SQLSERVER, CUBRID, TERADATA}) @SkipForQuoted public void limit_and_offset2() throws SQLException { // limit expectedQuery = "select e.ID from EMPLOYEE e limit ?"; query().from(employee).limit(4).select(employee.id).fetch(); // limit offset expectedQuery = "select e.ID from EMPLOYEE e limit ? offset ?"; query().from(employee).limit(4).offset(3).select(employee.id).fetch(); } @Test public void limit_and_order() { List<String> names1 = Arrays.asList("Barbara","Daisy","Helen","Jennifer"); assertEquals(names1, query().from(employee) .orderBy(employee.firstname.asc()) .limit(4) .select(employee.firstname).fetch()); } @Test public void listResults() { QueryResults<Integer> results = query().from(employee) .limit(10).offset(1).orderBy(employee.id.asc()) .select(employee.id).fetchResults(); assertEquals(10, results.getTotal()); } @Test public void listResults2() { QueryResults<Integer> results = query().from(employee) .limit(2).offset(10).orderBy(employee.id.asc()) .select(employee.id).fetchResults(); assertEquals(10, results.getTotal()); } @Test public void listResults_factoryExpression() { QueryResults<Employee> results = query().from(employee) .limit(10).offset(1).orderBy(employee.id.asc()) .select(employee).fetchResults(); assertEquals(10, results.getTotal()); } @Test @ExcludeIn({DB2, DERBY}) public void literals() { assertEquals(1L, firstResult(ConstantImpl.create(1)).intValue()); assertEquals(2L, firstResult(ConstantImpl.create(2L)).longValue()); assertEquals(3.0, firstResult(ConstantImpl.create(3.0)), 0.001); assertEquals(4.0f, firstResult(ConstantImpl.create(4.0f)), 0.001); assertEquals(true, firstResult(ConstantImpl.create(true))); assertEquals(false, firstResult(ConstantImpl.create(false))); assertEquals("abc", firstResult(ConstantImpl.create("abc"))); assertEquals("'", firstResult(ConstantImpl.create("'"))); assertEquals("\"", firstResult(ConstantImpl.create("\""))); assertEquals("\n", firstResult(ConstantImpl.create("\n"))); assertEquals("\r\n", firstResult(ConstantImpl.create("\r\n"))); assertEquals("\t", firstResult(ConstantImpl.create("\t"))); } @Test public void literals_literals() { if (configuration.getUseLiterals()) { literals(); } } private double log(double x, int y) { return Math.log(x) / Math.log(y); } @Test @ExcludeIn({SQLITE, DERBY}) public void lPad() { assertEquals(" ab", firstResult(StringExpressions.lpad(ConstantImpl.create("ab"), 4))); assertEquals("!!ab", firstResult(StringExpressions.lpad(ConstantImpl.create("ab"), 4, '!'))); } // @Test // public void map() { // Map<Integer, String> idToName = query().from(employee).map(employee.id.as("id"), employee.firstname); // for (Map.Entry<Integer, String> entry : idToName.entrySet()) { // assertNotNull(entry.getKey()); // assertNotNull(entry.getValue()); // } // } @Test @SuppressWarnings("serial") public void mappingProjection() { List<Pair<String, String>> pairs = query().from(employee) .select(new MappingProjection<Pair<String, String>>(Pair.class, employee.firstname, employee.lastname) { @Override protected Pair<String, String> map(Tuple row) { return Pair.of(row.get(employee.firstname), row.get(employee.lastname)); } }).fetch(); for (Pair<String, String> pair : pairs) { assertNotNull(pair.getFirst()); assertNotNull(pair.getSecond()); } } @Test public void math() { math(Expressions.numberTemplate(Double.class, "0.50")); } @Test @ExcludeIn({FIREBIRD, SQLSERVER}) // FIXME public void math2() { math(Expressions.constant(0.5)); } private void math(Expression<Double> expr) { double precision = 0.001; assertEquals(Math.acos(0.5), firstResult(MathExpressions.acos(expr)), precision); assertEquals(Math.asin(0.5), firstResult(MathExpressions.asin(expr)), precision); assertEquals(Math.atan(0.5), firstResult(MathExpressions.atan(expr)), precision); assertEquals(Math.cos(0.5), firstResult(MathExpressions.cos(expr)), precision); assertEquals(Math.cosh(0.5), firstResult(MathExpressions.cosh(expr)), precision); assertEquals(cot(0.5), firstResult(MathExpressions.cot(expr)), precision); if (target != Target.DERBY || expr instanceof Constant) { // FIXME: The resulting value is outside the range for the data type DECIMAL/NUMERIC(4,4). assertEquals(coth(0.5), firstResult(MathExpressions.coth(expr)), precision); } assertEquals(degrees(0.5), firstResult(MathExpressions.degrees(expr)), precision); assertEquals(Math.exp(0.5), firstResult(MathExpressions.exp(expr)), precision); assertEquals(Math.log(0.5), firstResult(MathExpressions.ln(expr)), precision); assertEquals(log(0.5, 10), firstResult(MathExpressions.log(expr, 10)), precision); assertEquals(0.25, firstResult(MathExpressions.power(expr, 2)), precision); assertEquals(radians(0.5), firstResult(MathExpressions.radians(expr)), precision); assertEquals(Integer.valueOf(1), firstResult(MathExpressions.sign(expr))); assertEquals(Math.sin(0.5), firstResult(MathExpressions.sin(expr)), precision); assertEquals(Math.sinh(0.5), firstResult(MathExpressions.sinh(expr)), precision); assertEquals(Math.tan(0.5), firstResult(MathExpressions.tan(expr)), precision); assertEquals(Math.tanh(0.5), firstResult(MathExpressions.tanh(expr)), precision); } @Test @ExcludeIn(DERBY) // Derby doesn't support mod with decimal operands public void math3() { // 1.0 + 2.0 * 3.0 - 4.0 / 5.0 + 6.0 % 3.0 NumberTemplate<Double> one = Expressions.numberTemplate(Double.class, "1.0"); NumberTemplate<Double> two = Expressions.numberTemplate(Double.class, "2.0"); NumberTemplate<Double> three = Expressions.numberTemplate(Double.class, "3.0"); NumberTemplate<Double> four = Expressions.numberTemplate(Double.class, "4.0"); NumberTemplate<Double> five = Expressions.numberTemplate(Double.class, "5.0"); NumberTemplate<Double> six = Expressions.numberTemplate(Double.class, "6.0"); Double num = query().select(one.add(two.multiply(three)).subtract(four.divide(five)).add(six.mod(three))).fetchFirst(); assertEquals(6.2, num, 0.001); } @Test public void nested_tuple_projection() { Concatenation concat = new Concatenation(employee.firstname, employee.lastname); List<Tuple> tuples = query().from(employee) .select(employee.firstname, employee.lastname, concat).fetch(); assertFalse(tuples.isEmpty()); for (Tuple tuple : tuples) { String firstName = tuple.get(employee.firstname); String lastName = tuple.get(employee.lastname); assertEquals(firstName + lastName, tuple.get(concat)); } } @Test public void no_from() { assertNotNull(firstResult(DateExpression.currentDate())); } @Test public void nullif() { query().from(employee).select(employee.firstname.nullif(employee.lastname)).fetch(); } @Test public void nullif_constant() { query().from(employee).select(employee.firstname.nullif("xxx")).fetch(); } @Test public void num_cast() { query().from(employee).select(employee.id.castToNum(Long.class)).fetch(); query().from(employee).select(employee.id.castToNum(Float.class)).fetch(); query().from(employee).select(employee.id.castToNum(Double.class)).fetch(); } @Test public void num_cast2() { NumberExpression<Integer> num = Expressions.numberTemplate(Integer.class, "0"); firstResult(num.castToNum(Byte.class)); firstResult(num.castToNum(Short.class)); firstResult(num.castToNum(Integer.class)); firstResult(num.castToNum(Long.class)); firstResult(num.castToNum(Float.class)); firstResult(num.castToNum(Double.class)); } @Test public void num_date_operation() { long result = query() .select(employee.datefield.year().mod(1)) .from(employee) .fetchFirst(); assertEquals(0, result); } @Test @ExcludeIn({DERBY, FIREBIRD, POSTGRESQL}) public void number_as_boolean() { QNumberTest numberTest = QNumberTest.numberTest; delete(numberTest).execute(); insert(numberTest).set(numberTest.col1Boolean, true).execute(); insert(numberTest).set(numberTest.col1Number, (byte) 1).execute(); assertEquals(2, query().from(numberTest).select(numberTest.col1Boolean).fetch().size()); assertEquals(2, query().from(numberTest).select(numberTest.col1Number).fetch().size()); } @Test public void number_as_boolean_Null() { QNumberTest numberTest = QNumberTest.numberTest; delete(numberTest).execute(); insert(numberTest).setNull(numberTest.col1Boolean).execute(); insert(numberTest).setNull(numberTest.col1Number).execute(); assertEquals(2, query().from(numberTest).select(numberTest.col1Boolean).fetch().size()); assertEquals(2, query().from(numberTest).select(numberTest.col1Number).fetch().size()); } @Test public void offset_only() { assertEquals(Arrays.asList(20, 13, 10, 2, 1, 11, 12), query().from(employee) .orderBy(employee.firstname.asc()) .offset(3) .select(employee.id).fetch()); } @Test public void operation_in_constant_list() { assertEquals(0, query().from(survey).where(survey.name.charAt(0).in(Collections.singletonList('a'))).fetchCount()); assertEquals(0, query().from(survey).where(survey.name.charAt(0).in(Arrays.asList('a','b'))).fetchCount()); assertEquals(0, query().from(survey).where(survey.name.charAt(0).in(Arrays.asList('a','b','c'))).fetchCount()); } @Test public void order_nullsFirst() { assertEquals(Collections.singletonList("Hello World"), query().from(survey) .orderBy(survey.name.asc().nullsFirst()) .select(survey.name).fetch()); } @Test public void order_nullsLast() { assertEquals(Collections.singletonList("Hello World"), query().from(survey) .orderBy(survey.name.asc().nullsLast()) .select(survey.name).fetch()); } @Test public void params() { Param<String> name = new Param<String>(String.class,"name"); assertEquals("Mike", query() .from(employee).where(employee.firstname.eq(name)) .set(name, "Mike") .select(employee.firstname).fetchFirst()); } @Test public void params_anon() { Param<String> name = new Param<String>(String.class); assertEquals("Mike", query() .from(employee).where(employee.firstname.eq(name)) .set(name, "Mike") .select(employee.firstname).fetchFirst()); } @Test(expected = ParamNotSetException.class) public void params_not_set() { Param<String> name = new Param<String>(String.class,"name"); assertEquals("Mike", query() .from(employee).where(employee.firstname.eq(name)) .select(employee.firstname).fetchFirst()); } @Test @ExcludeIn({DB2, DERBY, FIREBIRD, HSQLDB, ORACLE, SQLSERVER}) @SkipForQuoted public void path_alias() { expectedQuery = "select e.LASTNAME, sum(e.SALARY) as salarySum " + "from EMPLOYEE e " + "group by e.LASTNAME having salarySum > ?"; NumberExpression<BigDecimal> salarySum = employee.salary.sum().as("salarySum"); query().from(employee) .groupBy(employee.lastname) .having(salarySum.gt(10000)) .select(employee.lastname, salarySum).fetch(); } @Test public void path_in_constant_list() { assertEquals(0, query().from(survey).where(survey.name.in(Collections.singletonList("a"))).fetchCount()); assertEquals(0, query().from(survey).where(survey.name.in(Arrays.asList("a","b"))).fetchCount()); assertEquals(0, query().from(survey).where(survey.name.in(Arrays.asList("a","b","c"))).fetchCount()); } @Test public void precedence() { StringPath fn = employee.firstname; StringPath ln = employee.lastname; Predicate where = fn.eq("Mike").and(ln.eq("Smith")).or(fn.eq("Joe").and(ln.eq("Divis"))); assertEquals(2L, query().from(employee).where(where).fetchCount()); } @Test public void precedence2() { StringPath fn = employee.firstname; StringPath ln = employee.lastname; Predicate where = fn.eq("Mike").and(ln.eq("Smith").or(fn.eq("Joe")).and(ln.eq("Divis"))); assertEquals(0L, query().from(employee).where(where).fetchCount()); } @Test public void projection() throws IOException { CloseableIterator<Tuple> results = query().from(survey).select(survey.all()).iterate(); assertTrue(results.hasNext()); while (results.hasNext()) { assertEquals(3, results.next().size()); } results.close(); } @Test public void projection_and_twoColumns() { // projection and two columns for (Tuple row : query().from(survey) .select(new QIdName(survey.id, survey.name), survey.id, survey.name).fetch()) { assertEquals(3, row.size()); assertEquals(IdName.class, row.get(0, Object.class).getClass()); assertEquals(Integer.class, row.get(1, Object.class).getClass()); assertEquals(String.class, row.get(2, Object.class).getClass()); } } @Test public void projection2() throws IOException { CloseableIterator<Tuple> results = query().from(survey).select(survey.id, survey.name).iterate(); assertTrue(results.hasNext()); while (results.hasNext()) { assertEquals(2, results.next().size()); } results.close(); } @Test public void projection3() throws IOException { CloseableIterator<String> names = query().from(survey).select(survey.name).iterate(); assertTrue(names.hasNext()); while (names.hasNext()) { System.out.println(names.next()); } names.close(); } @Test public void qBeanUsage() { PathBuilder<Object[]> sq = new PathBuilder<Object[]>(Object[].class, "sq"); List<Survey> surveys = query().from( query().from(survey).select(survey.all()).as("sq")) .select(Projections.bean(Survey.class, Collections.singletonMap("name", sq.get(survey.name)))).fetch(); assertFalse(surveys.isEmpty()); } @Test public void query_with_constant() throws Exception { for (Tuple row : query().from(survey) .where(survey.id.eq(1)) .select(survey.id, survey.name).fetch()) { assertNotNull(row.get(survey.id)); assertNotNull(row.get(survey.name)); } } @Test public void query1() throws Exception { for (String s : query().from(survey).select(survey.name).fetch()) { assertNotNull(s); } } @Test public void query2() throws Exception { for (Tuple row : query().from(survey).select(survey.id, survey.name).fetch()) { assertNotNull(row.get(survey.id)); assertNotNull(row.get(survey.name)); } } private double radians(double x) { return x * Math.PI / 180.0; } @Test public void random() { firstResult(MathExpressions.random()); } @Test @ExcludeIn({FIREBIRD, ORACLE, POSTGRESQL, SQLITE, TERADATA}) public void random2() { firstResult(MathExpressions.random(10)); } @Test public void relationalPath_projection() { List<Tuple> results = query().from(employee, employee2).where(employee.id.eq(employee2.id)) .select(employee, employee2).fetch(); assertFalse(results.isEmpty()); for (Tuple row : results) { Employee e1 = row.get(employee); Employee e2 = row.get(employee2); assertEquals(e1.getId(), e2.getId()); } } @Test public void relationalPath_eq() { assertEquals(10, query().from(employee, employee2) .where(employee.eq(employee2)) .select(employee.id, employee2.id).fetch().size()); } @Test public void relationalPath_ne() { assertEquals(90, query().from(employee, employee2) .where(employee.ne(employee2)) .select(employee.id, employee2.id).fetch().size()); } @Test public void relationalPath_eq2() { assertEquals(1, query().from(survey, survey2) .where(survey.eq(survey2)) .select(survey.id, survey2.id).fetch().size()); } @Test public void relationalPath_ne2() { assertEquals(0, query().from(survey, survey2) .where(survey.ne(survey2)) .select(survey.id, survey2.id).fetch().size()); } @Test @ExcludeIn(SQLITE) public void right_join() throws SQLException { assertEquals(16, query().from(employee).rightJoin(employee2) .on(employee.superiorIdKey.on(employee2)) .select(employee.id, employee2.id).fetch().size()); } @Test @ExcludeIn(DERBY) public void round() { Expression<Double> expr = Expressions.numberTemplate(Double.class, "1.32"); assertEquals(Double.valueOf(1.0), firstResult(MathExpressions.round(expr))); assertEquals(Double.valueOf(1.3), firstResult(MathExpressions.round(expr, 1))); } @Test @ExcludeIn({SQLITE, DERBY}) public void rpad() { assertEquals("ab ", firstResult(StringExpressions.rpad(ConstantImpl.create("ab"), 4))); assertEquals("ab!!", firstResult(StringExpressions.rpad(ConstantImpl.create("ab"), 4, '!'))); } @Test @Ignore @ExcludeIn({ORACLE, DERBY, SQLSERVER}) public void select_booleanExpr() throws SQLException { // TODO : FIXME System.out.println(query().from(survey).select(survey.id.eq(0)).fetch()); } @Test @Ignore @ExcludeIn({ORACLE, DERBY, SQLSERVER}) public void select_booleanExpr2() throws SQLException { // TODO : FIXME System.out.println(query().from(survey).select(survey.id.gt(0)).fetch()); } @Test public void select_booleanExpr3() { assertTrue(query().select(Expressions.TRUE).fetchFirst()); assertFalse(query().select(Expressions.FALSE).fetchFirst()); } @Test public void select_concat() throws SQLException { for (Tuple row : query().from(survey).select(survey.name, survey.name.append("Hello World")).fetch()) { assertEquals( row.get(survey.name) + "Hello World", row.get(survey.name.append("Hello World"))); } } @Test @ExcludeIn({SQLITE, CUBRID, TERADATA}) public void select_for_update() { assertEquals(1, query().from(survey).forUpdate().select(survey.id).fetch().size()); } @Test @ExcludeIn({SQLITE, CUBRID, TERADATA}) public void select_for_update_Where() { assertEquals(1, query().from(survey).forUpdate().where(survey.id.isNotNull()).select(survey.id).fetch().size()); } @Test @ExcludeIn({SQLITE, CUBRID, TERADATA}) public void select_for_update_UniqueResult() { query().from(survey).forUpdate().select(survey.id).fetchOne(); } @Test public void select_for_share() { if (configuration.getTemplates().isForShareSupported()) { assertEquals(1, query().from(survey).forShare().where(survey.id.isNotNull()).select(survey.id).fetch().size()); } else { try { query().from(survey).forShare().where(survey.id.isNotNull()).select(survey.id).fetch().size(); fail(); } catch (QueryException e) { assertTrue(e.getMessage().equals("Using forShare() is not supported")); } } } @Test @SkipForQuoted public void serialization() { SQLQuery<?> query = query(); query.from(survey); assertEquals("from SURVEY s", query.toString()); query.from(survey2); assertEquals("from SURVEY s, SURVEY s2", query.toString()); } @Test public void serialization2() throws Exception { List<Tuple> rows = query().from(survey).select(survey.id, survey.name).fetch(); serialize(rows); } private void serialize(List<Tuple> rows) throws IOException, ClassNotFoundException { rows = Serialization.serialize(rows); for (Tuple row : rows) { row.hashCode(); } } @Test public void single() { assertNotNull(query().from(survey).select(survey.name).fetchFirst()); } @Test public void single_array() { assertNotNull(query().from(survey).select(new Expression<?>[]{survey.name}).fetchFirst()); } @Test public void single_column() { // single column for (String s : query().from(survey).select(survey.name).fetch()) { assertNotNull(s); } } @Test public void single_column_via_Object_type() { for (Object s : query().from(survey) .select(ExpressionUtils.path(Object.class, survey.name.getMetadata())).fetch()) { assertEquals(String.class, s.getClass()); } } @Test public void specialChars() { assertEquals(0, query().from(survey).where(survey.name.in("\n", "\r", "\\", "\'", "\"")).fetchCount()); } @Test public void standardTest() { standardTest.runBooleanTests(employee.firstname.isNull(), employee2.lastname.isNotNull()); // datetime standardTest.runDateTests(employee.datefield, employee2.datefield, date); // numeric standardTest.runNumericCasts(employee.id, employee2.id, 1); standardTest.runNumericTests(employee.id, employee2.id, 1); // BigDecimal standardTest.runNumericTests(employee.salary, employee2.salary, new BigDecimal("30000.00")); standardTest.runStringTests(employee.firstname, employee2.firstname, "Jennifer"); Target target = Connections.getTarget(); if (target != SQLITE && target != SQLSERVER) { // jTDS driver does not support TIME SQL data type standardTest.runTimeTests(employee.timefield, employee2.timefield, time); } standardTest.report(); } @Test @IncludeIn(H2) public void standardTest_turkish() { Locale defaultLocale = Locale.getDefault(); Locale.setDefault(new Locale("tr", "TR")); try { standardTest(); } finally { Locale.setDefault(defaultLocale); } } @Test @ExcludeIn(SQLITE) public void string() { StringExpression str = Expressions.stringTemplate("' abcd '"); assertEquals("abcd ", firstResult(StringExpressions.ltrim(str))); assertEquals(Integer.valueOf(3), firstResult(str.locate("a"))); assertEquals(Integer.valueOf(0), firstResult(str.locate("a", 4))); assertEquals(Integer.valueOf(4), firstResult(str.locate("b", 2))); assertEquals(" abcd", firstResult(StringExpressions.rtrim(str))); assertEquals("abc", firstResult(str.substring(2, 5))); } @Test @ExcludeIn(SQLITE) public void string_withTemplate() { StringExpression str = Expressions.stringTemplate("' abcd '"); NumberExpression<Integer> four = Expressions.numberTemplate(Integer.class, "4"); NumberExpression<Integer> two = Expressions.numberTemplate(Integer.class, "2"); NumberExpression<Integer> five = Expressions.numberTemplate(Integer.class, "5"); assertEquals("abcd ", firstResult(StringExpressions.ltrim(str))); assertEquals(Integer.valueOf(3), firstResult(str.locate("a"))); assertEquals(Integer.valueOf(0), firstResult(str.locate("a", four))); assertEquals(Integer.valueOf(4), firstResult(str.locate("b", two))); assertEquals(" abcd", firstResult(StringExpressions.rtrim(str))); assertEquals("abc", firstResult(str.substring(two, five))); } @Test @ExcludeIn({POSTGRESQL, SQLITE}) public void string_indexOf() { StringExpression str = Expressions.stringTemplate("' abcd '"); assertEquals(Integer.valueOf(2), firstResult(str.indexOf("a"))); assertEquals(Integer.valueOf(-1), firstResult(str.indexOf("a", 4))); assertEquals(Integer.valueOf(3), firstResult(str.indexOf("b", 2))); } @Test public void stringFunctions2() throws SQLException { for (BooleanExpression where : Arrays.asList( employee.firstname.startsWith("a"), employee.firstname.startsWithIgnoreCase("a"), employee.firstname.endsWith("a"), employee.firstname.endsWithIgnoreCase("a"))) { query().from(employee).where(where).select(employee.firstname).fetch(); } } @Test @ExcludeIn(SQLITE) public void string_left() { assertEquals("John", query().from(employee).where(employee.lastname.eq("Johnson")) .select(SQLExpressions.left(employee.lastname, 4)).fetchFirst()); } @Test @ExcludeIn({DERBY, SQLITE}) public void string_right() { assertEquals("son", query().from(employee).where(employee.lastname.eq("Johnson")) .select(SQLExpressions.right(employee.lastname, 3)).fetchFirst()); } @Test @ExcludeIn({DERBY, SQLITE}) public void string_left_Right() { assertEquals("hn", query().from(employee).where(employee.lastname.eq("Johnson")) .select(SQLExpressions.right(SQLExpressions.left(employee.lastname, 4), 2)).fetchFirst()); } @Test @ExcludeIn({DERBY, SQLITE}) public void string_right_Left() { assertEquals("ns", query().from(employee).where(employee.lastname.eq("Johnson")) .select(SQLExpressions.left(SQLExpressions.right(employee.lastname, 4), 2)).fetchFirst()); } @Test @ExcludeIn({DB2, DERBY, FIREBIRD}) public void substring() { //SELECT * FROM account where SUBSTRING(name, -x, 1) = SUBSTRING(name, -y, 1) query().from(employee) .where(employee.firstname.substring(-3, 1).eq(employee.firstname.substring(-2, 1))) .select(employee.id).fetch(); } @Test public void syntax_for_employee() throws SQLException { assertEquals(3, query().from(employee).groupBy(employee.superiorId) .orderBy(employee.superiorId.asc()) .select(employee.salary.avg(), employee.id.max()).fetch().size()); assertEquals(2, query().from(employee).groupBy(employee.superiorId) .having(employee.id.max().gt(5)) .orderBy(employee.superiorId.asc()) .select(employee.salary.avg(), employee.id.max()).fetch().size()); assertEquals(2, query().from(employee).groupBy(employee.superiorId) .having(employee.superiorId.isNotNull()) .orderBy(employee.superiorId.asc()) .select(employee.salary.avg(), employee.id.max()).fetch().size()); } @Test public void templateExpression() { NumberExpression<Integer> one = Expressions.numberTemplate(Integer.class, "1"); assertEquals(Collections.singletonList(1), query().from(survey).select(one.as("col1")).fetch()); } @Test public void transform_groupBy() { QEmployee employee = new QEmployee("employee"); QEmployee employee2 = new QEmployee("employee2"); Map<Integer, Map<Integer, Employee>> results = query().from(employee, employee2) .transform(GroupBy.groupBy(employee.id).as(GroupBy.map(employee2.id, employee2))); int count = (int) query().from(employee).fetchCount(); assertEquals(count, results.size()); for (Map.Entry<Integer, Map<Integer, Employee>> entry : results.entrySet()) { Map<Integer, Employee> employees = entry.getValue(); assertEquals(count, employees.size()); } } @Test public void tuple_projection() { List<Tuple> tuples = query().from(employee) .select(employee.firstname, employee.lastname).fetch(); assertFalse(tuples.isEmpty()); for (Tuple tuple : tuples) { assertNotNull(tuple.get(employee.firstname)); assertNotNull(tuple.get(employee.lastname)); } } @Test @ExcludeIn({DB2, DERBY}) public void tuple2() { assertEquals(10, query().from(employee) .select(Expressions.as(ConstantImpl.create("1"), "code"), employee.id).fetch().size()); } @Test public void twoColumns() { // two columns for (Tuple row : query().from(survey).select(survey.id, survey.name).fetch()) { assertEquals(2, row.size()); assertEquals(Integer.class, row.get(0, Object.class).getClass()); assertEquals(String.class, row.get(1, Object.class).getClass()); } } @Test public void twoColumns_and_projection() { // two columns and projection for (Tuple row : query().from(survey) .select(survey.id, survey.name, new QIdName(survey.id, survey.name)).fetch()) { assertEquals(3, row.size()); assertEquals(Integer.class, row.get(0, Object.class).getClass()); assertEquals(String.class, row.get(1, Object.class).getClass()); assertEquals(IdName.class, row.get(2, Object.class).getClass()); } } @Test public void unique_Constructor_projection() { IdName idAndName = query().from(survey).limit(1).select(new QIdName(survey.id, survey.name)).fetchFirst(); assertNotNull(idAndName); assertNotNull(idAndName.getId()); assertNotNull(idAndName.getName()); } @Test public void unique_single() { String s = query().from(survey).limit(1).select(survey.name).fetchFirst(); assertNotNull(s); } @Test public void unique_wildcard() { // unique wildcard Tuple row = query().from(survey).limit(1).select(survey.all()).fetchFirst(); assertNotNull(row); assertEquals(3, row.size()); assertNotNull(row.get(0, Object.class)); assertNotNull(row.get(0, Object.class) + " is not null", row.get(1, Object.class)); } @Test(expected = NonUniqueResultException.class) public void uniqueResultContract() { query().from(employee).select(employee.all()).fetchOne(); } @Test public void various() throws SQLException { for (String s : query().from(survey).select(survey.name.lower()).fetch()) { assertEquals(s, s.toLowerCase()); } for (String s : query().from(survey).select(survey.name.append("abc")).fetch()) { assertTrue(s.endsWith("abc")); } System.out.println(query().from(survey).select(survey.id.sqrt()).fetch()); } @Test public void where_exists() throws SQLException { SQLQuery<Integer> sq1 = query().from(employee).select(employee.id.max()); assertEquals(10, query().from(employee).where(sq1.exists()).fetchCount()); } @Test public void where_exists_Not() throws SQLException { SQLQuery<Integer> sq1 = query().from(employee).select(employee.id.max()); assertEquals(0, query().from(employee).where(sq1.exists().not()).fetchCount()); } @Test @IncludeIn({HSQLDB, ORACLE, POSTGRESQL}) public void with() { assertEquals(10, query().with(employee2, query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .from(employee, employee2) .select(employee.id, employee2.id).fetch().size()); } @Test @IncludeIn({HSQLDB, ORACLE, POSTGRESQL}) public void with2() { QEmployee employee3 = new QEmployee("e3"); assertEquals(100, query().with(employee2, query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .with(employee2, query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .from(employee, employee2, employee3) .select(employee.id, employee2.id, employee3.id).fetch().size()); } @Test @IncludeIn({HSQLDB, ORACLE, POSTGRESQL}) public void with3() { assertEquals(10, query().with(employee2, employee2.all()).as( query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .from(employee, employee2) .select(employee.id, employee2.id).fetch().size()); } @Test @IncludeIn({HSQLDB, ORACLE, POSTGRESQL}) public void with_limit() { assertEquals(5, query().with(employee2, employee2.all()).as( query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .from(employee, employee2) .limit(5) .orderBy(employee.id.asc(), employee2.id.asc()) .select(employee.id, employee2.id).fetch().size()); } @Test @IncludeIn({HSQLDB, ORACLE, POSTGRESQL}) public void with_limitOffset() { assertEquals(5, query().with(employee2, employee2.all()).as( query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .from(employee, employee2) .limit(10) .offset(5) .orderBy(employee.id.asc(), employee2.id.asc()) .select(employee.id, employee2.id).fetch().size()); } @Test @IncludeIn({ORACLE, POSTGRESQL}) public void with_recursive() { assertEquals(10, query().withRecursive(employee2, query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .from(employee, employee2) .select(employee.id, employee2.id).fetch().size()); } @Test @IncludeIn({ORACLE, POSTGRESQL}) public void with_recursive2() { assertEquals(10, query().withRecursive(employee2, employee2.all()).as( query().from(employee) .where(employee.firstname.eq("Jim")) .select(Wildcard.all)) .from(employee, employee2) .select(employee.id, employee2.id).fetch().size()); } @Test public void wildcard() { // wildcard for (Tuple row : query().from(survey).select(survey.all()).fetch()) { assertNotNull(row); assertEquals(3, row.size()); assertNotNull(row.get(0, Object.class)); assertNotNull(row.get(0, Object.class) + " is not null", row.get(1, Object.class)); } } @Test @SkipForQuoted public void wildcard_all() { expectedQuery = "select * from EMPLOYEE e"; query().from(employee).select(Wildcard.all).fetch(); } @Test public void wildcard_all2() { assertEquals(10, query().from(new RelationalPathBase<Object>(Object.class, "employee", "public", "EMPLOYEE")) .select(Wildcard.all).fetch().size()); } @Test public void wildcard_and_qTuple() { // wildcard and QTuple for (Tuple tuple : query().from(survey).select(survey.all()).fetch()) { assertNotNull(tuple.get(survey.id)); assertNotNull(tuple.get(survey.name)); } } @Test @IncludeIn(ORACLE) public void withinGroup() { List<WithinGroup<?>> exprs = new ArrayList<WithinGroup<?>>(); NumberPath<Integer> path = survey.id; // two args add(exprs, SQLExpressions.cumeDist(2, 3)); add(exprs, SQLExpressions.denseRank(4, 5)); add(exprs, SQLExpressions.listagg(path, ",")); add(exprs, SQLExpressions.percentRank(6, 7)); add(exprs, SQLExpressions.rank(8, 9)); for (WithinGroup<?> wg : exprs) { query().from(survey).select(wg.withinGroup().orderBy(survey.id, survey.id)).fetch(); query().from(survey).select(wg.withinGroup().orderBy(survey.id.asc(), survey.id.asc())).fetch(); } // one arg exprs.clear(); add(exprs, SQLExpressions.percentileCont(0.1)); add(exprs, SQLExpressions.percentileDisc(0.9)); for (WithinGroup<?> wg : exprs) { query().from(survey).select(wg.withinGroup().orderBy(survey.id)).fetch(); query().from(survey).select(wg.withinGroup().orderBy(survey.id.asc())).fetch(); } } @Test @ExcludeIn({DB2, DERBY, H2}) public void yearWeek() { SQLQuery<?> query = query().from(employee).orderBy(employee.id.asc()); assertEquals(Integer.valueOf(200006), query.select(employee.datefield.yearWeek()).fetchFirst()); } @Test @IncludeIn({H2}) public void yearWeek_h2() { SQLQuery<?> query = query().from(employee).orderBy(employee.id.asc()); assertEquals(Integer.valueOf(200007), query.select(employee.datefield.yearWeek()).fetchFirst()); } @Test public void statementOptions() { StatementOptions options = StatementOptions.builder().setFetchSize(15).setMaxRows(150).build(); SQLQuery<?> query = query().from(employee).orderBy(employee.id.asc()); query.setStatementOptions(options); query.addListener(new SQLBaseListener() { public void preExecute(SQLListenerContext context) { try { assertEquals(15, context.getPreparedStatement().getFetchSize()); assertEquals(150, context.getPreparedStatement().getMaxRows()); } catch (SQLException e) { throw new RuntimeException(e); } } }); query.select(employee.id).fetch(); } @Test public void getResults() throws SQLException, InterruptedException { final AtomicLong endCalled = new AtomicLong(0); SQLQuery<Integer> query = query().select(employee.id).from(employee); query.addListener(new SQLBaseListener() { @Override public void end(SQLListenerContext context) { endCalled.set(System.currentTimeMillis()); } }); ResultSet results = query.getResults(employee.id); long getResultsCalled = System.currentTimeMillis(); Thread.sleep(100); results.close(); assertTrue(endCalled.get() - getResultsCalled >= 100); } @Test @ExcludeIn({DB2, DERBY, ORACLE, SQLSERVER}) public void groupConcat() { List<String> expected = Arrays.asList("Mike,Mary", "Joe,Peter,Steve,Jim", "Jennifer,Helen,Daisy,Barbara"); if (Connections.getTarget() == POSTGRESQL) { expected = Arrays.asList("Steve,Jim,Joe,Peter", "Barbara,Helen,Daisy,Jennifer", "Mary,Mike"); } assertEquals( expected, query().select(SQLExpressions.groupConcat(employee.firstname)) .from(employee) .groupBy(employee.superiorId).fetch()); } @Test @ExcludeIn({DB2, DERBY, ORACLE, SQLSERVER}) public void groupConcat2() { List<String> expected = Arrays.asList("Mike-Mary", "Joe-Peter-Steve-Jim", "Jennifer-Helen-Daisy-Barbara"); if (Connections.getTarget() == POSTGRESQL) { expected = Arrays.asList("Steve-Jim-Joe-Peter", "Barbara-Helen-Daisy-Jennifer", "Mary-Mike"); } assertEquals( expected, query().select(SQLExpressions.groupConcat(employee.firstname, "-")) .from(employee) .groupBy(employee.superiorId).fetch()); } } //CHECKSTYLERULE:ON: FileLength
lpandzic/querydsl
querydsl-sql/src/test/java/com/querydsl/sql/SelectBase.java
Java
apache-2.0
83,403
package frommikesdesk.rest.reponse; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Michael Silveus <[email protected]> */ @XmlRootElement(name = "response") public class GenericResponse { private boolean status; private String message; private String errorCode; public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } @Override public String toString() { return status + "|" + message + "|" + errorCode; } public void setSuccessfulResult(String message) { this.message = message; this.status = true; this.errorCode = "0"; } }
msilveus/resteasy-template
src/frommikesdesk/rest/reponse/GenericResponse.java
Java
apache-2.0
922
package com.fasterxml.jackson.databind.ext; import java.text.DateFormat; import java.text.SimpleDateFormat; import com.fasterxml.jackson.databind.*; public class SqlTimestampDeserializationTest extends BaseMapTest { private final ObjectMapper MAPPER = newJsonMapper(); // As for TestDateDeserialization except we don't need to test date conversion routines, so // just check we pick up timestamp class public void testTimestampUtil() throws Exception { long now = 123456789L; java.sql.Timestamp value = new java.sql.Timestamp(now); // First from long assertEquals(value, MAPPER.readValue(""+now, java.sql.Timestamp.class)); String dateStr = serializeTimestampAsString(value); java.sql.Timestamp result = MAPPER.readValue("\""+dateStr+"\"", java.sql.Timestamp.class); assertEquals("Date: expect "+value+" ("+value.getTime()+"), got "+result+" ("+result.getTime()+")", value.getTime(), result.getTime()); } public void testTimestampUtilSingleElementArray() throws Exception { final ObjectReader r = MAPPER.readerFor(java.sql.Timestamp.class) .with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); long now = System.currentTimeMillis(); java.sql.Timestamp value = new java.sql.Timestamp(now); // First from long assertEquals(value, r.readValue("["+now+"]")); String dateStr = serializeTimestampAsString(value); java.sql.Timestamp result = r.readValue("[\""+dateStr+"\"]"); assertEquals("Date: expect "+value+" ("+value.getTime()+"), got "+result+" ("+result.getTime()+")", value.getTime(), result.getTime()); } /* /********************************************************** /* Helper methods /********************************************************** */ private String serializeTimestampAsString(java.sql.Timestamp value) { /* Then from String. This is bit tricky, since JDK does not really * suggest a 'standard' format. So let's try using something... */ DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); return df.format(value); } }
FasterXML/jackson-databind
src/test/java/com/fasterxml/jackson/databind/ext/SqlTimestampDeserializationTest.java
Java
apache-2.0
2,229
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.helianto.user.repository; /** * The provided signin name could not be mapped. * * @author mauriciofernandesdecastro */ @SuppressWarnings("serial") public final class UserKeyNotFoundException extends RemoteUserException { private final String username; public UserKeyNotFoundException(String principal) { super("Principal not found"); this.username = principal; } public String getUsername() { return username; } }
chmulato/helianto-seed
src/main/java/org/helianto/user/repository/UserKeyNotFoundException.java
Java
apache-2.0
1,104
/* * 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.sis.referencing.operation.builder; import java.util.Map; import java.util.HashMap; import java.util.Random; import java.awt.geom.AffineTransform; import org.opengis.util.FactoryException; import org.opengis.referencing.operation.Matrix; import org.apache.sis.geometry.DirectPosition1D; import org.apache.sis.geometry.DirectPosition2D; import org.apache.sis.test.DependsOnMethod; import org.apache.sis.test.TestUtilities; import org.apache.sis.test.TestCase; import org.junit.Test; import static org.junit.Assert.*; /** * Tests {@link LinearTransformBuilder}. * * @author Martin Desruisseaux (Geomatys) * @version 0.8 * @since 0.5 * @module */ public final strictfp class LinearTransformBuilderTest extends TestCase { /** * Tests a very simple case where an exact answer is expected. * * @throws FactoryException if the transform can not be created. */ @Test public void testMinimalist1D() throws FactoryException { final LinearTransformBuilder builder = new LinearTransformBuilder(); final Map<DirectPosition1D,DirectPosition1D> pos = new HashMap<>(4); assertNull(pos.put(new DirectPosition1D(1), new DirectPosition1D(1))); assertNull(pos.put(new DirectPosition1D(2), new DirectPosition1D(3))); builder.setControlPoints(pos); assertArrayEquals(new double[] {1}, builder.getControlPoint(new int[] {1}), STRICT); assertArrayEquals(new double[] {3}, builder.getControlPoint(new int[] {2}), STRICT); assertNull( builder.getControlPoint(new int[] {3})); final Matrix m = builder.create(null).getMatrix(); assertEquals("m₀₀", 2, m.getElement(0, 0), STRICT); assertEquals("m₀₁", -1, m.getElement(0, 1), STRICT); assertArrayEquals("correlation", new double[] {1}, builder.correlation(), STRICT); } /** * Tests a very simple case where an exact answer is expected. * Tolerance threshold is set to zero because the math transform has been built from exactly 3 points, * in which case we expect an exact solution without rounding errors at the scale of the {@code double} * type. This is possible because SIS implementation uses double-double arithmetic. * * @throws FactoryException if the transform can not be created. */ @Test public void testMinimalist2D() throws FactoryException { final Map<DirectPosition2D,DirectPosition2D> pos = new HashMap<>(8); assertNull(pos.put(new DirectPosition2D(1, 1), new DirectPosition2D(3, 2))); assertNull(pos.put(new DirectPosition2D(1, 2), new DirectPosition2D(3, 5))); assertNull(pos.put(new DirectPosition2D(2, 2), new DirectPosition2D(5, 5))); final LinearTransformBuilder builder = new LinearTransformBuilder(); builder.setControlPoints(pos); assertArrayEquals(new double[] {3, 2}, builder.getControlPoint(new int[] {1, 1}), STRICT); assertArrayEquals(new double[] {3, 5}, builder.getControlPoint(new int[] {1, 2}), STRICT); assertArrayEquals(new double[] {5, 5}, builder.getControlPoint(new int[] {2, 2}), STRICT); assertNull( builder.getControlPoint(new int[] {2, 1})); final Matrix m = builder.create(null).getMatrix(); // First row (x) assertEquals("m₀₀", 2, m.getElement(0, 0), STRICT); assertEquals("m₀₁", 0, m.getElement(0, 1), STRICT); assertEquals("m₀₂", 1, m.getElement(0, 2), STRICT); // Second row (y) assertEquals("m₁₀", 0, m.getElement(1, 0), STRICT); assertEquals("m₁₁", 3, m.getElement(1, 1), STRICT); assertEquals("m₁₂", -1, m.getElement(1, 2), STRICT); assertArrayEquals("correlation", new double[] {1, 1}, builder.correlation(), STRICT); } /** * Tests a two-dimensional case where sources coordinates are explicitely given. * * @throws FactoryException if the transform can not be created. * * @since 0.8 */ @Test public void testExplicitSource2D() throws FactoryException { testSetAllPoints(new LinearTransformBuilder()); testSetEachPoint(new LinearTransformBuilder()); } /** * Same test than {@link #testExplicitSource2D()}, but using the * {@link LinearTransformBuilder#LinearTransformBuilder(int...)} constructor. * * @throws FactoryException if the transform can not be created. * * @since 0.8 */ @Test @DependsOnMethod("testExplicitSource2D") public void testImplicitSource2D() throws FactoryException { testSetAllPoints(new LinearTransformBuilder(2, 3)); testSetEachPoint(new LinearTransformBuilder(2, 3)); } /** * Execution of {@link #testExplicitSource2D()} and {@link #testImplicitSource2D()} * where all control points are specified by a map. */ private void testSetAllPoints(final LinearTransformBuilder builder) throws FactoryException { final Map<DirectPosition2D,DirectPosition2D> pos = new HashMap<>(8); assertNull(pos.put(new DirectPosition2D(0, 0), new DirectPosition2D(3, 9))); assertNull(pos.put(new DirectPosition2D(0, 1), new DirectPosition2D(4, 7))); assertNull(pos.put(new DirectPosition2D(0, 2), new DirectPosition2D(6, 6))); assertNull(pos.put(new DirectPosition2D(1, 0), new DirectPosition2D(4, 8))); assertNull(pos.put(new DirectPosition2D(1, 1), new DirectPosition2D(5, 4))); assertNull(pos.put(new DirectPosition2D(1, 2), new DirectPosition2D(8, 2))); builder.setControlPoints(pos); verify(builder); } /** * Execution of {@link #testExplicitSource2D()} and {@link #testImplicitSource2D()} * where all control points are specified one-by-one. */ private void testSetEachPoint(final LinearTransformBuilder builder) throws FactoryException { builder.setControlPoint(new int[] {0, 0}, new double[] {3, 9}); builder.setControlPoint(new int[] {0, 1}, new double[] {4, 7}); builder.setControlPoint(new int[] {0, 2}, new double[] {6, 6}); builder.setControlPoint(new int[] {1, 0}, new double[] {4, 8}); builder.setControlPoint(new int[] {1, 1}, new double[] {5, 4}); builder.setControlPoint(new int[] {1, 2}, new double[] {8, 2}); verify(builder); } /** * Verifies the transform created by {@link #testExplicitSource2D()} and {@link #testImplicitSource2D()}. */ private void verify(final LinearTransformBuilder builder) throws FactoryException { final Matrix m = builder.create(null).getMatrix(); assertArrayEquals(new double[] {3, 9}, builder.getControlPoint(new int[] {0, 0}), STRICT); assertArrayEquals(new double[] {4, 7}, builder.getControlPoint(new int[] {0, 1}), STRICT); assertArrayEquals(new double[] {6, 6}, builder.getControlPoint(new int[] {0, 2}), STRICT); assertArrayEquals(new double[] {4, 8}, builder.getControlPoint(new int[] {1, 0}), STRICT); assertArrayEquals(new double[] {5, 4}, builder.getControlPoint(new int[] {1, 1}), STRICT); assertArrayEquals(new double[] {8, 2}, builder.getControlPoint(new int[] {1, 2}), STRICT); /* * Expect STRICT results because Apache SIS uses double-double arithmetic. */ assertEquals("m₀₀", 16 / 12d, m.getElement(0, 0), STRICT); // First row (x) assertEquals("m₀₁", 21 / 12d, m.getElement(0, 1), STRICT); assertEquals("m₀₂", 31 / 12d, m.getElement(0, 2), STRICT); assertEquals("m₁₀", -32 / 12d, m.getElement(1, 0), STRICT); // Second row (y) assertEquals("m₁₁", -27 / 12d, m.getElement(1, 1), STRICT); assertEquals("m₁₂", 115 / 12d, m.getElement(1, 2), STRICT); assertArrayEquals("correlation", new double[] {0.9656, 0.9536}, builder.correlation(), 0.0001); } /** * Tests with a random number of points with an exact solution expected. * * @throws FactoryException if the transform can not be created. */ @Test @DependsOnMethod("testMinimalist1D") public void testExact1D() throws FactoryException { final Random rd = TestUtilities.createRandomNumberGenerator(-6080923837183751016L); for (int i=0; i<10; i++) { test1D(rd, rd.nextInt(900) + 100, false, 1E-14, 1E-12); } } /** * Tests with a random number of points with an exact solution expected. * * <p><b>Note:</b> this test can pass with a random seed most of the time. But we fix the seed anyway * because there is always a small probability that truly random points are all colinear, in which case * the test would fail. Even if the probability is low, we do not take the risk of random build failures.</p> * * @throws FactoryException if the transform can not be created. */ @Test @DependsOnMethod("testMinimalist2D") public void testExact2D() throws FactoryException { final Random rd = TestUtilities.createRandomNumberGenerator(41632405806929L); for (int i=0; i<10; i++) { test2D(rd, rd.nextInt(900) + 100, false, 1E-14, 1E-12); } } /** * Tests with a random number of points and a random errors in target points. * * @throws FactoryException if the transform can not be created. */ @Test @DependsOnMethod("testExact1D") public void testNonExact1D() throws FactoryException { final Random rd = TestUtilities.createRandomNumberGenerator(8819436190826166876L); for (int i=0; i<4; i++) { test1D(rd, rd.nextInt(900) + 100, true, 0.02, 0.5); } } /** * Tests with a random number of points and a random errors in target points. * * <p><b>Note:</b> this test can pass with a random seed most of the time. But we fix the seed anyway * because there is always a small probability that truly random points are all colinear, or that lot * of errors are in the same directions (thus introducing a larger bias than expected), in which case * the test would fail. Even if the probability is low, we do not take the risk of such random build * failures.</p> * * @throws FactoryException if the transform can not be created. */ @Test @DependsOnMethod("testExact2D") public void testNonExact2D() throws FactoryException { final Random rd = TestUtilities.createRandomNumberGenerator(270575025643864L); for (int i=0; i<4; i++) { test2D(rd, rd.nextInt(900) + 100, true, 0.02, 0.5); } } /** * Implementation of {@link #testExact1D()} and {@link #testNonExact1D()}. * * @param rd the random number generator to use. * @param numPts the number of points to generate. * @param addErrors {@code true} for adding a random error in the target points. * @param scaleTolerance tolerance threshold for floating point comparisons. */ private static void test1D(final Random rd, final int numPts, final boolean addErrors, final double scaleTolerance, final double translationTolerance) throws FactoryException { final double scale = rd.nextDouble() * 30 - 12; final double offset = rd.nextDouble() * 10 - 4; final Map<DirectPosition1D,DirectPosition1D> pos = new HashMap<>(numPts); for (int i=0; i<numPts; i++) { final DirectPosition1D src = new DirectPosition1D(rd.nextDouble() * 100 - 50); final DirectPosition1D tgt = new DirectPosition1D(src.ordinate * scale + offset); if (addErrors) { tgt.ordinate += rd.nextDouble() * 10 - 5; } assertNull(pos.put(src, tgt)); } /* * Create the fitted transform to test. */ final LinearTransformBuilder builder = new LinearTransformBuilder(); builder.setControlPoints(pos); final Matrix m = builder.create(null).getMatrix(); assertEquals("m₀₀", scale, m.getElement(0, 0), scaleTolerance); assertEquals("m₀₁", offset, m.getElement(0, 1), translationTolerance); assertEquals("correlation", 1, StrictMath.abs(builder.correlation()[0]), scaleTolerance); } /** * Implementation of {@link #testExact2D()} and {@link #testNonExact2D()}. * * @param rd the random number generator to use. * @param numPts the number of points to generate. * @param addErrors {@code true} for adding a random error in the target points. * @param scaleTolerance tolerance threshold for floating point comparisons. */ private static void test2D(final Random rd, final int numPts, final boolean addErrors, final double scaleTolerance, final double translationTolerance) throws FactoryException { /* * Create an AffineTransform to use as the reference implementation. */ final AffineTransform ref = AffineTransform.getRotateInstance( rd.nextDouble() * (2 * StrictMath.PI), // Rotation angle rd.nextDouble() * 30 - 12, // Center X rd.nextDouble() * 10 - 8); // Center Y final Map<DirectPosition2D,DirectPosition2D> pos = new HashMap<>(numPts); for (int i=0; i<numPts; i++) { final DirectPosition2D src = new DirectPosition2D(rd.nextDouble() * 100 - 50, rd.nextDouble() * 200 - 75); final DirectPosition2D tgt = new DirectPosition2D(); assertSame(tgt, ref.transform(src, tgt)); if (addErrors) { tgt.x += rd.nextDouble() * 10 - 5; tgt.y += rd.nextDouble() * 10 - 5; } assertNull(pos.put(src, tgt)); } /* * Create the fitted transform to test. */ final LinearTransformBuilder builder = new LinearTransformBuilder(); builder.setControlPoints(pos); final Matrix m = builder.create(null).getMatrix(); /* * Compare the coefficients with the reference implementation. */ assertEquals("m₀₀", ref.getScaleX(), m.getElement(0, 0), scaleTolerance); assertEquals("m₀₁", ref.getShearX(), m.getElement(0, 1), scaleTolerance); assertEquals("m₀₂", ref.getTranslateX(), m.getElement(0, 2), translationTolerance); assertEquals("m₁₀", ref.getShearY(), m.getElement(1, 0), scaleTolerance); assertEquals("m₁₁", ref.getScaleY(), m.getElement(1, 1), scaleTolerance); assertEquals("m₁₂", ref.getTranslateY(), m.getElement(1, 2), translationTolerance); assertArrayEquals("correlation", new double[] {1, 1}, builder.correlation(), scaleTolerance); } }
Geomatys/sis
core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/builder/LinearTransformBuilderTest.java
Java
apache-2.0
15,744
/* * Copyright 2013-present Facebook, 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.facebook.buck.step; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.testutil.TestConsole; import com.facebook.buck.util.Verbosity; import java.io.IOException; import java.util.Optional; import org.junit.Before; import org.junit.Test; public class StepFailedExceptionTest { private ExecutionContext verboseContext; private ExecutionContext silentContext; @Before public void setUp() { ExecutionContext context = TestExecutionContext.newInstance(); verboseContext = context.withConsole(new TestConsole(Verbosity.ALL)); silentContext = context.withConsole(new TestConsole(Verbosity.SILENT)); } @Test public void testCreateForFailingStepForExitCodeWithBuildTarget() { int exitCode = 17; StepExecutionResult executionResult = StepExecutionResult.of(exitCode); Step step = new FakeStep("cp", "cp foo bar", exitCode); BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar"); StepFailedException exception = StepFailedException.createForFailingStepWithExitCode( step, verboseContext, executionResult, Optional.of(buildTarget)); assertEquals(step, exception.getStep()); assertEquals( "Command failed with exit code 17.\n" + " When running <cp foo bar>.", exception.getMessage()); } @Test public void testCreateForFailingStepForExitCodeWithoutBuildTarget() { int exitCode = 17; StepExecutionResult executionResult = StepExecutionResult.of(exitCode); Step step = new FakeStep("cp", "cp foo bar", exitCode); StepFailedException exception = StepFailedException.createForFailingStepWithExitCode( step, verboseContext, executionResult, Optional.empty()); assertEquals(step, exception.getStep()); assertEquals( "Command failed with exit code 17.\n" + " When running <cp foo bar>.", exception.getMessage()); } @Test public void testCreateForFailingStepWithSilentConsole() { int exitCode = 17; StepExecutionResult executionResult = StepExecutionResult.of(exitCode); Step step = new FakeStep("cp", "cp foo bar", exitCode); BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar"); StepFailedException exception = StepFailedException.createForFailingStepWithExitCode( step, silentContext, executionResult, Optional.of(buildTarget)); assertEquals(step, exception.getStep()); assertEquals( "Command failed with exit code 17.\n" + " When running <cp>.", exception.getMessage()); } @Test public void testCreateForFailingStepWithBuildTarget() { int exitCode = 17; Step step = new FakeStep("cp", "cp foo bar", exitCode); BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:bar"); StepFailedException exception = StepFailedException.createForFailingStepWithException( step, silentContext, new IOException("Copy failed!"), Optional.of(buildTarget)); assertEquals(step, exception.getStep()); assertTrue( exception.getMessage(), exception.getMessage().startsWith("Copy failed!\n" + " When running <cp>.")); } @Test public void testCreateForFailingStepWithoutBuildTarget() { int exitCode = 17; Step step = new FakeStep("cp", "cp foo bar", exitCode); StepFailedException exception = StepFailedException.createForFailingStepWithException( step, silentContext, new IOException("Copy failed!"), Optional.empty()); assertEquals(step, exception.getStep()); assertTrue( exception.getMessage(), exception.getMessage().startsWith("Copy failed!\n" + " When running <cp>.")); } }
LegNeato/buck
test/com/facebook/buck/step/StepFailedExceptionTest.java
Java
apache-2.0
4,429
package com.kns.adapter; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.kns.model.CustomRequestModel; import com.sunil.selectmutiple.R; public class CustomRequestAdapter extends BaseAdapter{ private final List<CustomRequestModel> list; private final Activity context; private LayoutInflater mInflater=null; ArrayList<CustomRequestModel> list1 = new ArrayList<CustomRequestModel>(); public CustomRequestAdapter(Activity context, List<CustomRequestModel> list) { // super(context, R.layout.listcheck, list); mInflater = context.getLayoutInflater(); this.context = context; this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int arg0) { return list.get(arg0); } @Override public long getItemId(int arg0) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null ) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.customrequest_row, null); holder.txt_name= (TextView)convertView.findViewById(R.id.textView_custname); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } CustomRequestModel model=list.get(position); String consumerid=model.getConsumerID(); String customname=model.getCustomName(); String customammount=model.getCustomAmount(); String customrequest=model.getCustomRequest(); String approvalflag=model.getApproval_Flag(); holder.txt_name.setText(customname); return convertView; } private static class ViewHolder { ImageView image; TextView txt_name; TextView txt_noofimage; } }
suniliet/AndroidWorkNew
GalleyUpload/src/com/kns/adapter/CustomRequestAdapter.java
Java
apache-2.0
1,953
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.2 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.opensim.modeling; /** * Implementation of a two state (activation and fiber-length) Muscle model by <br> * Thelen 2003.\ This a complete rewrite of a previous implementation (present in<br> * OpenSim 2.4 and earlier) contained numerous errors.<br> * <br> * The Thelen2003Muscle model uses a standard equilibrium muscle equation<br> * <br> * (a(t) f_{AL}(l_{CE}) f_{V}(\dot{l}_{CE}) - f_{PE}(l_{CE}))\cos \phi - f_{SE}(l_{T}) = 0 <br> * <br> * Rearranging the above equation and solving for f_{V}(\dot{l}_{CE}) <br> * yields<br> * <br> * f_{V}(\dot{l}_{CE}) = \frac{ \frac{f_{SE}(l_{T})}{\cos\phi} - f_{PE}(l_{CE}) }{ a(t) f_{AL}(l_{CE}) } <br> * <br> * The force velocity curve is usually inverted to compute the fiber velocity,<br> * <br> * \dot{l}_{CE} = f_{V}^{-1}( \frac{ \frac{f_{SE}(l_{T})}{\cos\phi} - f_{PE}(l_{CE}) }{ a(t) f_{AL}(l_{CE}) } ) <br> * <br> * which is then integrated to simulate the musculotendon dynamics. In general, <br> * the previous equation has 4 singularity conditions:<br> * <br> * -# a(t) \rightarrow 0 <br> * -# f_{AL}(l_{CE}) \rightarrow 0 <br> * -# \phi \rightarrow \frac{\pi}{2} <br> * -# f_{V}(\dot{l}_{CE}) \le 0 or <br> * f_{V}(\dot{l}_{CE}) \ge F^M_{len}<br> * <br> * This implementation has been slightly modified from the model presented in the <br> * journal paper (marked with a *) to prevent some of these singularities:<br> * <br> * -# * a(t) \rightarrow a_{min} > 0 : A modified activation dynamic <br> * equation is used - MuscleFirstOrderActivationDynamicModel - which smoothly <br> * approaches some minimum value that is greater than zero.<br> * -# f_{AL}(l_{CE}) > 0 . The active force length curve of the Thelen <br> * muscle is a Gaussian, which is always greater than 0.<br> * -# \phi \rightarrow \frac{\pi}{2} . This singularity cannot be removed <br> * without changing the first equation, and still exists in the present <br> * Thelen2003Muscle formulation.<br> * -# * f_{V}(\dot{l}_{CE}) \le 0 or <br> * f_{V}(\dot{l}_{CE}) \ge F^M_{len}: Equation 6 in Thelen 2003 has been <br> * modified so that V^M is linearly extrapolated when F^M < 0 <br> * (during a concentric contraction), and when F^M > 0.95 F^M_{len} <br> * (during an eccentric contraction). These two modifications make the force <br> * velocity curve invertible. The original force velocity curve as published <br> * by Thelen was not invertible. <br> * -# A unilateral constraint has been implemented to prevent the fiber from <br> * approaching a fiber length that is smaller than 0.01*optimal fiber length,<br> * or a fiber length that creates a pennation angle greater than the maximum <br> * pennation angle specified by the pennation model. Note that this unilateral <br> * constraint does not prevent the muscle fiber from becoming shorter than is <br> * physiologically possible (that is shorter than approximately half a <br> * normalized fiber length).<br> * <br> * <b> References </b><br> * <br> * DG Thelen, Adjustment of muscle mechanics model parameters to simulate dynamic <br> * contractions in older adults. Journal of biomechanical engineering, 2003.<br> * <br> * @author Matt Millard<br> * @author Ajay Seth<br> * @author Peter Loan */ public class Thelen2003Muscle extends ActivationFiberLengthMuscle { private transient long swigCPtr; public Thelen2003Muscle(long cPtr, boolean cMemoryOwn) { super(opensimSimulationJNI.Thelen2003Muscle_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } public static long getCPtr(Thelen2003Muscle obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; opensimSimulationJNI.delete_Thelen2003Muscle(swigCPtr); } swigCPtr = 0; } super.delete(); } public static Thelen2003Muscle safeDownCast(OpenSimObject obj) { long cPtr = opensimSimulationJNI.Thelen2003Muscle_safeDownCast(OpenSimObject.getCPtr(obj), obj); return (cPtr == 0) ? null : new Thelen2003Muscle(cPtr, false); } public void assign(OpenSimObject aObject) { opensimSimulationJNI.Thelen2003Muscle_assign(swigCPtr, this, OpenSimObject.getCPtr(aObject), aObject); } public static String getClassName() { return opensimSimulationJNI.Thelen2003Muscle_getClassName(); } public OpenSimObject clone() { long cPtr = opensimSimulationJNI.Thelen2003Muscle_clone(swigCPtr, this); return (cPtr == 0) ? null : new Thelen2003Muscle(cPtr, true); } public String getConcreteClassName() { return opensimSimulationJNI.Thelen2003Muscle_getConcreteClassName(swigCPtr, this); } public void copyProperty_FmaxTendonStrain(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_FmaxTendonStrain(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_FmaxTendonStrain(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_FmaxTendonStrain__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_FmaxTendonStrain(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_FmaxTendonStrain__SWIG_0(swigCPtr, this, i), false); } public void set_FmaxTendonStrain(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_FmaxTendonStrain__SWIG_0(swigCPtr, this, i, value); } public int append_FmaxTendonStrain(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_FmaxTendonStrain(swigCPtr, this, value); } public void constructProperty_FmaxTendonStrain(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_FmaxTendonStrain(swigCPtr, this, initValue); } public double get_FmaxTendonStrain() { return opensimSimulationJNI.Thelen2003Muscle_get_FmaxTendonStrain__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_FmaxTendonStrain() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_FmaxTendonStrain__SWIG_1(swigCPtr, this), false); } public void set_FmaxTendonStrain(double value) { opensimSimulationJNI.Thelen2003Muscle_set_FmaxTendonStrain__SWIG_1(swigCPtr, this, value); } public void copyProperty_FmaxMuscleStrain(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_FmaxMuscleStrain(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_FmaxMuscleStrain(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_FmaxMuscleStrain__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_FmaxMuscleStrain(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_FmaxMuscleStrain__SWIG_0(swigCPtr, this, i), false); } public void set_FmaxMuscleStrain(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_FmaxMuscleStrain__SWIG_0(swigCPtr, this, i, value); } public int append_FmaxMuscleStrain(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_FmaxMuscleStrain(swigCPtr, this, value); } public void constructProperty_FmaxMuscleStrain(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_FmaxMuscleStrain(swigCPtr, this, initValue); } public double get_FmaxMuscleStrain() { return opensimSimulationJNI.Thelen2003Muscle_get_FmaxMuscleStrain__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_FmaxMuscleStrain() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_FmaxMuscleStrain__SWIG_1(swigCPtr, this), false); } public void set_FmaxMuscleStrain(double value) { opensimSimulationJNI.Thelen2003Muscle_set_FmaxMuscleStrain__SWIG_1(swigCPtr, this, value); } public void copyProperty_KshapeActive(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_KshapeActive(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_KshapeActive(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_KshapeActive__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_KshapeActive(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_KshapeActive__SWIG_0(swigCPtr, this, i), false); } public void set_KshapeActive(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_KshapeActive__SWIG_0(swigCPtr, this, i, value); } public int append_KshapeActive(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_KshapeActive(swigCPtr, this, value); } public void constructProperty_KshapeActive(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_KshapeActive(swigCPtr, this, initValue); } public double get_KshapeActive() { return opensimSimulationJNI.Thelen2003Muscle_get_KshapeActive__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_KshapeActive() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_KshapeActive__SWIG_1(swigCPtr, this), false); } public void set_KshapeActive(double value) { opensimSimulationJNI.Thelen2003Muscle_set_KshapeActive__SWIG_1(swigCPtr, this, value); } public void copyProperty_KshapePassive(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_KshapePassive(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_KshapePassive(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_KshapePassive__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_KshapePassive(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_KshapePassive__SWIG_0(swigCPtr, this, i), false); } public void set_KshapePassive(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_KshapePassive__SWIG_0(swigCPtr, this, i, value); } public int append_KshapePassive(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_KshapePassive(swigCPtr, this, value); } public void constructProperty_KshapePassive(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_KshapePassive(swigCPtr, this, initValue); } public double get_KshapePassive() { return opensimSimulationJNI.Thelen2003Muscle_get_KshapePassive__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_KshapePassive() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_KshapePassive__SWIG_1(swigCPtr, this), false); } public void set_KshapePassive(double value) { opensimSimulationJNI.Thelen2003Muscle_set_KshapePassive__SWIG_1(swigCPtr, this, value); } public void copyProperty_Af(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_Af(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_Af(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_Af__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_Af(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_Af__SWIG_0(swigCPtr, this, i), false); } public void set_Af(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_Af__SWIG_0(swigCPtr, this, i, value); } public int append_Af(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_Af(swigCPtr, this, value); } public void constructProperty_Af(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_Af(swigCPtr, this, initValue); } public double get_Af() { return opensimSimulationJNI.Thelen2003Muscle_get_Af__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_Af() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_Af__SWIG_1(swigCPtr, this), false); } public void set_Af(double value) { opensimSimulationJNI.Thelen2003Muscle_set_Af__SWIG_1(swigCPtr, this, value); } public void copyProperty_Flen(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_Flen(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_Flen(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_Flen__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_Flen(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_Flen__SWIG_0(swigCPtr, this, i), false); } public void set_Flen(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_Flen__SWIG_0(swigCPtr, this, i, value); } public int append_Flen(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_Flen(swigCPtr, this, value); } public void constructProperty_Flen(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_Flen(swigCPtr, this, initValue); } public double get_Flen() { return opensimSimulationJNI.Thelen2003Muscle_get_Flen__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_Flen() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_Flen__SWIG_1(swigCPtr, this), false); } public void set_Flen(double value) { opensimSimulationJNI.Thelen2003Muscle_set_Flen__SWIG_1(swigCPtr, this, value); } public void copyProperty_fv_linear_extrap_threshold(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_fv_linear_extrap_threshold(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_fv_linear_extrap_threshold(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_fv_linear_extrap_threshold__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_fv_linear_extrap_threshold(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_fv_linear_extrap_threshold__SWIG_0(swigCPtr, this, i), false); } public void set_fv_linear_extrap_threshold(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_fv_linear_extrap_threshold__SWIG_0(swigCPtr, this, i, value); } public int append_fv_linear_extrap_threshold(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_fv_linear_extrap_threshold(swigCPtr, this, value); } public void constructProperty_fv_linear_extrap_threshold(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_fv_linear_extrap_threshold(swigCPtr, this, initValue); } public double get_fv_linear_extrap_threshold() { return opensimSimulationJNI.Thelen2003Muscle_get_fv_linear_extrap_threshold__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_fv_linear_extrap_threshold() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_fv_linear_extrap_threshold__SWIG_1(swigCPtr, this), false); } public void set_fv_linear_extrap_threshold(double value) { opensimSimulationJNI.Thelen2003Muscle_set_fv_linear_extrap_threshold__SWIG_1(swigCPtr, this, value); } public void copyProperty_maximum_pennation_angle(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_maximum_pennation_angle(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_maximum_pennation_angle(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_maximum_pennation_angle__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_maximum_pennation_angle(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_maximum_pennation_angle__SWIG_0(swigCPtr, this, i), false); } public void set_maximum_pennation_angle(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_maximum_pennation_angle__SWIG_0(swigCPtr, this, i, value); } public int append_maximum_pennation_angle(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_maximum_pennation_angle(swigCPtr, this, value); } public void constructProperty_maximum_pennation_angle(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_maximum_pennation_angle(swigCPtr, this, initValue); } public double get_maximum_pennation_angle() { return opensimSimulationJNI.Thelen2003Muscle_get_maximum_pennation_angle__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_maximum_pennation_angle() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_maximum_pennation_angle__SWIG_1(swigCPtr, this), false); } public void set_maximum_pennation_angle(double value) { opensimSimulationJNI.Thelen2003Muscle_set_maximum_pennation_angle__SWIG_1(swigCPtr, this, value); } public void copyProperty_activation_time_constant(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_activation_time_constant(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_activation_time_constant(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_activation_time_constant__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_activation_time_constant(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_activation_time_constant__SWIG_0(swigCPtr, this, i), false); } public void set_activation_time_constant(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_activation_time_constant__SWIG_0(swigCPtr, this, i, value); } public int append_activation_time_constant(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_activation_time_constant(swigCPtr, this, value); } public void constructProperty_activation_time_constant(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_activation_time_constant(swigCPtr, this, initValue); } public double get_activation_time_constant() { return opensimSimulationJNI.Thelen2003Muscle_get_activation_time_constant__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_activation_time_constant() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_activation_time_constant__SWIG_1(swigCPtr, this), false); } public void set_activation_time_constant(double value) { opensimSimulationJNI.Thelen2003Muscle_set_activation_time_constant__SWIG_1(swigCPtr, this, value); } public void copyProperty_deactivation_time_constant(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_deactivation_time_constant(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_deactivation_time_constant(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_deactivation_time_constant__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_deactivation_time_constant(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_deactivation_time_constant__SWIG_0(swigCPtr, this, i), false); } public void set_deactivation_time_constant(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_deactivation_time_constant__SWIG_0(swigCPtr, this, i, value); } public int append_deactivation_time_constant(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_deactivation_time_constant(swigCPtr, this, value); } public void constructProperty_deactivation_time_constant(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_deactivation_time_constant(swigCPtr, this, initValue); } public double get_deactivation_time_constant() { return opensimSimulationJNI.Thelen2003Muscle_get_deactivation_time_constant__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_deactivation_time_constant() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_deactivation_time_constant__SWIG_1(swigCPtr, this), false); } public void set_deactivation_time_constant(double value) { opensimSimulationJNI.Thelen2003Muscle_set_deactivation_time_constant__SWIG_1(swigCPtr, this, value); } public void copyProperty_minimum_activation(Thelen2003Muscle source) { opensimSimulationJNI.Thelen2003Muscle_copyProperty_minimum_activation(swigCPtr, this, Thelen2003Muscle.getCPtr(source), source); } public double get_minimum_activation(int i) { return opensimSimulationJNI.Thelen2003Muscle_get_minimum_activation__SWIG_0(swigCPtr, this, i); } public SWIGTYPE_p_double upd_minimum_activation(int i) { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_minimum_activation__SWIG_0(swigCPtr, this, i), false); } public void set_minimum_activation(int i, double value) { opensimSimulationJNI.Thelen2003Muscle_set_minimum_activation__SWIG_0(swigCPtr, this, i, value); } public int append_minimum_activation(double value) { return opensimSimulationJNI.Thelen2003Muscle_append_minimum_activation(swigCPtr, this, value); } public void constructProperty_minimum_activation(double initValue) { opensimSimulationJNI.Thelen2003Muscle_constructProperty_minimum_activation(swigCPtr, this, initValue); } public double get_minimum_activation() { return opensimSimulationJNI.Thelen2003Muscle_get_minimum_activation__SWIG_1(swigCPtr, this); } public SWIGTYPE_p_double upd_minimum_activation() { return new SWIGTYPE_p_double(opensimSimulationJNI.Thelen2003Muscle_upd_minimum_activation__SWIG_1(swigCPtr, this), false); } public void set_minimum_activation(double value) { opensimSimulationJNI.Thelen2003Muscle_set_minimum_activation__SWIG_1(swigCPtr, this, value); } public Thelen2003Muscle() { this(opensimSimulationJNI.new_Thelen2003Muscle__SWIG_0(), true); } public Thelen2003Muscle(String aName, double aMaxIsometricForce, double aOptimalFiberLength, double aTendonSlackLength, double aPennationAngle) { this(opensimSimulationJNI.new_Thelen2003Muscle__SWIG_1(aName, aMaxIsometricForce, aOptimalFiberLength, aTendonSlackLength, aPennationAngle), true); } /** * * */ public double getActivationTimeConstant() { return opensimSimulationJNI.Thelen2003Muscle_getActivationTimeConstant(swigCPtr, this); } public void setActivationTimeConstant(double actTimeConstant) { opensimSimulationJNI.Thelen2003Muscle_setActivationTimeConstant(swigCPtr, this, actTimeConstant); } public double getDeactivationTimeConstant() { return opensimSimulationJNI.Thelen2003Muscle_getDeactivationTimeConstant(swigCPtr, this); } public void setDeactivationTimeConstant(double deactTimeConstant) { opensimSimulationJNI.Thelen2003Muscle_setDeactivationTimeConstant(swigCPtr, this, deactTimeConstant); } public double getMinimumActivation() { return opensimSimulationJNI.Thelen2003Muscle_getMinimumActivation(swigCPtr, this); } public void setMinimumActivation(double minimumActivation) { opensimSimulationJNI.Thelen2003Muscle_setMinimumActivation(swigCPtr, this, minimumActivation); } public double getMaximumPennationAngle() { return opensimSimulationJNI.Thelen2003Muscle_getMaximumPennationAngle(swigCPtr, this); } public void setMaximumPennationAngle(double maximumPennationAngle) { opensimSimulationJNI.Thelen2003Muscle_setMaximumPennationAngle(swigCPtr, this, maximumPennationAngle); } /** * *<br> * @return the minimum fiber length, which is the maximum of two values:<br> * the smallest fiber length allowed by the pennation model, and the <br> * minimum fiber length in the active force length curve. When the fiber<br> * length reaches this value, it is constrained to this value until the <br> * fiber velocity goes positive. */ public double getMinimumFiberLength() { return opensimSimulationJNI.Thelen2003Muscle_getMinimumFiberLength(swigCPtr, this); } /** * @return the MuscleFirstOrderActivationDynamicModel <br> * that this muscle model uses */ public MuscleFirstOrderActivationDynamicModel getActivationModel() { return new MuscleFirstOrderActivationDynamicModel(opensimSimulationJNI.Thelen2003Muscle_getActivationModel(swigCPtr, this), false); } /** * @return the MuscleFixedWidthPennationModel <br> * that this muscle model uses */ public MuscleFixedWidthPennationModel getPennationModel() { return new MuscleFixedWidthPennationModel(opensimSimulationJNI.Thelen2003Muscle_getPennationModel(swigCPtr, this), false); } public void printCurveToCSVFile(Thelen2003Muscle.CurveType ctype, String path) { opensimSimulationJNI.Thelen2003Muscle_printCurveToCSVFile(swigCPtr, this, ctype.swigValue(), path); } public double computeActuation(State s) { return opensimSimulationJNI.Thelen2003Muscle_computeActuation(swigCPtr, this, State.getCPtr(s), s); } /** * Compute initial fiber length (velocity) such that muscle fiber and <br> * tendon are in static equilibrium and update the state<br> * <br> * Part of the Muscle.h interface<br> * <br> * @throws MuscleCannotEquilibrate */ public void computeInitialFiberEquilibrium(State s) { opensimSimulationJNI.Thelen2003Muscle_computeInitialFiberEquilibrium(swigCPtr, this, State.getCPtr(s), s); } /** * Conditional comment: DEPRECATED */ public double calcActiveFiberForceAlongTendon(double activation, double fiberLength, double fiberVelocity) { return opensimSimulationJNI.Thelen2003Muscle_calcActiveFiberForceAlongTendon(swigCPtr, this, activation, fiberLength, fiberVelocity); } public double calcInextensibleTendonActiveFiberForce(State s, double aActivation) { return opensimSimulationJNI.Thelen2003Muscle_calcInextensibleTendonActiveFiberForce(swigCPtr, this, State.getCPtr(s), s, aActivation); } public final static class CurveType { public final static Thelen2003Muscle.CurveType FiberActiveForceLength = new Thelen2003Muscle.CurveType("FiberActiveForceLength"); public final static Thelen2003Muscle.CurveType FiberPassiveForceLength = new Thelen2003Muscle.CurveType("FiberPassiveForceLength"); public final static Thelen2003Muscle.CurveType FiberForceVelocity = new Thelen2003Muscle.CurveType("FiberForceVelocity"); public final static Thelen2003Muscle.CurveType TendonForceLength = new Thelen2003Muscle.CurveType("TendonForceLength"); public final int swigValue() { return swigValue; } public String toString() { return swigName; } public static CurveType swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; throw new IllegalArgumentException("No enum " + CurveType.class + " with value " + swigValue); } private CurveType(String swigName) { this.swigName = swigName; this.swigValue = swigNext++; } private CurveType(String swigName, int swigValue) { this.swigName = swigName; this.swigValue = swigValue; swigNext = swigValue+1; } private CurveType(String swigName, CurveType swigEnum) { this.swigName = swigName; this.swigValue = swigEnum.swigValue; swigNext = this.swigValue+1; } private static CurveType[] swigValues = { FiberActiveForceLength, FiberPassiveForceLength, FiberForceVelocity, TendonForceLength }; private static int swigNext = 0; private final int swigValue; private final String swigName; } }
opensim-org/opensim-gui
Gui/opensim/modeling/src/org/opensim/modeling/Thelen2003Muscle.java
Java
apache-2.0
28,066
package storm.trident.spout; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.Fields; import java.io.Serializable; import java.util.List; import java.util.Map; import storm.trident.operation.TridentCollector; import storm.trident.topology.TransactionAttempt; /** * This interface defines a transactional spout that reads its tuples from a partitioned set of * brokers. It automates the storing of metadata for each partition to ensure that the same batch * is always emitted for the same transaction id. The partition metadata is stored in Zookeeper. */ public interface IPartitionedTridentSpout<Partitions, Partition extends ISpoutPartition, T> extends Serializable { public interface Coordinator<Partitions> { /** * Return the partitions currently in the source of data. The idea is * is that if a new partition is added and a prior transaction is replayed, it doesn't * emit tuples for the new partition because it knows what partitions were in * that transaction. */ Partitions getPartitionsForBatch(); boolean isReady(long txid); void close(); } public interface Emitter<Partitions, Partition extends ISpoutPartition, X> { List<Partition> getOrderedPartitions(Partitions allPartitionInfo); /** * Emit a batch of tuples for a partition/transaction that's never been emitted before. * Return the metadata that can be used to reconstruct this partition/batch in the future. */ X emitPartitionBatchNew(TransactionAttempt tx, TridentCollector collector, Partition partition, X lastPartitionMeta); /** * This method is called when this task is responsible for a new set of partitions. Should be used * to manage things like connections to brokers. */ void refreshPartitions(List<Partition> partitionResponsibilities); /** * Emit a batch of tuples for a partition/transaction that has been emitted before, using * the metadata created when it was first emitted. */ void emitPartitionBatch(TransactionAttempt tx, TridentCollector collector, Partition partition, X partitionMeta); void close(); } Coordinator<Partitions> getCoordinator(Map conf, TopologyContext context); Emitter<Partitions, Partition, T> getEmitter(Map conf, TopologyContext context); Map getComponentConfiguration(); Fields getOutputFields(); }
songtk/learn_jstorm
jstorm-client/src/main/java/storm/trident/spout/IPartitionedTridentSpout.java
Java
apache-2.0
2,624
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.client.file.cache.store; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import alluxio.Constants; import alluxio.ProjectConstants; import alluxio.client.file.cache.PageId; import alluxio.client.file.cache.PageInfo; import alluxio.client.file.cache.PageStore; import alluxio.exception.PageNotFoundException; import alluxio.util.io.BufferUtils; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @RunWith(Parameterized.class) public class PageStoreTest { @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {new RocksPageStoreOptions()}, {new LocalPageStoreOptions()} }); } @Parameterized.Parameter public PageStoreOptions mOptions; private PageStore mPageStore; @Rule public TemporaryFolder mTemp = new TemporaryFolder(); @Rule public final ExpectedException mThrown = ExpectedException.none(); @Before public void before() throws Exception { mOptions.setPageSize(1024); mOptions.setCacheSize(65536); mOptions.setAlluxioVersion(ProjectConstants.VERSION); mOptions.setRootDir(mTemp.getRoot().getAbsolutePath()); mPageStore = PageStore.create(mOptions); } @After public void after() throws Exception { mPageStore.close(); } @Test public void helloWorldTest() throws Exception { String msg = "Hello, World!"; byte[] msgBytes = msg.getBytes(); PageId id = new PageId("0", 0); mPageStore.put(id, msgBytes); byte[] buf = new byte[1024]; assertEquals(msgBytes.length, mPageStore.get(id, buf)); assertArrayEquals(msgBytes, Arrays.copyOfRange(buf, 0, msgBytes.length)); mPageStore.delete(id); try { mPageStore.get(id, buf); fail(); } catch (PageNotFoundException e) { // Test completed successfully; } } @Test public void getOffset() throws Exception { int len = 32; PageId id = new PageId("0", 0); mPageStore.put(id, BufferUtils.getIncreasingByteArray(len)); byte[] buf = new byte[len]; for (int offset = 1; offset < len; offset++) { int bytesRead = mPageStore.get(id, offset, len, buf, 0); assertEquals(len - offset, bytesRead); assertArrayEquals(BufferUtils.getIncreasingByteArray(offset, len - offset), Arrays.copyOfRange(buf, 0, bytesRead)); } } @Test public void getOffsetOverflow() throws Exception { int len = 32; int offset = 36; PageId id = new PageId("0", 0); mPageStore.put(id, BufferUtils.getIncreasingByteArray(len)); byte[] buf = new byte[1024]; mThrown.expect(IllegalArgumentException.class); mPageStore.get(id, offset, len, buf, 0); } @Test public void getPages() throws Exception { int len = 32; int count = 16; byte[] data = BufferUtils.getIncreasingByteArray(len); Set<PageInfo> pages = new HashSet<>(count); for (int i = 0; i < count; i++) { PageId id = new PageId("0", i); mPageStore.put(id, data); pages.add(new PageInfo(id, data.length)); } Set<PageInfo> restored = mPageStore.getPages().collect(Collectors.toSet()); assertEquals(pages, restored); } @Test public void getPagesUUID() throws Exception { int len = 32; int count = 16; byte[] data = BufferUtils.getIncreasingByteArray(len); Set<PageInfo> pages = new HashSet<>(count); for (int i = 0; i < count; i++) { PageId id = new PageId(UUID.randomUUID().toString(), i); mPageStore.put(id, data); pages.add(new PageInfo(id, data.length)); } Set<PageInfo> restored = mPageStore.getPages().collect(Collectors.toSet()); assertEquals(pages, restored); } @Test public void getSmallLen() throws Exception { int len = 32; PageId id = new PageId("0", 0); mPageStore.put(id, BufferUtils.getIncreasingByteArray(len)); byte[] buf = new byte[1024]; for (int b = 1; b < len; b++) { int bytesRead = mPageStore.get(id, 0, b, buf, 0); assertEquals(b, bytesRead); assertArrayEquals(BufferUtils.getIncreasingByteArray(b), Arrays.copyOfRange(buf, 0, bytesRead)); } } @Test public void getSmallBuffer() throws Exception { int len = 32; PageId id = new PageId("0", 0); mPageStore.put(id, BufferUtils.getIncreasingByteArray(len)); for (int b = 1; b < len; b++) { byte[] buf = new byte[b]; int bytesRead = mPageStore.get(id, 0, len, buf, 0); assertEquals(b, bytesRead); assertArrayEquals(BufferUtils.getIncreasingByteArray(b), Arrays.copyOfRange(buf, 0, bytesRead)); } } @Ignore @Test public void perfTest() throws Exception { thousandGetTest(mPageStore); } void thousandGetTest(PageStore store) throws Exception { int numPages = 1000; int numTrials = 3; // Fill the cache List<Integer> pages = new ArrayList<>(numPages); byte[] b = new byte[Constants.MB]; Arrays.fill(b, (byte) 0x7a); Random r = new Random(); for (int i = 0; i < numPages; i++) { int pind = r.nextInt(); store.put(new PageId("0", pind), b); pages.add(pind); } ByteArrayOutputStream bos = new ByteArrayOutputStream(Constants.MB); ArrayList<Long> times = new ArrayList<>(); byte[] buf = new byte[Constants.MB]; for (int i = 0; i < numTrials; i++) { Collections.shuffle(pages); long start = System.nanoTime(); bos.reset(); for (Integer pageIndex : pages) { store.get(new PageId("0", pageIndex), buf); } long end = System.nanoTime(); times.add(end - start); } double avg = (double) times.stream().mapToLong(Long::longValue).sum() / numTrials; System.out.println(String.format("Finished thousand get for %7s : %.2fns", mOptions, avg)); } }
EvilMcJerkface/alluxio
core/client/fs/src/test/java/alluxio/client/file/cache/store/PageStoreTest.java
Java
apache-2.0
6,885
package org.ovirt.engine.core.compat; import java.util.StringTokenizer; /** * Wrapper class for StringTokenizer * @deprecated Use {@link StringTokenizer} directly instead. */ @Deprecated public class StringTokenizerCompat { protected StringTokenizer st; public StringTokenizerCompat(String str) { st = new StringTokenizer(str); } public StringTokenizerCompat(String str, String delim) { st = new StringTokenizer(str, delim); } public StringTokenizerCompat(String str, String delim, boolean returnDelims) { st = new StringTokenizer(str, delim, returnDelims); } public boolean hasMoreTokens() { return st.hasMoreTokens(); } public String nextToken() { return st.nextToken(); } }
jbeecham/ovirt-engine
backend/manager/modules/compat/src/main/java/org/ovirt/engine/core/compat/StringTokenizerCompat.java
Java
apache-2.0
772
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.index.merge.policy; import org.apache.lucene.index.*; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.index.settings.IndexSettingsService; import org.elasticsearch.index.shard.AbstractIndexShardComponent; import org.elasticsearch.index.store.Store; import java.io.IOException; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; public class TieredMergePolicyProvider extends AbstractIndexShardComponent implements MergePolicyProvider<TieredMergePolicy> { private final IndexSettingsService indexSettingsService; private final Set<CustomTieredMergePolicyProvider> policies = new CopyOnWriteArraySet<CustomTieredMergePolicyProvider>(); private volatile boolean compoundFormat; private volatile double forceMergeDeletesPctAllowed; private volatile ByteSizeValue floorSegment; private volatile int maxMergeAtOnce; private volatile int maxMergeAtOnceExplicit; private volatile ByteSizeValue maxMergedSegment; private volatile double segmentsPerTier; private volatile double reclaimDeletesWeight; private boolean asyncMerge; private final ApplySettings applySettings = new ApplySettings(); @Inject public TieredMergePolicyProvider(Store store, IndexSettingsService indexSettingsService) { super(store.shardId(), store.indexSettings()); this.indexSettingsService = indexSettingsService; this.compoundFormat = indexSettings.getAsBoolean("index.compound_format", store.suggestUseCompoundFile()); this.asyncMerge = indexSettings.getAsBoolean("index.merge.async", true); this.forceMergeDeletesPctAllowed = componentSettings.getAsDouble("expunge_deletes_allowed", 10d); // percentage this.floorSegment = componentSettings.getAsBytesSize("floor_segment", new ByteSizeValue(2, ByteSizeUnit.MB)); this.maxMergeAtOnce = componentSettings.getAsInt("max_merge_at_once", 10); this.maxMergeAtOnceExplicit = componentSettings.getAsInt("max_merge_at_once_explicit", 30); // TODO is this really a good default number for max_merge_segment, what happens for large indices, won't they end up with many segments? this.maxMergedSegment = componentSettings.getAsBytesSize("max_merged_segment", componentSettings.getAsBytesSize("max_merge_segment", new ByteSizeValue(5, ByteSizeUnit.GB))); this.segmentsPerTier = componentSettings.getAsDouble("segments_per_tier", 9.2d); this.reclaimDeletesWeight = componentSettings.getAsDouble("reclaim_deletes_weight", 2.0d); fixSettingsIfNeeded(); logger.debug("using [tiered] merge policy with expunge_deletes_allowed[{}], floor_segment[{}], max_merge_at_once[{}], max_merge_at_once_explicit[{}], max_merged_segment[{}], segments_per_tier[{}], reclaim_deletes_weight[{}], async_merge[{}]", forceMergeDeletesPctAllowed, floorSegment, maxMergeAtOnce, maxMergeAtOnceExplicit, maxMergedSegment, segmentsPerTier, reclaimDeletesWeight, asyncMerge); indexSettingsService.addListener(applySettings); } private void fixSettingsIfNeeded() { // fixing maxMergeAtOnce, see TieredMergePolicy#setMaxMergeAtOnce if (!(segmentsPerTier >= maxMergeAtOnce)) { int newMaxMergeAtOnce = (int) segmentsPerTier; logger.debug("[tiered] merge policy changing max_merge_at_once from [{}] to [{}] because segments_per_tier [{}] has to be higher or equal to it", maxMergeAtOnce, newMaxMergeAtOnce, segmentsPerTier); this.maxMergeAtOnce = newMaxMergeAtOnce; } } @Override public TieredMergePolicy newMergePolicy() { CustomTieredMergePolicyProvider mergePolicy; if (asyncMerge) { mergePolicy = new EnableMergeTieredMergePolicyProvider(this); } else { mergePolicy = new CustomTieredMergePolicyProvider(this); } mergePolicy.setUseCompoundFile(compoundFormat); mergePolicy.setForceMergeDeletesPctAllowed(forceMergeDeletesPctAllowed); mergePolicy.setFloorSegmentMB(floorSegment.mbFrac()); mergePolicy.setMaxMergeAtOnce(maxMergeAtOnce); mergePolicy.setMaxMergeAtOnceExplicit(maxMergeAtOnceExplicit); mergePolicy.setMaxMergedSegmentMB(maxMergedSegment.mbFrac()); mergePolicy.setSegmentsPerTier(segmentsPerTier); mergePolicy.setReclaimDeletesWeight(reclaimDeletesWeight); return mergePolicy; } @Override public void close(boolean delete) throws ElasticSearchException { indexSettingsService.removeListener(applySettings); } static { IndexMetaData.addDynamicSettings( "index.merge.policy.expunge_deletes_allowed", "index.merge.policy.floor_segment", "index.merge.policy.max_merge_at_once", "index.merge.policy.max_merge_at_once_explicit", "index.merge.policy.max_merged_segment", "index.merge.policy.segments_per_tier", "index.merge.policy.reclaim_deletes_weight", "index.compound_format" ); } class ApplySettings implements IndexSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { double expungeDeletesPctAllowed = settings.getAsDouble("index.merge.policy.expunge_deletes_allowed", TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed); if (expungeDeletesPctAllowed != TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed) { logger.info("updating [expunge_deletes_allowed] from [{}] to [{}]", TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed, expungeDeletesPctAllowed); TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed = expungeDeletesPctAllowed; for (CustomTieredMergePolicyProvider policy : policies) { policy.setForceMergeDeletesPctAllowed(expungeDeletesPctAllowed); } } ByteSizeValue floorSegment = settings.getAsBytesSize("index.merge.policy.floor_segment", TieredMergePolicyProvider.this.floorSegment); if (!floorSegment.equals(TieredMergePolicyProvider.this.floorSegment)) { logger.info("updating [floor_segment] from [{}] to [{}]", TieredMergePolicyProvider.this.floorSegment, floorSegment); TieredMergePolicyProvider.this.floorSegment = floorSegment; for (CustomTieredMergePolicyProvider policy : policies) { policy.setFloorSegmentMB(floorSegment.mbFrac()); } } int maxMergeAtOnce = settings.getAsInt("index.merge.policy.max_merge_at_once", TieredMergePolicyProvider.this.maxMergeAtOnce); if (maxMergeAtOnce != TieredMergePolicyProvider.this.maxMergeAtOnce) { logger.info("updating [max_merge_at_once] from [{}] to [{}]", TieredMergePolicyProvider.this.maxMergeAtOnce, maxMergeAtOnce); TieredMergePolicyProvider.this.maxMergeAtOnce = maxMergeAtOnce; for (CustomTieredMergePolicyProvider policy : policies) { policy.setMaxMergeAtOnce(maxMergeAtOnce); } } int maxMergeAtOnceExplicit = settings.getAsInt("index.merge.policy.max_merge_at_once_explicit", TieredMergePolicyProvider.this.maxMergeAtOnceExplicit); if (maxMergeAtOnceExplicit != TieredMergePolicyProvider.this.maxMergeAtOnceExplicit) { logger.info("updating [max_merge_at_once_explicit] from [{}] to [{}]", TieredMergePolicyProvider.this.maxMergeAtOnceExplicit, maxMergeAtOnceExplicit); TieredMergePolicyProvider.this.maxMergeAtOnceExplicit = maxMergeAtOnceExplicit; for (CustomTieredMergePolicyProvider policy : policies) { policy.setMaxMergeAtOnceExplicit(maxMergeAtOnceExplicit); } } ByteSizeValue maxMergedSegment = settings.getAsBytesSize("index.merge.policy.max_merged_segment", TieredMergePolicyProvider.this.maxMergedSegment); if (!maxMergedSegment.equals(TieredMergePolicyProvider.this.maxMergedSegment)) { logger.info("updating [max_merged_segment] from [{}] to [{}]", TieredMergePolicyProvider.this.maxMergedSegment, maxMergedSegment); TieredMergePolicyProvider.this.maxMergedSegment = maxMergedSegment; for (CustomTieredMergePolicyProvider policy : policies) { policy.setFloorSegmentMB(maxMergedSegment.mbFrac()); } } double segmentsPerTier = settings.getAsDouble("index.merge.policy.segments_per_tier", TieredMergePolicyProvider.this.segmentsPerTier); if (segmentsPerTier != TieredMergePolicyProvider.this.segmentsPerTier) { logger.info("updating [segments_per_tier] from [{}] to [{}]", TieredMergePolicyProvider.this.segmentsPerTier, segmentsPerTier); TieredMergePolicyProvider.this.segmentsPerTier = segmentsPerTier; for (CustomTieredMergePolicyProvider policy : policies) { policy.setSegmentsPerTier(segmentsPerTier); } } double reclaimDeletesWeight = settings.getAsDouble("index.merge.policy.reclaim_deletes_weight", TieredMergePolicyProvider.this.reclaimDeletesWeight); if (reclaimDeletesWeight != TieredMergePolicyProvider.this.reclaimDeletesWeight) { logger.info("updating [reclaim_deletes_weight] from [{}] to [{}]", TieredMergePolicyProvider.this.reclaimDeletesWeight, reclaimDeletesWeight); TieredMergePolicyProvider.this.reclaimDeletesWeight = reclaimDeletesWeight; for (CustomTieredMergePolicyProvider policy : policies) { policy.setReclaimDeletesWeight(reclaimDeletesWeight); } } boolean compoundFormat = settings.getAsBoolean("index.compound_format", TieredMergePolicyProvider.this.compoundFormat); if (compoundFormat != TieredMergePolicyProvider.this.compoundFormat) { logger.info("updating index.compound_format from [{}] to [{}]", TieredMergePolicyProvider.this.compoundFormat, compoundFormat); TieredMergePolicyProvider.this.compoundFormat = compoundFormat; for (CustomTieredMergePolicyProvider policy : policies) { policy.setUseCompoundFile(compoundFormat); } } fixSettingsIfNeeded(); } } public static class CustomTieredMergePolicyProvider extends TieredMergePolicy { private final TieredMergePolicyProvider provider; public CustomTieredMergePolicyProvider(TieredMergePolicyProvider provider) { super(); this.provider = provider; } @Override public void close() { super.close(); provider.policies.remove(this); } } public static class EnableMergeTieredMergePolicyProvider extends CustomTieredMergePolicyProvider implements EnableMergePolicy { private final ThreadLocal<Boolean> enableMerge = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; public EnableMergeTieredMergePolicyProvider(TieredMergePolicyProvider provider) { super(provider); } @Override public void enableMerge() { enableMerge.set(Boolean.TRUE); } @Override public void disableMerge() { enableMerge.set(Boolean.FALSE); } @Override public boolean isMergeEnabled() { return enableMerge.get() == Boolean.TRUE; } @Override public void close() { enableMerge.remove(); super.close(); } @Override public MergePolicy.MergeSpecification findMerges(SegmentInfos infos) throws IOException { if (enableMerge.get() == Boolean.FALSE) { return null; } return super.findMerges(infos); } @Override public MergeSpecification findForcedMerges(SegmentInfos infos, int maxSegmentCount, Map<SegmentInfo, Boolean> segmentsToMerge) throws IOException { if (enableMerge.get() == Boolean.FALSE) { return null; } return super.findForcedMerges(infos, maxSegmentCount, segmentsToMerge); } @Override public MergeSpecification findForcedDeletesMerges(SegmentInfos infos) throws CorruptIndexException, IOException { if (enableMerge.get() == Boolean.FALSE) { return null; } return super.findForcedDeletesMerges(infos); } } }
chanil1218/elasticsearch
src/main/java/org/elasticsearch/index/merge/policy/TieredMergePolicyProvider.java
Java
apache-2.0
14,017
package com.neustar.ultraservice.schema.v01; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SMTPAvailabilityProbeData complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SMTPAvailabilityProbeData"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;/sequence> * &lt;attribute name="port" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="connectTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="runtime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="failConnectTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="criticalConnectTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="warningConnectTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="failRuntime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="criticalRuntime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="warningRuntime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="failAverageConnectTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="criticalAverageConnectTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="warningAverageConnectTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="failAverageRunTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="criticalAverageRunTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="warningAverageRunTime" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SMTPAvailabilityProbeData") public class SMTPAvailabilityProbeData { @XmlAttribute(name = "port") protected String port; @XmlAttribute(name = "connectTime") protected String connectTime; @XmlAttribute(name = "runtime") protected String runtime; @XmlAttribute(name = "failConnectTime") protected String failConnectTime; @XmlAttribute(name = "criticalConnectTime") protected String criticalConnectTime; @XmlAttribute(name = "warningConnectTime") protected String warningConnectTime; @XmlAttribute(name = "failRuntime") protected String failRuntime; @XmlAttribute(name = "criticalRuntime") protected String criticalRuntime; @XmlAttribute(name = "warningRuntime") protected String warningRuntime; @XmlAttribute(name = "failAverageConnectTime") protected String failAverageConnectTime; @XmlAttribute(name = "criticalAverageConnectTime") protected String criticalAverageConnectTime; @XmlAttribute(name = "warningAverageConnectTime") protected String warningAverageConnectTime; @XmlAttribute(name = "failAverageRunTime") protected String failAverageRunTime; @XmlAttribute(name = "criticalAverageRunTime") protected String criticalAverageRunTime; @XmlAttribute(name = "warningAverageRunTime") protected String warningAverageRunTime; /** * Gets the value of the port property. * * @return * possible object is * {@link String } * */ public String getPort() { return port; } /** * Sets the value of the port property. * * @param value * allowed object is * {@link String } * */ public void setPort(String value) { this.port = value; } /** * Gets the value of the connectTime property. * * @return * possible object is * {@link String } * */ public String getConnectTime() { return connectTime; } /** * Sets the value of the connectTime property. * * @param value * allowed object is * {@link String } * */ public void setConnectTime(String value) { this.connectTime = value; } /** * Gets the value of the runtime property. * * @return * possible object is * {@link String } * */ public String getRuntime() { return runtime; } /** * Sets the value of the runtime property. * * @param value * allowed object is * {@link String } * */ public void setRuntime(String value) { this.runtime = value; } /** * Gets the value of the failConnectTime property. * * @return * possible object is * {@link String } * */ public String getFailConnectTime() { return failConnectTime; } /** * Sets the value of the failConnectTime property. * * @param value * allowed object is * {@link String } * */ public void setFailConnectTime(String value) { this.failConnectTime = value; } /** * Gets the value of the criticalConnectTime property. * * @return * possible object is * {@link String } * */ public String getCriticalConnectTime() { return criticalConnectTime; } /** * Sets the value of the criticalConnectTime property. * * @param value * allowed object is * {@link String } * */ public void setCriticalConnectTime(String value) { this.criticalConnectTime = value; } /** * Gets the value of the warningConnectTime property. * * @return * possible object is * {@link String } * */ public String getWarningConnectTime() { return warningConnectTime; } /** * Sets the value of the warningConnectTime property. * * @param value * allowed object is * {@link String } * */ public void setWarningConnectTime(String value) { this.warningConnectTime = value; } /** * Gets the value of the failRuntime property. * * @return * possible object is * {@link String } * */ public String getFailRuntime() { return failRuntime; } /** * Sets the value of the failRuntime property. * * @param value * allowed object is * {@link String } * */ public void setFailRuntime(String value) { this.failRuntime = value; } /** * Gets the value of the criticalRuntime property. * * @return * possible object is * {@link String } * */ public String getCriticalRuntime() { return criticalRuntime; } /** * Sets the value of the criticalRuntime property. * * @param value * allowed object is * {@link String } * */ public void setCriticalRuntime(String value) { this.criticalRuntime = value; } /** * Gets the value of the warningRuntime property. * * @return * possible object is * {@link String } * */ public String getWarningRuntime() { return warningRuntime; } /** * Sets the value of the warningRuntime property. * * @param value * allowed object is * {@link String } * */ public void setWarningRuntime(String value) { this.warningRuntime = value; } /** * Gets the value of the failAverageConnectTime property. * * @return * possible object is * {@link String } * */ public String getFailAverageConnectTime() { return failAverageConnectTime; } /** * Sets the value of the failAverageConnectTime property. * * @param value * allowed object is * {@link String } * */ public void setFailAverageConnectTime(String value) { this.failAverageConnectTime = value; } /** * Gets the value of the criticalAverageConnectTime property. * * @return * possible object is * {@link String } * */ public String getCriticalAverageConnectTime() { return criticalAverageConnectTime; } /** * Sets the value of the criticalAverageConnectTime property. * * @param value * allowed object is * {@link String } * */ public void setCriticalAverageConnectTime(String value) { this.criticalAverageConnectTime = value; } /** * Gets the value of the warningAverageConnectTime property. * * @return * possible object is * {@link String } * */ public String getWarningAverageConnectTime() { return warningAverageConnectTime; } /** * Sets the value of the warningAverageConnectTime property. * * @param value * allowed object is * {@link String } * */ public void setWarningAverageConnectTime(String value) { this.warningAverageConnectTime = value; } /** * Gets the value of the failAverageRunTime property. * * @return * possible object is * {@link String } * */ public String getFailAverageRunTime() { return failAverageRunTime; } /** * Sets the value of the failAverageRunTime property. * * @param value * allowed object is * {@link String } * */ public void setFailAverageRunTime(String value) { this.failAverageRunTime = value; } /** * Gets the value of the criticalAverageRunTime property. * * @return * possible object is * {@link String } * */ public String getCriticalAverageRunTime() { return criticalAverageRunTime; } /** * Sets the value of the criticalAverageRunTime property. * * @param value * allowed object is * {@link String } * */ public void setCriticalAverageRunTime(String value) { this.criticalAverageRunTime = value; } /** * Gets the value of the warningAverageRunTime property. * * @return * possible object is * {@link String } * */ public String getWarningAverageRunTime() { return warningAverageRunTime; } /** * Sets the value of the warningAverageRunTime property. * * @param value * allowed object is * {@link String } * */ public void setWarningAverageRunTime(String value) { this.warningAverageRunTime = value; } }
ultradns/ultra-java-api
src/main/java/com/neustar/ultraservice/schema/v01/SMTPAvailabilityProbeData.java
Java
apache-2.0
11,316
package xworker.swt.reacts.creators; import java.util.Map; import org.eclipse.swt.widgets.Widget; import org.xmeta.ActionContext; import org.xmeta.Thing; import org.xmeta.util.UtilString; import xworker.swt.reacts.DataReactor; import xworker.swt.reacts.DataReactorCreator; import xworker.swt.reacts.events.SelectionDataReactor; public class SelectionDataReactorCreator implements DataReactorCreator{ @Override public DataReactor create(Object control, String action, ActionContext actionContext) { Thing thing = new Thing("xworker.swt.reactors.events.SelectionDataReactor"); Map<String, String> params = UtilString.getParams(action); thing.getAttributes().putAll(params); return new SelectionDataReactor((Widget) control, thing, actionContext); } }
x-meta/xworker
xworker_swt/src/main/java/xworker/swt/reacts/creators/SelectionDataReactorCreator.java
Java
apache-2.0
792
package org.develnext.jphp.swing.loader.support.propertyreaders; import org.develnext.jphp.swing.ComponentProperties; import org.develnext.jphp.swing.SwingExtension; import org.develnext.jphp.swing.loader.support.PropertyReader; import org.develnext.jphp.swing.loader.support.Value; import org.develnext.jphp.swing.misc.Align; import org.develnext.jphp.swing.misc.Anchor; import java.awt.*; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; final public class ComponentPropertyReaders extends PropertyReaders<Component> { protected final Map<String, PropertyReader<Component>> register = new HashMap<String, PropertyReader<Component>>(){{ put("visible", VISIBLE); put("enabled", ENABLED); put("focusable", FOCUSABLE); put("x", X); put("y", Y); put("w", W); put("h", H); put("align", ALIGN); put("anchors", ANCHORS); put("padding", PADDING); put("group", GROUP); put("font", FONT); put("background", BACKGROUND); put("foreground", FOREGROUND); put("size", SIZE); put("position", POSITION); put("min-size", MIN_SIZE); put("autosize", AUTOSIZE); put("cursor", CURSOR); }}; @Override protected Map<String, PropertyReader<Component>> getRegister() { return register; } @Override public Class<Component> getRegisterClass() { return Component.class; } public final static PropertyReader<Component> VISIBLE = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setVisible(value.asBoolean()); } }; public final static PropertyReader<Component> ENABLED = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setEnabled(value.asBoolean()); } }; public final static PropertyReader<Component> FOCUSABLE = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setFocusable(value.asBoolean()); } }; public final static PropertyReader<Component> X = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setLocation(value.asInteger(), component.getY()); } }; public final static PropertyReader<Component> Y = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setLocation(component.getX(), value.asInteger()); } }; public final static PropertyReader<Component> W = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setSize(value.asInteger(), component.getHeight()); } }; public final static PropertyReader<Component> H = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setSize(component.getWidth(), value.asInteger()); } }; public final static PropertyReader<Component> BACKGROUND = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setBackground(value.asColor()); } }; public final static PropertyReader<Component> FOREGROUND = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setForeground(value.asColor()); } }; public final static PropertyReader<Component> FONT = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setFont(value.asFont()); } }; public final static PropertyReader<Component> MIN_SIZE = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setMinimumSize(value.asDimension()); } }; public final static PropertyReader<Component> SIZE = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { if (value.asString().equals("auto")) { ComponentProperties properties = SwingExtension.getProperties(component); properties.setAutoSize(true); } else component.setSize(value.asDimension()); } }; public final static PropertyReader<Component> POSITION = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { component.setLocation(value.asPoint()); } }; public final static PropertyReader<Component> AUTOSIZE = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { ComponentProperties properties = SwingExtension.getProperties(component); properties.setAutoSize(value.asBoolean()); } }; public final static PropertyReader<Component> ALIGN = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { ComponentProperties properties = SwingExtension.getProperties(component); properties.setAlign(Align.valueOf(value.asString().toUpperCase())); } }; public final static PropertyReader<Component> ANCHORS = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { ComponentProperties propertiies = SwingExtension.getProperties(component); propertiies.anchors.clear(); for(String e : value.asArray()){ Anchor anchor = Anchor.valueOf(e.toUpperCase()); if (anchor != null) propertiies.anchors.add(anchor); } } }; public final static PropertyReader<Component> GROUP = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { ComponentProperties properties = SwingExtension.getProperties(component); properties.setGroups(value.asString()); } }; public final static PropertyReader<Component> PADDING = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { ComponentProperties properties = SwingExtension.getProperties(component); String v[] = value.asArray(true); if (v.length == 1) { int size = Integer.parseInt(v[0]); properties.setPadding(size, size, size, size); } else if (v.length == 2) { int ver = Integer.parseInt(v[0]); int hor = Integer.parseInt(v[1]); properties.setPadding(ver, hor, ver, hor); } else if (v.length == 3) { int top = Integer.parseInt(v[0]); int hor = Integer.parseInt(v[1]); int bottom = Integer.parseInt(v[2]); properties.setPadding(top, hor, bottom, hor); } else if (v.length > 3) { int top = Integer.parseInt(v[0]); int right = Integer.parseInt(v[1]); int bottom = Integer.parseInt(v[2]); int left = Integer.parseInt(v[3]); properties.setPadding(top, right, bottom, left); } } }; public final static PropertyReader<Component> CURSOR = new PropertyReader<Component>() { @Override public void read(Component component, Value value) { try { Field field = Cursor.class.getField(value.asString().toUpperCase() + "_CURSOR"); component.setCursor(Cursor.getPredefinedCursor(field.getInt(null))); } catch (Exception e) { //throw new RuntimeException(e); } } }; }
livingvirus/jphp
jphp-swing-ext/src/org/develnext/jphp/swing/loader/support/propertyreaders/ComponentPropertyReaders.java
Java
apache-2.0
8,211
/****************************************************************************** * Compilation: javac Counter.java * Execution: java Counter n trials * Dependencies: StdRandom.java StdOut.java * * A mutable data type for an integer counter. * * The test clients create n counters and performs trials increment * operations on random counters. * * java Counter 6 600000 * 100140 counter0 * 100273 counter1 * 99848 counter2 * 100129 counter3 * 99973 counter4 * 99637 counter5 * ******************************************************************************/ package algs4; /** * The {@code Counter} class is a mutable data type to encapsulate a counter. * <p> * For additional documentation, * see <a href="http://algs4.cs.princeton.edu/12oop">Section 1.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Counter implements Comparable<Counter> { private final String name; // counter name private int count = 0; // current value /** * Initializes a new counter starting at 0, with the given id. * * @param id the name of the counter */ public Counter(String id) { name = id; } /** * Increments the counter by 1. */ public void increment() { count++; } /** * Returns the current value of this counter. * * @return the current value of this counter */ public int tally() { return count; } /** * Returns a string representation of this counter. * * @return a string representation of this counter */ public String toString() { return count + " " + name; } /** * Compares this counter to the specified counter. * * @param that the other counter * @return {@code 0} if the value of this counter equals * the value of that counter; a negative integer if * the value of this counter is less than the value of * that counter; and a positive integer if the value * of this counter is greater than the value of that * counter */ @Override public int compareTo(Counter that) { if (this.count < that.count) return -1; else if (this.count > that.count) return +1; else return 0; } /** * Reads two command-line integers n and trials; creates n counters; * increments trials counters at random; and prints results. * * @param args the command-line arguments */ public static void main(String[] args) { int n = Integer.parseInt(args[0]); int trials = Integer.parseInt(args[1]); // create n counters Counter[] hits = new Counter[n]; for (int i = 0; i < n; i++) { hits[i] = new Counter("counter" + i); } // increment trials counters at random for (int t = 0; t < trials; t++) { hits[StdRandom.uniform(n)].increment(); } // print results for (int i = 0; i < n; i++) { StdOut.println(hits[i]); } } } /****************************************************************************** * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/
kefu-algorithm/study-practice-src
algorithm4rd-library/src/main/java/algs4/Counter.java
Java
apache-2.0
4,361
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * * Copyright 2018 Nextdoor.com, Inc * */ package com.nextdoor.bender.operation.substitution.regex; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonIgnore; import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaDefault; import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaDescription; import com.nextdoor.bender.operation.substitution.SubstitutionConfig; @JsonTypeName("RegexSubstitution") @JsonSchemaDescription("Substitutes event field value for another event field value. Note the source " + "field and destination field can be the same.") public class RegexSubstitutionConfig extends SubstitutionConfig { public RegexSubstitutionConfig() {} public static class RegexSubField { @JsonSchemaDescription("Regex group name identifying the field.") @JsonProperty(required = true) private String regexGroupName; @JsonSchemaDescription("Data type of match group field. If type coercion does not succeed then " + "field is ignored.") @JsonProperty(required = true) private RegexSubFieldType type; @JsonSchemaDescription("Name or path of the new field.") @JsonProperty(required = true) private String key; public static enum RegexSubFieldType { STRING, NUMBER, BOOLEAN } public RegexSubField() {} public RegexSubField(String regexGroupName, RegexSubFieldType type, String key) { this.regexGroupName = regexGroupName; this.type = type; this.key = key; } public String getRegexGroupName() { return this.regexGroupName; } public void setRegexGroupName(String regexGroupName) { this.regexGroupName = regexGroupName; } public RegexSubFieldType getType() { return type; } public void setType(RegexSubFieldType type) { this.type = type; } public String getKey() { return this.key; } public void setKey(String key) { this.key = key; } } public RegexSubstitutionConfig(List<String> srcFields, String pattern, List<RegexSubField> fields, boolean removeSrcField, boolean failSrcNotFound, boolean failDstNotFound) { super(null, failDstNotFound); this.srcFields = srcFields; this.pattern = pattern; this.fields = fields; this.removeSrcField = removeSrcField; this.failSrcNotFound = failSrcNotFound; } @JsonIgnore private String key; @JsonSchemaDescription("Regex pattern with match groups. See https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html") @JsonProperty(required = true) private String pattern; @JsonSchemaDescription("Source fields to pull value from and apply regex to. If multiple fields are provided the " + "first non-null valued one is used.") @JsonProperty(required = true) private List<String> srcFields; @JsonSchemaDescription("List of fields to create from matching regex groups.") @JsonSchemaDefault(value = "{}") @JsonProperty(required = true) private List<RegexSubField> fields = Collections.emptyList(); @JsonSchemaDescription("Removes the source field after applying this substitution.") @JsonSchemaDefault(value = "false") @JsonProperty(required = false) private Boolean removeSrcField = false; @JsonSchemaDescription("Fail if source fields do not match regex or are not found.") @JsonProperty(required = false) @JsonSchemaDefault(value = "true") private Boolean failSrcNotFound = true; public String getPattern() { return this.pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public void setSrcFields(List<String> srcFields) { this.srcFields = srcFields; } public List<String> getSrcFields() { return this.srcFields; } public List<RegexSubField> getFields() { return this.fields; } public void setFields(List<RegexSubField> fields) { this.fields = fields; } public Boolean getRemoveSrcField() { return this.removeSrcField; } public void setRemoveSrcField(Boolean removeSrcField) { this.removeSrcField = removeSrcField; } public Boolean getFailSrcNotFound() { return this.failSrcNotFound; } public void setFailSrcNotFound(Boolean failSrcNotFound) { this.failSrcNotFound = failSrcNotFound; } @Override public Class<RegexSubstitutionFactory> getFactoryClass() { return RegexSubstitutionFactory.class; } }
Nextdoor/bender
operations/src/main/java/com/nextdoor/bender/operation/substitution/regex/RegexSubstitutionConfig.java
Java
apache-2.0
5,098
// Copyright (C) 2013 Splunk Inc. // // Splunk 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.splunk.hunk.input; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.LinkedList; import java.util.Map; import java.util.regex.Pattern; import javax.imageio.ImageIO; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.BoundedInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import com.splunk.hunk.input.image.HsbBucketProcessor; import com.splunk.mr.input.BaseSplunkRecordReader; import com.splunk.mr.input.VixInputSplit; /** * Preprocesses images stored in a tar. Class contains all the plumbing needed * to read tar entries, send them to an {@link ImageEventProcessor} to create * "image events", to at last return them through the * {@link TgzImageRecordReader#getCurrentValue()}. */ public class TgzImageRecordReader extends BaseSplunkRecordReader { private static final Logger logger = Logger .getLogger(TgzImageRecordReader.class); private final LinkedList<Map<String, Object>> eventQueue = new LinkedList<Map<String, Object>>(); private Text key = new Text(); private Map<String, Object> value; private TarArchiveInputStream tarIn; private ImageEventProcessor imagePreProcessor; private final ObjectMapper objectMapper = new ObjectMapper(); private long totalBytesToRead; // -- Interesting stuff start here @Override public Pattern getFilePattern() { return Pattern.compile("\\.tgz$"); } @Override public void vixInitialize(VixInputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { FileSystem fs = FileSystem.get(context.getConfiguration()); tarIn = new TarArchiveInputStream(new GzipCompressorInputStream( fs.open(split.getPath()))); totalBytesToRead = split.getLength() - split.getStart(); imagePreProcessor = new HsbBucketProcessor(); } @Override public Text getCurrentValue() throws IOException, InterruptedException { return new Text(objectMapper.writeValueAsString(value)); } @Override public void serializeCurrentValueTo(OutputStream out) throws IOException, InterruptedException { objectMapper.writeValue(out, value); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { while (eventQueue.isEmpty() && thereAreBytesToRead()) tryPopulatingQueue(tarIn.getNextTarEntry()); if (!eventQueue.isEmpty()) { setNextValue(eventQueue.pop()); return true; } else { return false; } } private boolean thereAreBytesToRead() { return tarIn.getBytesRead() < totalBytesToRead; } private void tryPopulatingQueue(TarArchiveEntry entry) throws IOException { if (entry != null && isFile(entry)) putImageInQueue(entry); else tarIn.skip(entry.getSize()); } private boolean isFile(TarArchiveEntry entry) { return entry.isFile() && !entry.isLink(); } private void putImageInQueue(TarArchiveEntry entry) throws IOException { BufferedImage image = readImage(entry); if (image != null) eventQueue.offer(createImageEvent(entry, image)); else logger.warn("Could not read image: " + entry.getName()); } private BufferedImage readImage(TarArchiveEntry entry) throws IOException { return ImageIO.read(new BoundedInputStream(tarIn, entry.getSize())); } private Map<String, Object> createImageEvent(TarArchiveEntry entry, BufferedImage image) { Map<String, Object> imageData = imagePreProcessor .createEventFromImage(image); imageData.put("image", entry.getName()); return imageData; } private void setNextValue(Map<String, Object> event) throws IOException { value = event; } @Override public float getProgress() throws IOException, InterruptedException { return new Double(Utils.getPercentage(tarIn.getBytesRead(), totalBytesToRead)).floatValue(); } // -- The end of the interesting stuff @Override public void close() throws IOException { IOUtils.closeQuietly(tarIn); super.close(); } @Override public String getName() { return "image"; } @Override public Text getCurrentKey() throws IOException, InterruptedException { return key; } @Override public String getOutputDataFormat() { return "json"; } }
splunk/hunk-demo-image-reader
src/com/splunk/hunk/input/TgzImageRecordReader.java
Java
apache-2.0
5,149
/******************************************************************************* * 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.ofbiz.base.util.string; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.el.PropertyNotFoundException; import org.ofbiz.base.lang.IsEmpty; import org.ofbiz.base.lang.SourceMonitored; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.ObjectType; import org.ofbiz.base.util.ScriptUtil; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilFormatOut; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilNumber; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.cache.UtilCache; /** Expands String values that contain Unified Expression Language (JSR 245) * syntax. This class also supports the execution of Groovy scripts * by using the 'groovy:' prefix. * Further it is possible to control the output by specifying the suffix * '?currency(XX)' to format the output according to the supplied locale * and specified (XX) currency.<p>This class extends the UEL by allowing * nested expressions.</p> */ @SourceMonitored @SuppressWarnings("serial") public abstract class FlexibleStringExpander implements Serializable, IsEmpty { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); public static final String openBracket = "${"; public static final String closeBracket = "}"; protected static final UtilCache<Key, FlexibleStringExpander> exprCache = UtilCache.createUtilCache("flexibleStringExpander.ExpressionCache"); protected static final FlexibleStringExpander nullExpr = new ConstSimpleElem(new char[0]); /** * Returns <code>true</code> if <code>fse</code> contains a <code>String</code> constant. * @param fse The <code>FlexibleStringExpander</code> to test * @return <code>true</code> if <code>fse</code> contains a <code>String</code> constant */ public static boolean containsConstant(FlexibleStringExpander fse) { if (fse instanceof ConstSimpleElem || fse instanceof ConstOffsetElem) { return true; } if (fse instanceof Elements) { Elements fseElements = (Elements) fse; for (FlexibleStringExpander childElement : fseElements.childElems) { if (containsConstant(childElement)) { return true; } } } return false; } /** * Returns <code>true</code> if <code>fse</code> contains an expression. * @param fse The <code>FlexibleStringExpander</code> to test * @return <code>true</code> if <code>fse</code> contains an expression */ public static boolean containsExpression(FlexibleStringExpander fse) { return !(fse instanceof ConstSimpleElem); } /** * Returns <code>true</code> if <code>fse</code> contains a script. * @param fse The <code>FlexibleStringExpander</code> to test * @return <code>true</code> if <code>fse</code> contains a script */ public static boolean containsScript(FlexibleStringExpander fse) { if (fse instanceof ScriptElem) { return true; } if (fse instanceof Elements) { Elements fseElements = (Elements) fse; for (FlexibleStringExpander childElement : fseElements.childElems) { if (containsScript(childElement)) { return true; } } } return false; } /** * SCIPIO: Returns <code>true</code> if <code>fse</code> is only a <code>String</code> constant, * with no interpreted expressions or scripts (by this class). * <p> * Added 2018-09-19. * @param fse The <code>FlexibleStringExpander</code> to test * @return <code>true</code> if <code>fse</code> contains a <code>String</code> constant */ public static boolean isConstant(FlexibleStringExpander fse) { return (fse != null && fse.isConstant()); } /** * SCIPIO: Returns <code>true</code> if <code>this</code> is only a <code>String</code> constant, * with no interpreted expressions or scripts (by this class). * <p> * NOTE: We make the assumption that if fse were parsed to Elements, * one of them would always end up being a non-constant expression, so we can * avoid checking Elements recursively. * Basically this method is roughly the same as checking if the original contains an open bracket. * <p> * DEV NOTE: This is overridden to return true in the Const* subclasses below. * The others don't need to do anything. This makes this check basically free. * <p> * Added 2018-09-19. * @return <code>true</code> if this expander contains a <code>String</code> constant */ public boolean isConstant() { return false; } /** Evaluate an expression and return the result as a <code>String</code>. * Null expressions return <code>null</code>. * A null <code>context</code> argument will return the original expression. * <p>Note that the behavior of this method is not the same as using * <code>FlexibleStringExpander.getInstance(expression).expandString(context)</code> * because it returns <code>null</code> when given a null <code>expression</code> * argument, and * <code>FlexibleStringExpander.getInstance(expression).expandString(context)</code> * returns an empty <code>String</code>.</p> * * @param expression The original expression * @param context The evaluation context * @return The original expression's evaluation result as a <code>String</code> */ public static String expandString(String expression, Map<String, ? extends Object> context) { return expandString(expression, context, null, null); } /** Evaluate an expression and return the result as a <code>String</code>. * Null expressions return <code>null</code>. * A null <code>context</code> argument will return the original expression. * <p>Note that the behavior of this method is not the same as using * <code>FlexibleStringExpander.getInstance(expression).expandString(context, locale)</code> * because it returns <code>null</code> when given a null <code>expression</code> * argument, and * <code>FlexibleStringExpander.getInstance(expression).expandString(context, locale)</code> * returns an empty <code>String</code>.</p> * * @param expression The original expression * @param context The evaluation context * @param locale The locale to be used for localization * @return The original expression's evaluation result as a <code>String</code> */ public static String expandString(String expression, Map<String, ? extends Object> context, Locale locale) { return expandString(expression, context, null, locale); } /** Evaluate an expression and return the result as a <code>String</code>. * Null expressions return <code>null</code>. * A null <code>context</code> argument will return the original expression. * <p>Note that the behavior of this method is not the same as using * <code>FlexibleStringExpander.getInstance(expression).expandString(context, timeZone locale)</code> * because it returns <code>null</code> when given a null <code>expression</code> * argument, and * <code>FlexibleStringExpander.getInstance(expression).expandString(context, timeZone, locale)</code> * returns an empty <code>String</code>.</p> * * @param expression The original expression * @param context The evaluation context * @param timeZone The time zone to be used for localization * @param locale The locale to be used for localization * @return The original expression's evaluation result as a <code>String</code> */ public static String expandString(String expression, Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { if (expression == null) { return ""; } if (context == null || !expression.contains(openBracket)) { return expression; } FlexibleStringExpander fse = FlexibleStringExpander.getInstance(expression); return fse.expandString(context, timeZone, locale); } /** Returns a <code>FlexibleStringExpander</code> object. <p>A null or * empty argument will return a <code>FlexibleStringExpander</code> * object that represents an empty expression. That object is a shared * singleton, so there is no memory or performance penalty in using it.</p> * <p>If the method is passed a <code>String</code> argument that doesn't * contain an expression, the <code>FlexibleStringExpander</code> object * that is returned does not perform any evaluations on the original * <code>String</code> - any methods that return a <code>String</code> * will return the original <code>String</code>. The object returned by * this method is very compact - taking less memory than the original * <code>String</code>.</p> * * @param expression The original expression * @return A <code>FlexibleStringExpander</code> instance */ public static FlexibleStringExpander getInstance(String expression) { return getInstance(expression, true); } /* Returns a <code>FlexibleStringExpander</code> object. <p>A null or * empty argument will return a <code>FlexibleStringExpander</code> * object that represents an empty expression. That object is a shared * singleton, so there is no memory or performance penalty in using it.</p> * <p>If the method is passed a <code>String</code> argument that doesn't * contain an expression, the <code>FlexibleStringExpander</code> object * that is returned does not perform any evaluations on the original * <code>String</code> - any methods that return a <code>String</code> * will return the original <code>String</code>. The object returned by * this method is very compact - taking less memory than the original * <code>String</code>.</p> * * @param expression The original expression * @param useCache whether to store things into a global cache * @return A <code>FlexibleStringExpander</code> instance */ public static FlexibleStringExpander getInstance(String expression, boolean useCache) { if (UtilValidate.isEmpty(expression)) { return nullExpr; } return getInstance(expression, expression.toCharArray(), 0, expression.length(), useCache); } private static FlexibleStringExpander getInstance(String expression, char[] chars, int offset, int length, boolean useCache) { if (length == 0) { return nullExpr; } if (!useCache) { return parse(chars, offset, length); } // Remove the next nine lines to cache all expressions if (!expression.contains(openBracket)) { if (chars.length == length) { return new ConstSimpleElem(chars); } else { return new ConstOffsetElem(chars, offset, length); } } Key key = chars.length == length ? new SimpleKey(chars) : new OffsetKey(chars, offset, length); FlexibleStringExpander fse = exprCache.get(key); if (fse == null) { exprCache.put(key, parse(chars, offset, length)); fse = exprCache.get(key); } return fse; } /** * SCIPIO: Returns an instance that produces null on {@link FlexibleStringExpander#get} * and empty string on {@link FlexibleStringExpander#expandString}. * <p> * This is the same as <code>getInstance("")</code> but cleaner. * <p> * Added 2018-09-20. */ public static FlexibleStringExpander getEmptyExpr() { return nullExpr; } private static abstract class Key { @Override public final boolean equals(Object o) { // No class test here, nor null, as this class is only used // internally return toString().equals(o.toString()); } @Override public final int hashCode() { return toString().hashCode(); } } private static final class SimpleKey extends Key { private final char[] chars; protected SimpleKey(char[] chars) { this.chars = chars; } @Override public String toString() { return new String(chars); } } private static final class OffsetKey extends Key { private final char[] chars; private final int offset; private final int length; protected OffsetKey(char[] chars, int offset, int length) { this.chars = chars; this.offset = offset; this.length = length; } @Override public String toString() { return new String(chars, offset, length); } } private static FlexibleStringExpander parse(char[] chars, int offset, int length) { FlexibleStringExpander[] strElems = getStrElems(chars, offset, length); if (strElems.length == 1) { return strElems[0]; } else { return new Elements(chars, offset, length, strElems); } } protected static FlexibleStringExpander[] getStrElems(char[] chars, int offset, int length) { String expression = new String(chars, 0, length + offset); int start = expression.indexOf(openBracket, offset); if (start == -1) { return new FlexibleStringExpander[] { new ConstOffsetElem(chars, offset, length) }; } int origLen = length; ArrayList<FlexibleStringExpander> strElems = new ArrayList<FlexibleStringExpander>(); int currentInd = offset; int end = -1; while (start != -1) { end = expression.indexOf(closeBracket, start); if (end == -1) { Debug.logWarning("Found a ${ without a closing } (curly-brace) in the String: " + expression, module); break; } // Check for escaped expression boolean escapedExpression = (start - 1 >= 0 && expression.charAt(start - 1) == '\\'); if (start > currentInd) { // append everything from the current index to the start of the expression strElems.add(new ConstOffsetElem(chars, currentInd, (escapedExpression ? start -1 : start) - currentInd)); } if (expression.indexOf("bsh:", start + 2) == start + 2 && !escapedExpression) { // SCIPIO: 2018-09-19: This should be avoided at all costs from now on Debug.logWarning("Deprecated Beanshell script prefix (${bsh:...}) detected in " + "Flexible expression; this is a compatibility mode only (runs as Groovy); " + "please update code to use ${groovy:...}", module); // checks to see if this starts with a "bsh:", if so treat the rest of the expression as a bsh scriptlet strElems.add(new ScriptElem(chars, start, Math.min(end + 1, start + length) - start, start + 6, end - start - 6)); } else if (expression.indexOf("groovy:", start + 2) == start + 2 && !escapedExpression) { // checks to see if this starts with a "groovy:", if so treat the rest of the expression as a groovy scriptlet strElems.add(new ScriptElem(chars, start, Math.min(end + 1, start + length) - start, start + 9, end - start - 9)); } else { // Scan for matching closing bracket int ptr = expression.indexOf("{", start + 2); while (ptr != -1 && end != -1 && ptr < end) { end = expression.indexOf(closeBracket, end + 1); ptr = expression.indexOf("{", ptr + 1); } if (end == -1) { end = origLen; } // Evaluation sequence is important - do not change it if (escapedExpression) { strElems.add(new ConstOffsetElem(chars, start, end + 1 - start)); } else { String subExpression = expression.substring(start + 2, end); int currencyPos = subExpression.indexOf("?currency("); int closeParen = currencyPos > 0 ? subExpression.indexOf(")", currencyPos + 10) : -1; if (closeParen != -1) { strElems.add(new CurrElem(chars, start, Math.min(end + 1, start + length) - start, start + 2, end - start - 1)); } else if (subExpression.contains(openBracket)) { strElems.add(new NestedVarElem(chars, start, Math.min(end + 1, start + length) - start, start + 2, Math.min(end - 2, start + length) - start)); } else { strElems.add(new VarElem(chars, start, Math.min(end + 1, start + length) - start, start + 2, Math.min(end - 2, start + length) - start)); } } } // reset the current index to after the expression, and the start to the beginning of the next expression currentInd = end + 1; if (currentInd > origLen + offset) { currentInd = origLen + offset; } start = expression.indexOf(openBracket, currentInd); } // append the rest of the original string, ie after the last expression if (currentInd < origLen + offset) { strElems.add(new ConstOffsetElem(chars, currentInd, offset + length - currentInd)); } return strElems.toArray(new FlexibleStringExpander[strElems.size()]); } // Note: a character array is used instead of a String to keep the memory footprint small. protected final char[] chars; protected int hint = 20; protected FlexibleStringExpander(char[] chars) { this.chars = chars; } protected abstract Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale); private static Locale getLocale(Locale locale, Map<String, ? extends Object> context) { if (locale == null) { locale = (Locale) context.get("locale"); if (locale == null && context.containsKey("autoUserLogin")) { Map<String, Object> autoUserLogin = UtilGenerics.cast(context.get("autoUserLogin")); locale = UtilMisc.ensureLocale(autoUserLogin.get("lastLocale")); } if (locale == null) { locale = Locale.getDefault(); } } return locale; } private static TimeZone getTimeZone(TimeZone timeZone, Map<String, ? extends Object> context) { if (timeZone == null) { timeZone = (TimeZone) context.get("timeZone"); if (timeZone == null && context.containsKey("autoUserLogin")) { Map<String, String> autoUserLogin = UtilGenerics.cast(context.get("autoUserLogin")); timeZone = UtilDateTime.toTimeZone(autoUserLogin.get("lastTimeZone")); } if (timeZone == null) { timeZone = TimeZone.getDefault(); } } return timeZone; } /** Evaluate this object's expression and return the result as a <code>String</code>. * Null or empty expressions return an empty <code>String</code>. * A <code>null context</code> argument will return the original expression. * * @param context The evaluation context * @return This object's expression result as a <code>String</code> */ public String expandString(Map<String, ? extends Object> context) { return this.expandString(context, null, null); } /** Evaluate this object's expression and return the result as a <code>String</code>. * Null or empty expressions return an empty <code>String</code>. * A <code>null context</code> argument will return the original expression. * * @param context The evaluation context * @param locale The locale to be used for localization * @return This object's expression result as a <code>String</code> */ public String expandString(Map<String, ? extends Object> context, Locale locale) { return this.expandString(context, null, locale); } /** Evaluate this object's expression and return the result as a <code>String</code>. * Null or empty expressions return an empty <code>String</code>. * A <code>null context</code> argument will return the original expression. * * @param context The evaluation context * @param timeZone The time zone to be used for localization * @param locale The locale to be used for localization * @return This object's expression result as a <code>String</code> */ public String expandString(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { if (context == null) { return this.toString(); } timeZone = getTimeZone(timeZone, context); locale = getLocale(locale, context); Object obj = get(context, timeZone, locale); StringBuilder buffer = new StringBuilder(this.hint); try { if (obj != null) { if (obj instanceof String) { buffer.append(obj); } else { buffer.append(ObjectType.simpleTypeConvert(obj, "String", null, timeZone, locale, true)); } } } catch (GeneralException | RuntimeException e) { Debug.log(e, module); buffer.append(obj); } if (buffer.length() > this.hint) { this.hint = buffer.length(); } return buffer.toString(); } /** Evaluate this object's expression and return the result as an <code>Object</code>. * Null or empty expressions return an empty <code>String</code>. * A <code>null context</code> argument will return the original expression. * * @param context The evaluation context * @return This object's expression result as a <code>String</code> */ public Object expand(Map<String, ? extends Object> context) { return this.expand(context, null, null); } /** Evaluate this object's expression and return the result as an <code>Object</code>. * Null or empty expressions return an empty <code>String</code>. * A <code>null context</code> argument will return the original expression. * * @param context The evaluation context * @param locale The locale to be used for localization * @return This object's expression result as a <code>String</code> */ public Object expand(Map<String, ? extends Object> context, Locale locale) { return this.expand(context, null, locale); } /** Evaluate this object's expression and return the result as an <code>Object</code>. * Null or empty expressions return an empty <code>String</code>. * A <code>null context</code> argument will return the original expression. * * @param context The evaluation context * @param timeZone The time zone to be used for localization * @param locale The locale to be used for localization * @return This object's expression result as a <code>String</code> */ public Object expand(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { if (context == null) { return null; } return get(context, getTimeZone(timeZone, context), getLocale(locale, context)); } /** Returns a copy of the original expression. * * @return The original expression */ public abstract String getOriginal(); /** Returns <code>true</code> if the original expression is empty * or <code>null</code>. * * @return <code>true</code> if the original expression is empty * or <code>null</code> */ public abstract boolean isEmpty(); /** Returns a copy of the original expression. * * @return The original expression */ @Override public String toString() { return this.getOriginal(); } protected static abstract class ArrayOffsetString extends FlexibleStringExpander { protected final int offset; protected final int length; protected ArrayOffsetString(char[] chars, int offset, int length) { super(chars); this.offset = offset; this.length = length; } @Override public boolean isEmpty() { // This is always false; the complex child classes can't be // empty, as they contain at least ${; constant elements // with a length of 0 will never be created. return false; } @Override public String getOriginal() { return new String(this.chars, this.offset, this.length); } } /** An object that represents a <code>String</code> constant portion of an expression. */ protected static class ConstSimpleElem extends FlexibleStringExpander { protected ConstSimpleElem(char[] chars) { super(chars); } @Override public boolean isEmpty() { return this.chars.length == 0; } @Override public String getOriginal() { return new String(this.chars); } @Override public String expandString(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { return getOriginal(); } @Override protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { return isEmpty() ? null : getOriginal(); } @Override public boolean isConstant() { // SCIPIO: Added 2018-09-19 return true; } } /** An object that represents a <code>String</code> constant portion of an expression. */ protected static class ConstOffsetElem extends ArrayOffsetString { protected ConstOffsetElem(char[] chars, int offset, int length) { super(chars, offset, length); } @Override protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { return getOriginal(); } @Override public String expandString(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { return new String(this.chars, this.offset, this.length); } @Override public boolean isConstant() { // SCIPIO: Added 2018-09-19 return true; } } /** An object that represents a currency portion of an expression. */ protected static class CurrElem extends ArrayOffsetString { protected final char[] valueStr; protected final FlexibleStringExpander codeExpr; protected CurrElem(char[] chars, int offset, int length, int parseStart, int parseLength) { super(chars, offset, length); String parse = new String(chars, parseStart, parseLength); int currencyPos = parse.indexOf("?currency("); int closeParen = parse.indexOf(")", currencyPos + 10); this.codeExpr = FlexibleStringExpander.getInstance(parse, chars, parseStart + currencyPos + 10, closeParen - currencyPos - 10, true); this.valueStr = openBracket.concat(parse.substring(0, currencyPos)).concat(closeBracket).toCharArray(); } @Override protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { try { Object obj = UelUtil.evaluate(context, new String(this.valueStr)); if (obj != null) { String currencyCode = this.codeExpr.expandString(context, timeZone, locale); // SCIPIO: 2017-01-13: added BigDecimal instanceof check to avoid string overhead and potential loss of information if (obj instanceof BigDecimal) { return UtilFormatOut.formatCurrency((BigDecimal) obj, currencyCode, locale); } return UtilFormatOut.formatCurrency(new BigDecimal(obj.toString()), currencyCode, locale); } } catch (PropertyNotFoundException e) { if (Debug.verboseOn()) { Debug.logVerbose("Error evaluating expression: " + e, module); } } catch (Exception e) { Debug.logError("Error evaluating expression: " + e, module); } return null; } } /** A container object that contains expression fragments. */ protected static class Elements extends ArrayOffsetString { protected final FlexibleStringExpander[] childElems; protected Elements(char[] chars, int offset, int length, FlexibleStringExpander[] childElems) { super(chars, offset, length); this.childElems = childElems; } @Override protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { StringBuilder buffer = new StringBuilder(); for (FlexibleStringExpander child : this.childElems) { buffer.append(child.expandString(context, timeZone, locale)); } return buffer.toString(); } } /** An object that represents a <code>${[groovy|bsh]:}</code> expression. */ protected static class ScriptElem extends ArrayOffsetString { private final String language; private final int parseStart; private final int parseLength; private final String script; protected final Class<?> parsedScript; protected ScriptElem(char[] chars, int offset, int length, int parseStart, int parseLength) { super(chars, offset, length); this.language = new String(this.chars, offset + 2, parseStart - offset - 3); this.parseStart = parseStart; this.parseLength = parseLength; this.script = new String(this.chars, this.parseStart, this.parseLength); this.parsedScript = ScriptUtil.parseScript(this.language, this.script); } @Override protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { try { Map <String, Object> contextCopy = new HashMap<String, Object>(context); Object obj = ScriptUtil.evaluate(this.language, this.script, this.parsedScript, contextCopy); if (obj != null) { return obj; } else { if (Debug.verboseOn()) { Debug.logVerbose("Scriptlet evaluated to null [" + this + "].", module); } } } catch (Exception e) { Debug.logWarning(e, "Error evaluating scriptlet [" + this + "]; error was: " + e, module); } return null; } } /** An object that represents a nested expression. */ protected static class NestedVarElem extends ArrayOffsetString { protected final FlexibleStringExpander[] childElems; protected NestedVarElem(char[] chars, int offset, int length, int parseStart, int parseLength) { super(chars, offset, length); this.childElems = getStrElems(chars, parseStart, parseLength); if (length > this.hint) { this.hint = length; } } @Override protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { StringBuilder expr = new StringBuilder(this.hint); for (FlexibleStringExpander child : this.childElems) { expr.append(child.expandString(context, timeZone, locale)); } if (expr.length() == 0) { return ""; } try { return UelUtil.evaluate(context, openBracket.concat(expr.toString()).concat(closeBracket)); } catch (PropertyNotFoundException e) { if (Debug.verboseOn()) { Debug.logVerbose("Error evaluating expression: " + e, module); } } catch (Exception e) { Debug.logError("Error evaluating expression: " + e, module); } return ""; } } /** An object that represents a simple, non-nested expression. */ protected static class VarElem extends ArrayOffsetString { protected final char[] bracketedOriginal; protected VarElem(char[] chars, int offset, int length, int parseStart, int parseLength) { super(chars, offset, length); this.bracketedOriginal = openBracket.concat(UelUtil.prepareExpression(new String(chars, parseStart, parseLength))).concat(closeBracket).toCharArray(); } @Override protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) { Object obj = null; try { obj = UelUtil.evaluate(context, new String(this.bracketedOriginal)); } catch (PropertyNotFoundException e) { if (Debug.verboseOn()) { Debug.logVerbose("Error evaluating expression " + this + ": " + e, module); } } catch (Exception e) { Debug.logError("Error evaluating expression " + this + ": " + e, module); } return obj; } } /** * DO NOT USE: Returns a "dummy" static instance, for use by <code>FreeMarkerWorker</code>. * Subject to change without notice. * SCIPIO: 2.1.0: Added. */ public static FlexibleStringExpander getStaticInstance() { return nullExpr; } }
ilscipio/scipio-erp
framework/base/src/org/ofbiz/base/util/string/FlexibleStringExpander.java
Java
apache-2.0
35,405
package org.mcupdater.translate; public abstract class TranslateProxy { public String instances = "#MISSING#"; public String update = "#MISSING#"; public String launchMinecraft = "#MISSING#"; public String news = "#MISSING#"; public String console = "#MISSING#"; public String settings = "#MISSING#"; public String modules = "#MISSING#"; public String progress = "#MISSING"; public String minMemory = "#MISSING#"; public String maxMemory = "#MISSING#"; public String permGen = "#MISSING#"; public String memDisclaimer = "#MISSING#"; public String resolution = "#MISSING#"; public String javaHome = "#MISSING#"; public String browse = "#MISSING#"; public String jvmOpts = "#MISSING#"; public String instancePath = "#MISSING#"; public String programWrapper = "#MISSING#"; public String minimize = "#MISSING#"; public String autoConnect = "#MISSING#"; public String definedPacks = "#MISSING#"; public String fullscreen = "#MISSING#"; public String save = "#MISSING#"; public String reload = "#MISSING#"; public String back = "#MISSING#"; public String profile = "#MISSING#"; public String profiles = "#MISSING#"; public String add = "#MISSING#"; public String remove = "#MISSING#"; public String addProfile = "#MISSING#"; public String username = "#MISSING#"; public String password = "#MISSING#"; public String login = "#MISSING#"; public String cancel = "#MISSING#"; public String updateRequired = "#MISSING#"; public String oldMCUpdater = "#MISSING#"; }
MCUpdater/MCUpdater
MCU-EndUser/src/org/mcupdater/translate/TranslateProxy.java
Java
apache-2.0
1,491
/******************************************************************************* * Copyright (C) 2014, International Business Machines Corporation * All Rights Reserved *******************************************************************************/ package com.ibm.streamsx.patterns.operator; import com.ibm.streams.operator.AbstractOperator; import com.ibm.streams.operator.OperatorContext; import com.ibm.streams.operator.OperatorContext.ContextCheck; import com.ibm.streams.operator.StreamingData; import com.ibm.streams.operator.StreamingInput; import com.ibm.streams.operator.Tuple; import com.ibm.streams.operator.compile.OperatorContextChecker; import com.ibm.streams.operator.model.InputPortSet; import com.ibm.streams.operator.model.InputPorts; import com.ibm.streams.operator.model.OutputPortSet; import com.ibm.streams.operator.model.OutputPortSet.WindowPunctuationOutputMode; import com.ibm.streams.operator.model.OutputPorts; /** * Pattern that splits the stream into multiple output streams. * <P> * The schema of all output ports must exactly * match the schema of the input port. * */ @InputPorts(@InputPortSet(cardinality=1,id="input", description="Tuples to be split across multiple output ports.")) @OutputPorts({ @OutputPortSet(cardinality=1,description="Output ports the input is split into.", windowPunctuationOutputMode=WindowPunctuationOutputMode.Preserving, windowPunctuationInputPort="input"), @OutputPortSet(optional=true,description="Additional output ports the input is split into.") }) public abstract class Split extends AbstractOperator { private int outputPortCount; /** * {@inheritDoc} * <P> * Obtains the number of output ports for the mod * operation performed against the return of {@link #destination(Tuple)}. * </P> */ @Override public void initialize(OperatorContext context) throws Exception { super.initialize(context); outputPortCount = context.getNumberOfStreamingOutputs(); } /** * Invokes {@link #filter(Tuple)} on {@code tuple}. If it * returns {@code true} then the tuple is submitted to the * first output port. If it returns {@code false} then * the tuple is submitted to the second output port if it exists, * otherwise it is discarded. */ @Override public void process(StreamingInput<Tuple> stream, final Tuple tuple) throws Exception { final int destination = destination(tuple); if (destination >= 0) getOutput(destination % outputPortCount).submit(tuple); } /** * Determine the destination index for the tuple. * <BR> * If the index returned is less than zero then * {@code tuple} is discarded. * <BR> * Otherwise the returned index determines which output * port the tuple is submitted to. The index is modded ({@code %}) * by the number of output ports to return the * index (zero-based) of the output port the * tuple is submitted to. * * @param tuple Tuple to be filtered. * @return Destination index for {@code tuple}. * @throws Exception Exception determining the tuple's destination. */ protected abstract int destination(Tuple tuple) throws Exception; /** * Check that the schemas for all output * ports match the first input port, as the tuples are directly * submitted from the input to the output. * @param checker Context checker object. */ @ContextCheck public static void checkMatchingSchemas(OperatorContextChecker checker) { OperatorContext context = checker.getOperatorContext(); StreamingData inputPort = context.getStreamingInputs().get(0); for (StreamingData outputPort : context.getStreamingOutputs()) checker.checkMatchingSchemas(inputPort, outputPort); } }
ddebrunner/streamsx.patterns
java/src/com/ibm/streamsx/patterns/operator/Split.java
Java
apache-2.0
3,688
/* * #%L * wcm.io * %% * Copyright (C) 2015 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.wcm.caravan.jaxrs.publisher.sampleservice1; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.osgi.service.component.ComponentContext; import io.wcm.caravan.jaxrs.publisher.ApplicationPath; import io.wcm.caravan.jaxrs.publisher.JaxRsComponent; /** * Sample JAX-RS Service */ @Component(immediate = true) @Service(JaxRsComponent.class) @Path("/serviceId") public class JaxRsService implements JaxRsComponent { private String serviceId; @Activate protected void activate(ComponentContext componentContext) { serviceId = ApplicationPath.get(componentContext); } /** * @return Returns service id detected from OSGi component context */ @GET @Produces("text/plain") public String getServiceId() { return serviceId; } }
wcm-io-caravan/caravan-jaxrs
integration-test/sample-service-1/src/main/java/io/wcm/caravan/jaxrs/publisher/sampleservice1/JaxRsService.java
Java
apache-2.0
1,584
package com.yin.myproject.demo.jvm.chapter07; /** * Created by Eason on 2017/1/5. * * 通过数组来引用类,不会触发类的初始化 */ public class NotInitializationDemo2 { public static void main(String[] args) { SuperClass[] arr = new SuperClass[10]; } }
SmallBadFish/demo
src/main/java/com/yin/myproject/demo/jvm/chapter07/NotInitializationDemo2.java
Java
apache-2.0
288
/* * Copyright 2017 David Karnok * * 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 hu.akarnokd.reactive4javaflow.impl.consumers; import hu.akarnokd.reactive4javaflow.Folyam; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.Assert.*; public class BlockingFirstConsumerTest { @Test public void normal() { Assert.assertEquals(1, Folyam.just(1) .blockingFirst().get().intValue()); } @Test public void normal2() { assertEquals(1, Folyam.just(1) .blockingFirst(1, TimeUnit.MINUTES).get().intValue()); } @Test public void normal3() { assertEquals(1, Folyam.range(1, 5) .blockingFirst().get().intValue()); } @Test public void empty() { assertFalse(Folyam.empty().blockingFirst().isPresent()); } @Test(expected = IllegalArgumentException.class) public void blockingFirstError() { Folyam.error(new IllegalArgumentException()).blockingFirst(); } @Test(expected = InternalError.class) public void blockingFirstError2() { Folyam.error(new InternalError()).blockingFirst(); } @Test public void blockingFirstError3() { try { Folyam.error(new IOException()).blockingFirst(); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof IOException)) { throw new AssertionError("Wrong exception", ex); } } } @Test(expected = IllegalArgumentException.class) public void blockingFirstErrorTimeout() { Folyam.error(new IllegalArgumentException()).blockingFirst(1, TimeUnit.MINUTES); } @Test(expected = InternalError.class) public void blockingFirstErrorTimeout2() { Folyam.error(new InternalError()).blockingFirst(1, TimeUnit.MINUTES); } @Test public void blockingFirstErrorTimeout3() { try { Folyam.error(new IOException()).blockingFirst(1, TimeUnit.MINUTES); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof IOException)) { throw new AssertionError("Wrong exception", ex); } } } @Test public void timeout() { try { Folyam.never().blockingFirst(1, TimeUnit.MILLISECONDS); fail("Should have thrown"); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof TimeoutException)) { throw new AssertionError("Wrong exception", ex); } } } @Test public void interrupt() { Thread.currentThread().interrupt(); try { Folyam.never().blockingFirst(5, TimeUnit.SECONDS); fail("Should have thrown"); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof InterruptedException)) { throw new AssertionError("Wrong exception", ex); } } } @Test(timeout = 5000) public void interrupt2() { Thread.currentThread().interrupt(); try { Folyam.never().blockingFirst(); fail("Should have thrown"); } catch (RuntimeException ex) { if (!(ex.getCause() instanceof InterruptedException)) { throw new AssertionError("Wrong exception", ex); } } } @Test public void defaultValue() { assertEquals(1, Folyam.<Integer>empty().blockingFirst(1).intValue()); } }
akarnokd/Reactive4JavaFlow
src/test/java/hu/akarnokd/reactive4javaflow/impl/consumers/BlockingFirstConsumerTest.java
Java
apache-2.0
4,131
/** * Copyright 2012 Twitter, 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 parquet.io; import static parquet.Log.DEBUG; import parquet.Log; import parquet.column.ColumnReadStore; import parquet.io.RecordReaderImplementation.State; import parquet.io.convert.RecordConverter; // TODO(julien): this class appears to be unused -- can it be nuked? - todd public abstract class BaseRecordReader<T> extends RecordReader<T> { private static final Log LOG = Log.getLog(BaseRecordReader.class); public RecordConsumer recordConsumer; public RecordConverter<T> recordMaterializer; public ColumnReadStore columnStore; @Override public T read() { readOneRecord(); return recordMaterializer.getCurrentRecord(); } protected abstract void readOneRecord(); State[] caseLookup; private String endField; private int endIndex; protected void currentLevel(int currentLevel) { if (DEBUG) LOG.debug("currentLevel: "+currentLevel); } protected void log(String message) { if (DEBUG) LOG.debug("bc: "+message); } final protected int getCaseId(int state, int currentLevel, int d, int nextR) { return caseLookup[state].getCase(currentLevel, d, nextR).getID(); } final protected void startMessage() { // reset state endField = null; if (DEBUG) LOG.debug("startMessage()"); recordConsumer.startMessage(); } final protected void startGroup(String field, int index) { startField(field, index); if (DEBUG) LOG.debug("startGroup()"); recordConsumer.startGroup(); } private void startField(String field, int index) { if (DEBUG) LOG.debug("startField("+field+","+index+")"); if (endField != null && index == endIndex) { // skip the close/open tag endField = null; } else { if (endField != null) { // close the previous field recordConsumer.endField(endField, endIndex); endField = null; } recordConsumer.startField(field, index); } } final protected void addPrimitiveINT64(String field, int index, long value) { startField(field, index); if (DEBUG) LOG.debug("addLong("+value+")"); recordConsumer.addLong(value); endField(field, index); } private void endField(String field, int index) { if (DEBUG) LOG.debug("endField("+field+","+index+")"); if (endField != null) { recordConsumer.endField(endField, endIndex); } endField = field; endIndex = index; } final protected void addPrimitiveBINARY(String field, int index, Binary value) { startField(field, index); if (DEBUG) LOG.debug("addBinary("+value+")"); recordConsumer.addBinary(value); endField(field, index); } final protected void addPrimitiveINT32(String field, int index, int value) { startField(field, index); if (DEBUG) LOG.debug("addInteger("+value+")"); recordConsumer.addInteger(value); endField(field, index); } final protected void endGroup(String field, int index) { if (endField != null) { // close the previous field recordConsumer.endField(endField, endIndex); endField = null; } if (DEBUG) LOG.debug("endGroup()"); recordConsumer.endGroup(); endField(field, index); } final protected void endMessage() { if (endField != null) { // close the previous field recordConsumer.endField(endField, endIndex); endField = null; } if (DEBUG) LOG.debug("endMessage()"); recordConsumer.endMessage(); } protected void error(String message) { throw new ParquetDecodingException(message); } }
julienledem/redelm
parquet-column/src/main/java/parquet/io/BaseRecordReader.java
Java
apache-2.0
4,096
package mytranslate; public class TranslateConf { public static String TRANSLATEPLATFORM = ""; public static String BAIDU_APP_ID = ""; public static String BAIDU_SECURITY_KEY = ""; public static String YOUDAO_KEYFROM = ""; public static String YOUDAO_KEY = ""; public static String YOUDAO_TYPE = "data"; public static String YOUDAO_DOCTYPE = "json"; public static String YOUDAO_VERSION = "1.1"; public static String YOUDAO_HOST = "http://fanyi.youdao.com/openapi.do"; /** * 自动检测 */ public static final String AUTO = "auto"; /** * 中文 */ public static final String ZH = "zh"; /** * 英文 */ public static final String EN = "en"; }
Julyme/myTranslate
src/mytranslate/TranslateConf.java
Java
apache-2.0
771
/* * Copyright (C) 2015 Haruki Hasegawa * * 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.h6ah4i.android.widget.advrecyclerview.expandable; import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange; import androidx.annotation.NonNull; public class ChildPositionItemDraggableRange extends ItemDraggableRange { public ChildPositionItemDraggableRange(int start, int end) { super(start, end); } @NonNull protected String getClassName() { return "ChildPositionItemDraggableRange"; } }
h6ah4i/android-advancedrecyclerview
library/src/main/java/com/h6ah4i/android/widget/advrecyclerview/expandable/ChildPositionItemDraggableRange.java
Java
apache-2.0
1,096
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl.protocol.codec.builtin; import com.hazelcast.client.impl.protocol.ClientMessage; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.INT_SIZE_IN_BYTES; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.decodeInteger; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.encodeInteger; public final class ListIntegerCodec { private ListIntegerCodec() { } public static void encode(ClientMessage clientMessage, Collection<Integer> collection) { int itemCount = collection.size(); ClientMessage.Frame frame = new ClientMessage.Frame(new byte[itemCount * INT_SIZE_IN_BYTES]); Iterator<Integer> iterator = collection.iterator(); for (int i = 0; i < itemCount; i++) { encodeInteger(frame.content, i * INT_SIZE_IN_BYTES, iterator.next()); } clientMessage.add(frame); } public static List<Integer> decode(ClientMessage.ForwardFrameIterator iterator) { return decode(iterator.next()); } public static List<Integer> decode(ClientMessage.Frame frame) { int itemCount = frame.content == null ? 0 : frame.content.length / INT_SIZE_IN_BYTES; List<Integer> result = new ArrayList<>(itemCount); for (int i = 0; i < itemCount; i++) { result.add(decodeInteger(frame.content, i * INT_SIZE_IN_BYTES)); } return result; } }
mesutcelik/hazelcast
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/builtin/ListIntegerCodec.java
Java
apache-2.0
2,226
/* * EVE Swagger Interface * An OpenAPI for EVE Online * * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package net.troja.eve.esi.model; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.time.OffsetDateTime; import net.troja.eve.esi.model.CorporationBookmarkItem; import net.troja.eve.esi.model.CorporationBookmarksCoordinates; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for CorporationBookmarksResponse */ public class CorporationBookmarksResponseTest { private final CorporationBookmarksResponse model = new CorporationBookmarksResponse(); /** * Model tests for CorporationBookmarksResponse */ @Test public void testCorporationBookmarksResponse() { // TODO: test CorporationBookmarksResponse } /** * Test the property 'bookmarkId' */ @Test public void bookmarkIdTest() { // TODO: test bookmarkId } /** * Test the property 'item' */ @Test public void itemTest() { // TODO: test item } /** * Test the property 'notes' */ @Test public void notesTest() { // TODO: test notes } /** * Test the property 'created' */ @Test public void createdTest() { // TODO: test created } /** * Test the property 'coordinates' */ @Test public void coordinatesTest() { // TODO: test coordinates } /** * Test the property 'creatorId' */ @Test public void creatorIdTest() { // TODO: test creatorId } /** * Test the property 'label' */ @Test public void labelTest() { // TODO: test label } /** * Test the property 'folderId' */ @Test public void folderIdTest() { // TODO: test folderId } /** * Test the property 'locationId' */ @Test public void locationIdTest() { // TODO: test locationId } }
burberius/eve-esi
src/test/java/net/troja/eve/esi/model/CorporationBookmarksResponseTest.java
Java
apache-2.0
2,407
/* * Copyright 2016-2017 Testify Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.testifyproject; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.Before; import org.junit.Test; import org.mockito.Answers; /** * * @author saden */ public class MockProviderTest { MockProvider sut; @Before public void init() { sut = mock(MockProvider.class, Answers.CALLS_REAL_METHODS); } @Test public void callToCreateVirtualSutShouldCallCreateVirtual() { Class type = Object.class; Object delegate = new Object(); Object virtualInstance = new Object(); given(sut.createVirtual(type, delegate)).willReturn(virtualInstance); Object result = sut.createVirtualSut(type, delegate); assertThat(result).isEqualTo(virtualInstance); verify(sut).createVirtualSut(type, delegate); verify(sut).createVirtual(type, delegate); verifyNoMoreInteractions(sut); } }
testify-project/testify
modules/api/src/test/java/org/testifyproject/MockProviderTest.java
Java
apache-2.0
1,702
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.procedure; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.hadoop.hbase.SmallTests; import org.apache.hadoop.hbase.errorhandling.ForeignException; import org.apache.hadoop.hbase.errorhandling.ForeignExceptionDispatcher; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Demonstrate how Procedure handles single members, multiple members, and errors semantics */ @Category(SmallTests.class) public class TestProcedure { ProcedureCoordinator coord; @Before public void setup() { coord = mock(ProcedureCoordinator.class); final ProcedureCoordinatorRpcs comms = mock(ProcedureCoordinatorRpcs.class); when(coord.getRpcs()).thenReturn(comms); // make it not null } class LatchedProcedure extends Procedure { CountDownLatch startedAcquireBarrier = new CountDownLatch(1); CountDownLatch startedDuringBarrier = new CountDownLatch(1); CountDownLatch completedProcedure = new CountDownLatch(1); public LatchedProcedure(ProcedureCoordinator coord, ForeignExceptionDispatcher monitor, long wakeFreq, long timeout, String opName, byte[] data, List<String> expectedMembers) { super(coord, monitor, wakeFreq, timeout, opName, data, expectedMembers); } @Override public void sendGlobalBarrierStart() { startedAcquireBarrier.countDown(); } @Override public void sendGlobalBarrierReached() { startedDuringBarrier.countDown(); } @Override public void sendGlobalBarrierComplete() { completedProcedure.countDown(); } }; /** * With a single member, verify ordered execution. The Coordinator side is run in a separate * thread so we can only trigger from members and wait for particular state latches. */ @Test(timeout = 60000) public void testSingleMember() throws Exception { // The member List<String> members = new ArrayList<String>(); members.add("member"); LatchedProcedure proc = new LatchedProcedure(coord, new ForeignExceptionDispatcher(), 100, Integer.MAX_VALUE, "op", null, members); final LatchedProcedure procspy = spy(proc); // coordinator: start the barrier procedure new Thread() { public void run() { procspy.call(); } }.start(); // coordinator: wait for the barrier to be acquired, then send start barrier proc.startedAcquireBarrier.await(); // we only know that {@link Procedure#sendStartBarrier()} was called, and others are blocked. verify(procspy).sendGlobalBarrierStart(); verify(procspy, never()).sendGlobalBarrierReached(); verify(procspy, never()).sendGlobalBarrierComplete(); verify(procspy, never()).barrierAcquiredByMember(anyString()); // member: trigger global barrier acquisition proc.barrierAcquiredByMember(members.get(0)); // coordinator: wait for global barrier to be acquired. proc.acquiredBarrierLatch.await(); verify(procspy).sendGlobalBarrierStart(); // old news // since two threads, we cannot guarantee that {@link Procedure#sendSatsifiedBarrier()} was // or was not called here. // member: trigger global barrier release proc.barrierReleasedByMember(members.get(0), new byte[0]); // coordinator: wait for procedure to be completed proc.completedProcedure.await(); verify(procspy).sendGlobalBarrierReached(); verify(procspy).sendGlobalBarrierComplete(); verify(procspy, never()).receive(any(ForeignException.class)); } @Test(timeout = 60000) public void testMultipleMember() throws Exception { // 2 members List<String> members = new ArrayList<String>(); members.add("member1"); members.add("member2"); LatchedProcedure proc = new LatchedProcedure(coord, new ForeignExceptionDispatcher(), 100, Integer.MAX_VALUE, "op", null, members); final LatchedProcedure procspy = spy(proc); // start the barrier procedure new Thread() { public void run() { procspy.call(); } }.start(); // coordinator: wait for the barrier to be acquired, then send start barrier procspy.startedAcquireBarrier.await(); // we only know that {@link Procedure#sendStartBarrier()} was called, and others are blocked. verify(procspy).sendGlobalBarrierStart(); verify(procspy, never()).sendGlobalBarrierReached(); verify(procspy, never()).sendGlobalBarrierComplete(); verify(procspy, never()).barrierAcquiredByMember(anyString()); // no externals // member0: [1/2] trigger global barrier acquisition. procspy.barrierAcquiredByMember(members.get(0)); // coordinator not satisified. verify(procspy).sendGlobalBarrierStart(); verify(procspy, never()).sendGlobalBarrierReached(); verify(procspy, never()).sendGlobalBarrierComplete(); // member 1: [2/2] trigger global barrier acquisition. procspy.barrierAcquiredByMember(members.get(1)); // coordinator: wait for global barrier to be acquired. procspy.startedDuringBarrier.await(); verify(procspy).sendGlobalBarrierStart(); // old news // member 1, 2: trigger global barrier release procspy.barrierReleasedByMember(members.get(0), new byte[0]); procspy.barrierReleasedByMember(members.get(1), new byte[0]); // coordinator wait for procedure to be completed procspy.completedProcedure.await(); verify(procspy).sendGlobalBarrierReached(); verify(procspy).sendGlobalBarrierComplete(); verify(procspy, never()).receive(any(ForeignException.class)); } @Test(timeout = 60000) public void testErrorPropagation() throws Exception { List<String> members = new ArrayList<String>(); members.add("member"); Procedure proc = new Procedure(coord, new ForeignExceptionDispatcher(), 100, Integer.MAX_VALUE, "op", null, members); final Procedure procspy = spy(proc); ForeignException cause = new ForeignException("SRC", "External Exception"); proc.receive(cause); // start the barrier procedure Thread t = new Thread() { public void run() { procspy.call(); } }; t.start(); t.join(); verify(procspy, never()).sendGlobalBarrierStart(); verify(procspy, never()).sendGlobalBarrierReached(); verify(procspy).sendGlobalBarrierComplete(); } @Test(timeout = 60000) public void testBarrieredErrorPropagation() throws Exception { List<String> members = new ArrayList<String>(); members.add("member"); LatchedProcedure proc = new LatchedProcedure(coord, new ForeignExceptionDispatcher(), 100, Integer.MAX_VALUE, "op", null, members); final LatchedProcedure procspy = spy(proc); // start the barrier procedure Thread t = new Thread() { public void run() { procspy.call(); } }; t.start(); // now test that we can put an error in before the commit phase runs procspy.startedAcquireBarrier.await(); ForeignException cause = new ForeignException("SRC", "External Exception"); procspy.receive(cause); procspy.barrierAcquiredByMember(members.get(0)); t.join(); // verify state of all the object verify(procspy).sendGlobalBarrierStart(); verify(procspy).sendGlobalBarrierComplete(); verify(procspy, never()).sendGlobalBarrierReached(); } }
intel-hadoop/hbase-rhino
hbase-server/src/test/java/org/apache/hadoop/hbase/procedure/TestProcedure.java
Java
apache-2.0
8,475
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2021 Fabian Prasser and contributors * * 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.deidentifier.arx; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.carrotsearch.hppc.IntArrayList; /** * This class represents a the dataset that is to be de-identified * as a subset of the given population table. * * @author Fabian Prasser * @author Florian Kohlmayer */ public class DataSubset implements Serializable { /** * Wrapper around a string array. * * @author Fabian Prasser * @author Florian Kohlmayer */ private static class Entry implements Serializable { /** SVUID */ private static final long serialVersionUID = 31695068160887476L; /** Record */ private String[] data; /** Hashcode */ private int hashcode; /** * * * @param data */ public Entry(String[] data){ this.data = data; this.hashcode = Arrays.hashCode(data); } @Override public boolean equals(Object obj) { if (obj == null) return false; Entry other = (Entry) obj; return Arrays.equals(data, other.data); } @Override public int hashCode() { return hashcode; } } /** SVUID */ private static final long serialVersionUID = 3945730896172205344L; /** * Create a subset by matching two data instances. * * @param data * @param subset * @return */ public static DataSubset create(Data data, Data subset){ // TODO: Implement more efficiently DataHandle bHandle = data.getHandle(); DataHandle sHandle = subset.getHandle(); // Add background data to map Map<Entry, List<Integer>> background = new HashMap<Entry, List<Integer>>(); for (int i=0; i<bHandle.getNumRows(); i++){ String[] tuple = new String[bHandle.getNumColumns()]; for (int j=0; j<tuple.length; j++){ tuple[j] = bHandle.getValue(i, j); } Entry entry = new Entry(tuple); if (!background.containsKey(entry)) { background.put(entry, new ArrayList<Integer>()); } background.get(entry).add(i); } // Init RowSet bitset = RowSet.create(data); int[] array = new int[sHandle.getNumRows()]; int idx = 0; // Match subset for (int i=0; i<sHandle.getNumRows(); i++){ String[] tuple = new String[sHandle.getNumColumns()]; for (int j=0; j<tuple.length; j++){ tuple[j] = sHandle.getValue(i, j); } List<Integer> indices = background.get(new Entry(tuple)); if (indices == null) { throw new IllegalArgumentException("No match found for: "+Arrays.toString(tuple)); } if (indices.isEmpty()) { throw new IllegalArgumentException("Too many matches found for: "+Arrays.toString(tuple)); } int index = indices.remove(0); bitset.add(index); array[idx++] = index; } // Return Arrays.sort(array); return new DataSubset(bitset, array); } /** * Creates a subset from the given selector. * * @param data * @param selector * @return */ public static DataSubset create(Data data, DataSelector selector){ // Init int rows = data.getHandle().getNumRows(); RowSet bitset = RowSet.create(data); ArrayList<Integer> list = new ArrayList<Integer>(); // Check for (int i=0; i<rows; i++){ if (selector.isSelected(i)) { bitset.add(i); list.add(i); } } // Convert int[] array = new int[list.size()]; for (int i=0; i<list.size(); i++){ array[i] = list.get(i); } // Return return new DataSubset(bitset, array); } /** * Creates a new subset from the given row set, from which a copy is created. * * @param data * @param subset * @return */ public static DataSubset create(Data data, RowSet subset) { return create(data.getHandle().getNumRows(), subset); } /** * Creates a new subset from the given set of tuple indices. * * @param data * @param subset * @return */ public static DataSubset create(Data data, Set<Integer> subset){ return create(data.getHandle().getNumRows(), subset); } /** * Creates a new subset from the given row set, from which a copy is created. * * @param data * @param subset * @return */ public static DataSubset create(int rows, RowSet subset) { RowSet bitset = RowSet.create(rows); int[] array = new int[subset.size()]; int idx = 0; for (int i=0; i<rows; i++){ if (subset.contains(i)) { bitset.add(i); array[idx++]=i; } } return new DataSubset(bitset, array); } /** * Creates a new subset from the given set of tuple indices. * * @param rows * @param subset * @return */ public static DataSubset create(int rows, Set<Integer> subset){ RowSet bitset = RowSet.create(rows); int[] array = new int[subset.size()]; int idx = 0; for (Integer line : subset) { if (line < 0 || line >= rows) { throw new IllegalArgumentException("Subset index out of range!"); } bitset.add(line); array[idx++] = line; } Arrays.sort(array); return new DataSubset(bitset, array); } /** The subset as a bitset. */ protected RowSet set; /** The subset as a sorted array of indices. */ protected int[] array; /** * Creates a new instance. * * @param bitSet * @param sortedIndices */ private DataSubset(RowSet bitSet, int[] sortedIndices) { this.set = bitSet; this.array = sortedIndices; } /** * Clone */ public DataSubset clone() { return new DataSubset(this.set.clone(), Arrays.copyOf(this.array, this.array.length)); } /** * Getter * * @return */ public int[] getArray() { return array; } /** * Getter * * @return */ public RowSet getSet() { return set; } /** * Returns the size of the data subset * @return */ public int getSize() { return array.length; } /** * Returns a new data subset, only containing those rows that are included in the subset * @param rowset * @return */ protected DataSubset getSubsetInstance(RowSet rowset) { int index = -1; RowSet newset = RowSet.create(rowset.size()); IntArrayList list = new IntArrayList(); for (int row = 0; row < this.set.length(); row++) { if (rowset.contains(row)) { index++; if (this.set.contains(row)) { newset.add(index); list.add(index); } } } return new DataSubset(newset, list.toArray()); } }
arx-deidentifier/arx
src/main/org/deidentifier/arx/DataSubset.java
Java
apache-2.0
8,595
package com.github.athi.athifx.injector.eventbus; import com.google.common.eventbus.Subscribe; /** * Created by Athi */ class EventBusSubscriptionListener { @Subscribe public void thirdSubscribe(EventBusEvent eventBusEvent) { System.out.println(eventBusEvent.getMessage()); } }
Athi/athifx
athi-fx-injector/src/test/java/com/github/athi/athifx/injector/eventbus/EventBusSubscriptionListener.java
Java
apache-2.0
303
/* * * 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.bookkeeper.meta; import java.util.Arrays; import java.util.Collection; import org.apache.bookkeeper.test.BookKeeperClusterTestCase; import org.apache.bookkeeper.util.SnapshotMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Test case to run over serveral ledger managers */ @RunWith(Parameterized.class) public abstract class LedgerManagerTestCase extends BookKeeperClusterTestCase { static final Logger LOG = LoggerFactory.getLogger(LedgerManagerTestCase.class); LedgerManagerFactory ledgerManagerFactory; LedgerManager ledgerManager = null; SnapshotMap<Long, Boolean> activeLedgers = null; public LedgerManagerTestCase(Class<? extends LedgerManagerFactory> lmFactoryCls) { super(0); activeLedgers = new SnapshotMap<Long, Boolean>(); baseConf.setLedgerManagerFactoryClass(lmFactoryCls); } public LedgerManager getLedgerManager() { if (null == ledgerManager) { ledgerManager = ledgerManagerFactory.newLedgerManager(); } return ledgerManager; } @Parameters public static Collection<Object[]> configs() { return Arrays.asList(new Object[][] { { FlatLedgerManagerFactory.class }, { HierarchicalLedgerManagerFactory.class }, { MSLedgerManagerFactory.class } }); } @Before @Override public void setUp() throws Exception { super.setUp(); ledgerManagerFactory = LedgerManagerFactory.newLedgerManagerFactory(baseConf, zkc); } @After @Override public void tearDown() throws Exception { if (null != ledgerManager) { ledgerManager.close(); } ledgerManagerFactory.uninitialize(); super.tearDown(); } }
mocc/bookkeeper-lab
bookkeeper-server/src/test/java/org/apache/bookkeeper/meta/LedgerManagerTestCase.java
Java
apache-2.0
2,777
/** */ package de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.impl; import de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.DimensionTypeEnum; import de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.DimensiontypesPackage; import de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.Element; import de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.Order; import de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.util.DimensiontypesValidator; import java.util.Collection; import java.util.Map; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.common.util.DiagnosticChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.util.EObjectValidator; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Dimension Type Enum</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.impl.DimensionTypeEnumImpl#getElements <em>Elements</em>}</li> * <li>{@link de.uka.ipd.sdq.dsexplore.qml.dimensiontypes.impl.DimensionTypeEnumImpl#getOrder <em>Order</em>}</li> * </ul> * * @generated */ public class DimensionTypeEnumImpl extends DimensionTypeImpl implements DimensionTypeEnum { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DimensionTypeEnumImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DimensiontypesPackage.Literals.DIMENSION_TYPE_ENUM; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") public EList<Element> getElements() { return (EList<Element>)eDynamicGet(DimensiontypesPackage.DIMENSION_TYPE_ENUM__ELEMENTS, DimensiontypesPackage.Literals.DIMENSION_TYPE_ENUM__ELEMENTS, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") public EList<Order> getOrder() { return (EList<Order>)eDynamicGet(DimensiontypesPackage.DIMENSION_TYPE_ENUM__ORDER, DimensiontypesPackage.Literals.DIMENSION_TYPE_ENUM__ORDER, true, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean ORDER_can_only_exist_with_RELATIONSEMANTICS_and_vice_versa(DiagnosticChain diagnostics, Map<Object, Object> context) { // TODO: implement this method // -> specify the condition that violates the invariant // -> verify the details of the diagnostic, including severity and message // Ensure that you remove @generated or mark it @generated NOT if (false) { if (diagnostics != null) { diagnostics.add (new BasicDiagnostic (Diagnostic.ERROR, DimensiontypesValidator.DIAGNOSTIC_SOURCE, DimensiontypesValidator.DIMENSION_TYPE_ENUM__ORDER_CAN_ONLY_EXIST_WITH_RELATIONSEMANTICS_AND_VICE_VERSA, EcorePlugin.INSTANCE.getString("_UI_GenericInvariant_diagnostic", new Object[] { "ORDER_can_only_exist_with_RELATIONSEMANTICS_and_vice_versa", EObjectValidator.getObjectLabel(this, context) }), new Object [] { this })); } return false; } return true; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ELEMENTS: return ((InternalEList<?>)getElements()).basicRemove(otherEnd, msgs); case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ORDER: return ((InternalEList<?>)getOrder()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ELEMENTS: return getElements(); case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ORDER: return getOrder(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ELEMENTS: getElements().clear(); getElements().addAll((Collection<? extends Element>)newValue); return; case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ORDER: getOrder().clear(); getOrder().addAll((Collection<? extends Order>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ELEMENTS: getElements().clear(); return; case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ORDER: getOrder().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ELEMENTS: return !getElements().isEmpty(); case DimensiontypesPackage.DIMENSION_TYPE_ENUM__ORDER: return !getOrder().isEmpty(); } return super.eIsSet(featureID); } } //DimensionTypeEnumImpl
KAMP-Research/KAMP
bundles/Toometa/de.uka.ipd.sdq.dsexplore.qml.dimensiontypes/src/de/uka/ipd/sdq/dsexplore/qml/dimensiontypes/impl/DimensionTypeEnumImpl.java
Java
apache-2.0
5,781
package org.jobjects.ihm.resource; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.application.Resource; import javax.faces.application.ResourceHandler; import javax.faces.application.ResourceHandlerWrapper; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import org.apache.commons.lang3.builder.ToStringBuilder; /* * http://roguexz.blogspot.fr/2013/10/jsf-2-returning-resource-url-that-is.html */ public class AppResourceHandler extends ResourceHandlerWrapper { public static final String WEBAPP_RESOURCES_DIRECTORY_PARAM_NAME= "javax.faces.WEBAPP_RESOURCES_DIRECTORY"; private Logger log = Logger.getLogger(getClass().getName()); private ResourceHandler wrapped; public AppResourceHandler(ResourceHandler wrapped) { //log.log(Level.INFO, "AppResourceHandler created."); this.wrapped = wrapped; } @Override public ResourceHandler getWrapped() { return wrapped; } @Override public Resource createResource(String resourceName, String libraryName) { log.log(Level.INFO, "AppResourceHandler#createResourc("+resourceName+","+libraryName+")" ); Resource resource = super.createResource(resourceName, libraryName); return getWrappedResource(resource); } /** * If the given resource object can be rendered locally, then do so by * returning a wrapped object, otherwise return the input as is. */ private Resource getWrappedResource(Resource resource) { log.log(Level.INFO, "AppResourceHandler#getWrappedResource created."+ToStringBuilder.reflectionToString(resource) ); WebAppResource webAppResource = null; ExternalContext context = FacesContext.getCurrentInstance() .getExternalContext(); // Get hold of the webapp resources directory name String resourcesRoot = null; if (resourcesRoot == null) { resourcesRoot = context.getInitParameter(WEBAPP_RESOURCES_DIRECTORY_PARAM_NAME); if (resourcesRoot == null) { resourcesRoot = "/resources"; } } if (resource != null) { URL baseURL = resource.getURL(); if (baseURL != null) { String extForm = baseURL.toExternalForm(); int idx = extForm.indexOf(resourcesRoot); if (idx != -1) { try { extForm = extForm.substring(idx); URL resourceURL = context.getResource(extForm); if (resourceURL != null) { webAppResource = new WebAppResource(extForm, resource); } } catch (MalformedURLException e) {} } } } return webAppResource != null ? webAppResource : resource; } }
mpatron/poc
poc-jsf-bootstrap/src/main/java/org/jobjects/ihm/resource/AppResourceHandler.java
Java
apache-2.0
3,054
/* * Copyright (c) 2016 Open Baton (http://www.openbaton.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.openbaton.catalogue.mano.descriptor; import java.util.Set; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import org.openbaton.catalogue.mano.common.AbstractVirtualLink; /** * Created by lto on 06/02/15. * * <p>Based on ETSI GS NFV-MAN 001 V1.1.1 (2014-12) */ @Entity public class InternalVirtualLink extends AbstractVirtualLink { /** * References to Connection Points (vnfd:vdu:vnfc:connection_point:id,vnfd:connection_point:id), * e.g. of type E-Line, E-Tree, or E-LAN. */ @ElementCollection(fetch = FetchType.EAGER) private Set<String> connection_points_references; public InternalVirtualLink() {} public Set<String> getConnection_points_references() { return connection_points_references; } public void setConnection_points_references(Set<String> connection_points_references) { this.connection_points_references = connection_points_references; } @Override public String toString() { return "InternalVirtualLink{" + "id='" + id + '\'' + ", name='" + getName() + '\'' + ", version='" + hb_version + ", connectivity_type='" + getConnectivity_type() + '\'' + ", connection_points_references='" + connection_points_references + '\'' + ", root_requirement='" + getRoot_requirement() + '\'' + ", leaf_requirement='" + getLeaf_requirement() + '\'' + ", qos='" + getQos() + '\'' + ", extId='" + extId + '\'' + ", test_access='" + getTest_access() + '\'' + '}'; } }
openbaton/openbaton-libs
catalogue/src/main/java/org/openbaton/catalogue/mano/descriptor/InternalVirtualLink.java
Java
apache-2.0
2,363
package dolphin.hotdexpatch; import android.util.Log; import java.io.File; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import dalvik.system.BaseDexClassLoader; /** * Created by hanyanan on 2015/11/11. */ public class DexHotPatchHelper { private static final String TAG = "DexHotPatchHelper"; public static class V19 { /** * 适用于4.4,5.0, 5.1,但是6.0未测 */ public synchronized static void install(ClassLoader loader, ArrayList<File> additionalClassPathEntries, File optimizedDirectory)throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException{ Field pathListField = findField(loader, "pathList"); Object dexPathList = pathListField.get(loader); ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>(); expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList, new ArrayList<File>(additionalClassPathEntries), optimizedDirectory, suppressedExceptions)); if (suppressedExceptions.size() > 0) { for (IOException e : suppressedExceptions) { Log.w(TAG, "Exception in makeDexElement", e); } Field suppressedExceptionsField = findField(loader, "dexElementsSuppressedExceptions"); IOException[] dexElementsSuppressedExceptions = (IOException[]) suppressedExceptionsField.get(loader); if (dexElementsSuppressedExceptions == null) { dexElementsSuppressedExceptions = suppressedExceptions.toArray( new IOException[suppressedExceptions.size()]); } else { IOException[] combined = new IOException[suppressedExceptions.size() + dexElementsSuppressedExceptions.length]; suppressedExceptions.toArray(combined); System.arraycopy(dexElementsSuppressedExceptions, 0, combined, suppressedExceptions.size(), dexElementsSuppressedExceptions.length); dexElementsSuppressedExceptions = combined; } suppressedExceptionsField.set(loader, dexElementsSuppressedExceptions); } } /** * A wrapper around * {@code private static final dalvik.system.DexPathList#makeDexElements}. */ private static Object[] makeDexElements( Object dexPathList, ArrayList<File> files, File optimizedDirectory, ArrayList<IOException> suppressedExceptions) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Method makeDexElements = findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class, ArrayList.class); return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory, suppressedExceptions); } } public static class V14 { /** * Installer for platform versions 14, 15, 16, 17 and 18. * 从4.0-4.3 */ public synchronized static void install(ClassLoader loader, ArrayList<File> additionalClassPathEntries, File optimizedDirectory) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException { /* The patched class loader is expected to be a descendant of * dalvik.system.BaseDexClassLoader. We modify its * dalvik.system.DexPathList pathList field to append additional DEX * file entries. */ Field pathListField = findField(loader, "pathList"); Object dexPathList = pathListField.get(loader); expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList, new ArrayList<File>(additionalClassPathEntries), optimizedDirectory)); } public static class V4 { // /** // * Installer for platform versions 4 to 13. // */ // private static void install(ClassLoader loader, List<File> additionalClassPathEntries) // throws IllegalArgumentException, IllegalAccessException, // NoSuchFieldException, IOException { // /* The patched class loader is expected to be a descendant of // * dalvik.system.DexClassLoader. We modify its // * fields mPaths, mFiles, mZips and mDexs to append additional DEX // * file entries. // */ // int extraSize = additionalClassPathEntries.size(); // Field pathField = findField(loader, "path"); // StringBuilder path = new StringBuilder((String) pathField.get(loader)); // String[] extraPaths = new String[extraSize]; // File[] extraFiles = new File[extraSize]; // ZipFile[] extraZips = new ZipFile[extraSize]; // DexFile[] extraDexs = new DexFile[extraSize]; // for (ListIterator<File> iterator = additionalClassPathEntries.listIterator(); // iterator.hasNext();) { // File additionalEntry = iterator.next(); // String entryPath = additionalEntry.getAbsolutePath(); // path.append(':').append(entryPath); // int index = iterator.previousIndex(); // extraPaths[index] = entryPath; // extraFiles[index] = additionalEntry; // extraZips[index] = new ZipFile(additionalEntry); // extraDexs[index] = DexFile.loadDex(entryPath, entryPath + ".dex", 0); // } // pathField.set(loader, path.toString()); // expandFieldArray(loader, "mPaths", extraPaths); // expandFieldArray(loader, "mFiles", extraFiles); // expandFieldArray(loader, "mZips", extraZips); // expandFieldArray(loader, "mDexs", extraDexs); // } // } /** * A wrapper around * {@code private static final dalvik.system.DexPathList#makeDexElements}. */ private static Object[] makeDexElements( Object dexPathList, ArrayList<File> files, File optimizedDirectory) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Method makeDexElements = findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class); return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory); } } /** * Replace the value of a field containing a non null array, by a new array containing the * elements of the original array plus the elements of extraElements. * * @param instance the instance whose field is to be modified. * @param fieldName the field to modify. * @param extraElements elements to append at the end of the array. */ private static void expandFieldArray(Object instance, String fieldName, Object[] extraElements) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field jlrField = findField(instance, fieldName); Object[] original = (Object[]) jlrField.get(instance); Object[] combined = (Object[]) Array.newInstance(original.getClass().getComponentType(), original.length + extraElements.length); System.arraycopy(extraElements, 0, combined, 0, extraElements.length); System.arraycopy(original, 0, combined, extraElements.length, original.length); jlrField.set(instance, combined); } /** * Locates a given field anywhere in the class inheritance hierarchy. * * @param instance an object to search the field into. * @param name field name * @return a field object * @throws NoSuchFieldException if the field cannot be located */ private static Field findField(Object instance, String name) throws NoSuchFieldException { for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) { try { Field field = clazz.getDeclaredField(name); if (!field.isAccessible()) { field.setAccessible(true); } return field; } catch (NoSuchFieldException e) { // ignore and search next } } throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass()); } /** * Locates a given method anywhere in the class inheritance hierarchy. * * @param instance an object to search the method into. * @param name method name * @param parameterTypes method parameter types * @return a method object * @throws NoSuchMethodException if the method cannot be located */ private static Method findMethod(Object instance, String name, Class<?>... parameterTypes) throws NoSuchMethodException { for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) { try { Method method = clazz.getDeclaredMethod(name, parameterTypes); if (!method.isAccessible()) { method.setAccessible(true); } return method; } catch (NoSuchMethodException e) { // ignore and search next } } throw new NoSuchMethodException("Method " + name + " with parameters " + Arrays.asList(parameterTypes) + " not found in " + instance.getClass()); } }
onesubone/hotpatch
app/src/main/java/dolphin/hotdexpatch/DexHotPatchHelper.java
Java
apache-2.0
10,799
package org.cavebeetle.maven.plugins; import javax.xml.stream.Location; public final class Type implements HasLocation { public static final Type DEFAULT = new Type("jar"); private final Location location; private final String type; public Type( final String type) { location = null; this.type = type; } public Type( final Location location, final String type) { this.location = location; this.type = type; } @Override public Location getLocation() { return location; } @Override public String toString() { return type; } }
Hilco-Wijbenga/smarter-maven
maven-pom-plugin/src/main/java/org/cavebeetle/maven/plugins/Type.java
Java
apache-2.0
702
package ${package}.login; import java.util.Set; public class AuthorityResponse { public boolean isLogin() { return isLogin; } public void setLogin(boolean isLogin) { this.isLogin = isLogin; } public Set<String> getRoles() { return roles; } public void setRoles(Set<String> roles) { this.roles = roles; } public String getUsrname() { return usrname; } public void setUsrname(String usrname) { this.usrname = usrname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private String email; private String usrname; private boolean isLogin; private Set<String> roles; }
kerongbaby/risetek.archetypes
empty-frame-shiro/src/main/resources/archetype-resources/server/src/main/java/login/AuthorityResponse.java
Java
apache-2.0
698
/*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. This source code is licensed under the Apache License Version 2.0.*/ package apijson; /**请求方法,对应org.springframework.web.bind.annotation.RequestMethod,多出GETS,HEADS方法 * @author Lemon */ public enum RequestMethod { /** * 常规获取数据方式 */ GET, /** * 检查,默认是非空检查,返回数据总数 */ HEAD, /**Safe, Single, Simple * <br > 限制性GET,通过POST来GET数据,不显示请求内容和返回结果,并且校验请求,一般用于对安全要求比较高的请求 */ GETS, /**Safe, Single, Simple * <br > 限制性HEAD,通过POST来HEAD数据,不显示请求内容和返回结果,并且校验请求,一般用于对安全要求比较高的请求 */ HEADS, /** * 新增(或者说插入)数据 */ POST, /** * 修改数据,只修改传入字段对应的值 */ PUT, /** * 删除数据 */ DELETE; /**是否为GET请求方法 * @param method * @param containPrivate 包含私密(非明文)获取方法GETS * @return */ public static boolean isGetMethod(RequestMethod method, boolean containPrivate) { boolean is = method == null || method == GET; return containPrivate == false ? is : is || method == GETS; } /**是否为HEAD请求方法 * @param method * @param containPrivate 包含私密(非明文)获取方法HEADS * @return */ public static boolean isHeadMethod(RequestMethod method, boolean containPrivate) { boolean is = method == HEAD; return containPrivate == false ? is : is || method == HEADS; } /**是否为查询的请求方法 * @param method * @return 读操作(GET型或HEAD型) - true, 写操作(POST,PUT,DELETE) - false */ public static boolean isQueryMethod(RequestMethod method) { return isGetMethod(method, true) || isHeadMethod(method, true); } /**是否为开放(不限制请求的结构或内容;明文,浏览器能直接访问及查看)的请求方法 * @param method * @return */ public static boolean isPublicMethod(RequestMethod method) { return method == null || method == GET || method == HEAD; } public static String getName(RequestMethod method) { return method == null ? GET.name() : method.name(); } }
TommyLemon/APIJSON
APIJSONORM/src/main/java/apijson/RequestMethod.java
Java
apache-2.0
2,308
/* Copyright 2020 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 com.coreos.monitoring.models; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * RuleGroup is a list of sequentially evaluated recording and alerting rules. Note: * PartialResponseStrategy is only used by ThanosRuler and will be ignored by Prometheus instances. * Valid values for this field are &#39;warn&#39; or &#39;abort&#39;. More info: * https://github.com/thanos-io/thanos/blob/master/docs/components/rule.md#partial-response */ @ApiModel( description = "RuleGroup is a list of sequentially evaluated recording and alerting rules. Note: PartialResponseStrategy is only used by ThanosRuler and will be ignored by Prometheus instances. Valid values for this field are 'warn' or 'abort'. More info: https://github.com/thanos-io/thanos/blob/master/docs/components/rule.md#partial-response") @javax.annotation.Generated( value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-08-31T19:41:55.826Z[Etc/UTC]") public class V1PrometheusRuleSpecGroups { public static final String SERIALIZED_NAME_INTERVAL = "interval"; @SerializedName(SERIALIZED_NAME_INTERVAL) private String interval; public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) private String name; public static final String SERIALIZED_NAME_PARTIAL_RESPONSE_STRATEGY = "partial_response_strategy"; @SerializedName(SERIALIZED_NAME_PARTIAL_RESPONSE_STRATEGY) private String partialResponseStrategy; public static final String SERIALIZED_NAME_RULES = "rules"; @SerializedName(SERIALIZED_NAME_RULES) private List<V1PrometheusRuleSpecRules> rules = new ArrayList<V1PrometheusRuleSpecRules>(); public V1PrometheusRuleSpecGroups interval(String interval) { this.interval = interval; return this; } /** * Get interval * * @return interval */ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getInterval() { return interval; } public void setInterval(String interval) { this.interval = interval; } public V1PrometheusRuleSpecGroups name(String name) { this.name = name; return this; } /** * Get name * * @return name */ @ApiModelProperty(required = true, value = "") public String getName() { return name; } public void setName(String name) { this.name = name; } public V1PrometheusRuleSpecGroups partialResponseStrategy(String partialResponseStrategy) { this.partialResponseStrategy = partialResponseStrategy; return this; } /** * Get partialResponseStrategy * * @return partialResponseStrategy */ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getPartialResponseStrategy() { return partialResponseStrategy; } public void setPartialResponseStrategy(String partialResponseStrategy) { this.partialResponseStrategy = partialResponseStrategy; } public V1PrometheusRuleSpecGroups rules(List<V1PrometheusRuleSpecRules> rules) { this.rules = rules; return this; } public V1PrometheusRuleSpecGroups addRulesItem(V1PrometheusRuleSpecRules rulesItem) { this.rules.add(rulesItem); return this; } /** * Get rules * * @return rules */ @ApiModelProperty(required = true, value = "") public List<V1PrometheusRuleSpecRules> getRules() { return rules; } public void setRules(List<V1PrometheusRuleSpecRules> rules) { this.rules = rules; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1PrometheusRuleSpecGroups v1PrometheusRuleSpecGroups = (V1PrometheusRuleSpecGroups) o; return Objects.equals(this.interval, v1PrometheusRuleSpecGroups.interval) && Objects.equals(this.name, v1PrometheusRuleSpecGroups.name) && Objects.equals( this.partialResponseStrategy, v1PrometheusRuleSpecGroups.partialResponseStrategy) && Objects.equals(this.rules, v1PrometheusRuleSpecGroups.rules); } @Override public int hashCode() { return Objects.hash(interval, name, partialResponseStrategy, rules); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1PrometheusRuleSpecGroups {\n"); sb.append(" interval: ").append(toIndentedString(interval)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" partialResponseStrategy: ") .append(toIndentedString(partialResponseStrategy)) .append("\n"); sb.append(" rules: ").append(toIndentedString(rules)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
kubernetes-client/java
client-java-contrib/prometheus-operator/src/main/java/com/coreos/monitoring/models/V1PrometheusRuleSpecGroups.java
Java
apache-2.0
5,759
/* * 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.directory.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * The result of a CreateTrust request. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/CreateTrust" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateTrustResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A unique identifier for the trust relationship that was created. * </p> */ private String trustId; /** * <p> * A unique identifier for the trust relationship that was created. * </p> * * @param trustId * A unique identifier for the trust relationship that was created. */ public void setTrustId(String trustId) { this.trustId = trustId; } /** * <p> * A unique identifier for the trust relationship that was created. * </p> * * @return A unique identifier for the trust relationship that was created. */ public String getTrustId() { return this.trustId; } /** * <p> * A unique identifier for the trust relationship that was created. * </p> * * @param trustId * A unique identifier for the trust relationship that was created. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateTrustResult withTrustId(String trustId) { setTrustId(trustId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getTrustId() != null) sb.append("TrustId: ").append(getTrustId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateTrustResult == false) return false; CreateTrustResult other = (CreateTrustResult) obj; if (other.getTrustId() == null ^ this.getTrustId() == null) return false; if (other.getTrustId() != null && other.getTrustId().equals(this.getTrustId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getTrustId() == null) ? 0 : getTrustId().hashCode()); return hashCode; } @Override public CreateTrustResult clone() { try { return (CreateTrustResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/CreateTrustResult.java
Java
apache-2.0
3,909
package playground; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @Constraint(validatedBy = { }) public @interface MyConstraint { String message() default "{javax.validation.constraints.NotNull.message}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; int[] int2() default {}; }
actframework/actframework
src/test/java/playground/MyConstraint.java
Java
apache-2.0
1,337
/* * 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.directconnect.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum BGPStatus { Up("up"), Down("down"), Unknown("unknown"); private String value; private BGPStatus(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return BGPStatus corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static BGPStatus fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (BGPStatus enumEntry : BGPStatus.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
jentfoo/aws-sdk-java
aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/BGPStatus.java
Java
apache-2.0
1,761
/* * Copyright 2011-2012 Maxim Dominichenko * * 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.dominichenko.pet.gwt.phys2d.client.math; import com.dominichenko.pet.gwt.phys2d.client.utils.VectorTools; import gwt.g2d.client.math.Vector2; /** * Simple class that just implements {@link Object#toString()} method for {@link Vector2} class.<br/> * This class will be deprecated as soon as issue with absent {@code toString()} method * in native {@link Vector2} class will be fixed. * * @author <a href="mailto:[email protected]">Maxim Dominichenko</a> */ public class PrintableVector2 extends Vector2 { private static final long serialVersionUID = -8796108587875755409L; public PrintableVector2() { super(); } public PrintableVector2(double x, double y) { super(x, y); } public PrintableVector2(double value) { super(value); } public PrintableVector2(Vector2 vector) { super(vector); } /** * Adopts given vector into printable implementation.<br/> * <em>Caution</em>: You have to use explicit vector creation if you want * to have guaranteed new instance of {@link PrintableVector2}. * * @param vector An instance of {@link Vector2} that should be adopted. * @return new instance of {@link PrintableVector2} if given vector isn't instance of it. * The same instance of given vector if it is {@link PrintableVector2}. * {@code null} if given vector is {@code null}. */ public static PrintableVector2 valueOf(Vector2 vector) { return vector == null ? null : vector instanceof PrintableVector2 ? (PrintableVector2) vector : new PrintableVector2(vector); } @Override public String toString() { return VectorTools.printVector(this); } }
domax/gwt-phys2d
Phys2D/src/com/dominichenko/pet/gwt/phys2d/client/math/PrintableVector2.java
Java
apache-2.0
2,244
package dvdrental; // Generated Feb 4, 2017 8:25:50 PM by Hibernate Tools 4.3.1 import java.util.Date; /** * FilmCategory generated by hbm2java */ public class FilmCategory implements java.io.Serializable { private FilmCategoryId id; private Category category; private Film film; private Date lastUpdate; public FilmCategory() { } public FilmCategory(FilmCategoryId id, Category category, Film film, Date lastUpdate) { this.id = id; this.category = category; this.film = film; this.lastUpdate = lastUpdate; } public FilmCategoryId getId() { return this.id; } public void setId(FilmCategoryId id) { this.id = id; } public Category getCategory() { return this.category; } public void setCategory(Category category) { this.category = category; } public Film getFilm() { return this.film; } public void setFilm(Film film) { this.film = film; } public Date getLastUpdate() { return this.lastUpdate; } public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } }
geekdos/Personal_Labs
NetBeansProjects/DVDStore/src/java/dvdrental/FilmCategory.java
Java
apache-2.0
1,207
/* * 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.facebook.presto.orc; import com.facebook.hive.orc.OrcConf; import com.facebook.hive.orc.lazy.OrcLazyObject; import com.facebook.presto.common.Page; import com.facebook.presto.common.Subfield; import com.facebook.presto.common.block.Block; import com.facebook.presto.common.block.BlockBuilder; import com.facebook.presto.common.type.ArrayType; import com.facebook.presto.common.type.CharType; import com.facebook.presto.common.type.DecimalType; import com.facebook.presto.common.type.Decimals; import com.facebook.presto.common.type.MapType; import com.facebook.presto.common.type.NamedTypeSignature; import com.facebook.presto.common.type.RowFieldName; import com.facebook.presto.common.type.RowType; import com.facebook.presto.common.type.SqlDate; import com.facebook.presto.common.type.SqlDecimal; import com.facebook.presto.common.type.SqlTimestamp; import com.facebook.presto.common.type.SqlVarbinary; import com.facebook.presto.common.type.StandardTypes; import com.facebook.presto.common.type.Type; import com.facebook.presto.common.type.TypeSignatureParameter; import com.facebook.presto.common.type.VarbinaryType; import com.facebook.presto.common.type.VarcharType; import com.facebook.presto.metadata.FunctionAndTypeManager; import com.facebook.presto.orc.TrackingTupleDomainFilter.TestBigintRange; import com.facebook.presto.orc.TrackingTupleDomainFilter.TestDoubleRange; import com.facebook.presto.orc.TupleDomainFilter.BigintRange; import com.facebook.presto.orc.TupleDomainFilter.DoubleRange; import com.facebook.presto.orc.cache.OrcFileTailSource; import com.facebook.presto.orc.cache.StorageOrcFileTailSource; import com.facebook.presto.orc.metadata.CompressionKind; import com.google.common.base.Functions; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import io.airlift.units.DataSize; import io.airlift.units.DataSize.Unit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter; import org.apache.hadoop.hive.ql.io.orc.OrcFile; import org.apache.hadoop.hive.ql.io.orc.OrcFile.ReaderOptions; import org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat; import org.apache.hadoop.hive.ql.io.orc.OrcSerde; import org.apache.hadoop.hive.ql.io.orc.OrcStruct; import org.apache.hadoop.hive.ql.io.orc.OrcUtil; import org.apache.hadoop.hive.ql.io.orc.Reader; import org.apache.hadoop.hive.serde2.Serializer; import org.apache.hadoop.hive.serde2.io.DateWritable; import org.apache.hadoop.hive.serde2.io.HiveCharWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.serde2.io.ShortWritable; import org.apache.hadoop.hive.serde2.io.TimestampWritable; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructField; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.JavaHiveCharObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.io.BooleanWritable; import org.apache.hadoop.io.ByteWritable; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapred.JobConf; import org.joda.time.DateTimeZone; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Date; import java.sql.Timestamp; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.BooleanType.BOOLEAN; import static com.facebook.presto.common.type.Chars.truncateToLengthAndTrimSpaces; import static com.facebook.presto.common.type.DateType.DATE; import static com.facebook.presto.common.type.Decimals.rescale; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.common.type.IntegerType.INTEGER; import static com.facebook.presto.common.type.RealType.REAL; import static com.facebook.presto.common.type.SmallintType.SMALLINT; import static com.facebook.presto.common.type.TimestampType.TIMESTAMP; import static com.facebook.presto.common.type.TinyintType.TINYINT; import static com.facebook.presto.common.type.VarbinaryType.VARBINARY; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.facebook.presto.common.type.Varchars.truncateToLength; import static com.facebook.presto.metadata.FunctionAndTypeManager.createTestFunctionAndTypeManager; import static com.facebook.presto.orc.NoopOrcAggregatedMemoryContext.NOOP_ORC_AGGREGATED_MEMORY_CONTEXT; import static com.facebook.presto.orc.OrcReader.MAX_BATCH_SIZE; import static com.facebook.presto.orc.OrcTester.Format.DWRF; import static com.facebook.presto.orc.OrcTester.Format.ORC_11; import static com.facebook.presto.orc.OrcTester.Format.ORC_12; import static com.facebook.presto.orc.OrcWriteValidation.OrcWriteValidationMode.BOTH; import static com.facebook.presto.orc.TestingOrcPredicate.createOrcPredicate; import static com.facebook.presto.orc.TupleDomainFilter.IS_NOT_NULL; import static com.facebook.presto.orc.TupleDomainFilter.IS_NULL; import static com.facebook.presto.orc.metadata.CompressionKind.LZ4; import static com.facebook.presto.orc.metadata.CompressionKind.NONE; import static com.facebook.presto.orc.metadata.CompressionKind.SNAPPY; import static com.facebook.presto.orc.metadata.CompressionKind.ZLIB; import static com.facebook.presto.orc.metadata.CompressionKind.ZSTD; import static com.facebook.presto.orc.metadata.KeyProvider.UNKNOWN; import static com.facebook.presto.testing.DateTimeTestingUtils.sqlTimestampOf; import static com.facebook.presto.testing.TestingConnectorSession.SESSION; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Lists.newArrayList; import static io.airlift.slice.Slices.utf8Slice; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static io.airlift.units.DataSize.succinctBytes; import static java.lang.Math.toIntExact; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toList; import static org.apache.hadoop.hive.serde2.ColumnProjectionUtils.READ_ALL_COLUMNS; import static org.apache.hadoop.hive.serde2.ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR; import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardListObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardMapObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardStructObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaBooleanObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteArrayObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaByteObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDateObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDoubleObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaFloatObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaIntObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaLongObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaShortObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaStringObjectInspector; import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaTimestampObjectInspector; import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getCharTypeInfo; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class OrcTester { public static final DataSize MAX_BLOCK_SIZE = new DataSize(1, Unit.MEGABYTE); public static final DateTimeZone HIVE_STORAGE_TIME_ZONE = DateTimeZone.forID("America/Bahia_Banderas"); private static final boolean LEGACY_MAP_SUBSCRIPT = true; private static final FunctionAndTypeManager FUNCTION_AND_TYPE_MANAGER = createTestFunctionAndTypeManager(); private static final List<Integer> PRIME_NUMBERS = ImmutableList.of(5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97); public enum Format { ORC_12(OrcEncoding.ORC) { @Override @SuppressWarnings("deprecation") public Serializer createSerializer() { return new OrcSerde(); } }, ORC_11(OrcEncoding.ORC) { @Override @SuppressWarnings("deprecation") public Serializer createSerializer() { return new OrcSerde(); } }, DWRF(OrcEncoding.DWRF) { @Override public boolean supportsType(Type type) { return !hasType(type, ImmutableSet.of(StandardTypes.DATE, StandardTypes.DECIMAL, StandardTypes.CHAR)); } @Override @SuppressWarnings("deprecation") public Serializer createSerializer() { return new com.facebook.hive.orc.OrcSerde(); } }; private final OrcEncoding orcEncoding; Format(OrcEncoding orcEncoding) { this.orcEncoding = requireNonNull(orcEncoding, "orcEncoding is null"); } public OrcEncoding getOrcEncoding() { return orcEncoding; } public boolean supportsType(Type type) { return true; } @SuppressWarnings("deprecation") public abstract Serializer createSerializer(); } private boolean structTestsEnabled; private boolean mapTestsEnabled; private boolean listTestsEnabled; private boolean complexStructuralTestsEnabled; private boolean structuralNullTestsEnabled; private boolean reverseTestsEnabled; private boolean nullTestsEnabled; private boolean missingStructFieldsTestsEnabled; private boolean skipBatchTestsEnabled; private boolean skipStripeTestsEnabled; private boolean dwrfEncryptionEnabled; private Set<Format> formats = ImmutableSet.of(); private Set<CompressionKind> compressions = ImmutableSet.of(); private boolean useSelectiveOrcReader; public static OrcTester quickOrcTester() { OrcTester orcTester = new OrcTester(); orcTester.structTestsEnabled = true; orcTester.mapTestsEnabled = true; orcTester.listTestsEnabled = true; orcTester.nullTestsEnabled = true; orcTester.missingStructFieldsTestsEnabled = true; orcTester.skipBatchTestsEnabled = true; orcTester.formats = ImmutableSet.of(ORC_12, ORC_11, DWRF); orcTester.compressions = ImmutableSet.of(ZLIB); orcTester.dwrfEncryptionEnabled = true; return orcTester; } public static OrcTester fullOrcTester() { OrcTester orcTester = new OrcTester(); orcTester.structTestsEnabled = true; orcTester.mapTestsEnabled = true; orcTester.listTestsEnabled = true; orcTester.complexStructuralTestsEnabled = true; orcTester.structuralNullTestsEnabled = true; orcTester.reverseTestsEnabled = true; orcTester.nullTestsEnabled = true; orcTester.missingStructFieldsTestsEnabled = true; orcTester.skipBatchTestsEnabled = true; orcTester.skipStripeTestsEnabled = true; orcTester.formats = ImmutableSet.copyOf(Format.values()); orcTester.compressions = ImmutableSet.of(NONE, SNAPPY, ZLIB, LZ4, ZSTD); orcTester.dwrfEncryptionEnabled = true; return orcTester; } public static OrcTester quickSelectiveOrcTester() { OrcTester orcTester = new OrcTester(); orcTester.listTestsEnabled = true; orcTester.structTestsEnabled = true; orcTester.nullTestsEnabled = true; orcTester.skipBatchTestsEnabled = true; orcTester.formats = ImmutableSet.of(ORC_12, ORC_11, DWRF); orcTester.compressions = ImmutableSet.of(ZLIB, ZSTD); orcTester.useSelectiveOrcReader = true; return orcTester; } public void testRoundTrip(Type type, List<?> readValues) throws Exception { testRoundTrip(type, readValues, ImmutableList.of()); } public void testRoundTrip(Type type, List<?> readValues, TupleDomainFilter... filters) throws Exception { testRoundTrip(type, readValues, Arrays.stream(filters).map(filter -> ImmutableMap.of(new Subfield("c"), filter)).collect(toImmutableList())); } public void testRoundTrip(Type type, List<?> readValues, List<Map<Subfield, TupleDomainFilter>> filters) throws Exception { List<Map<Integer, Map<Subfield, TupleDomainFilter>>> columnFilters = filters.stream().map(filter -> ImmutableMap.of(0, filter)).collect(toImmutableList()); // just the values testRoundTripTypes(ImmutableList.of(type), ImmutableList.of(readValues), columnFilters); // all nulls if (nullTestsEnabled) { assertRoundTrip( type, readValues.stream() .map(value -> null) .collect(toList()), columnFilters); } // values wrapped in struct if (structTestsEnabled) { testStructRoundTrip(type, readValues); } // values wrapped in a struct wrapped in a struct if (complexStructuralTestsEnabled) { testStructRoundTrip( rowType(type, type, type), readValues.stream() .map(OrcTester::toHiveStruct) .collect(toList())); } // values wrapped in map if (mapTestsEnabled && type.isComparable()) { testMapRoundTrip(type, readValues); } // values wrapped in list if (listTestsEnabled) { testListRoundTrip(type, readValues); } // values wrapped in a list wrapped in a list if (complexStructuralTestsEnabled) { testListRoundTrip( arrayType(type), readValues.stream() .map(OrcTester::toHiveList) .collect(toList())); } } private void testStructRoundTrip(Type type, List<?> values) throws Exception { Type rowType = rowType(type, type, type); // values in simple struct testRoundTripType( rowType, values.stream() .map(OrcTester::toHiveStruct) .collect(toList())); if (structuralNullTestsEnabled) { // values and nulls in simple struct testRoundTripType( rowType, insertNullEvery(5, values).stream() .map(OrcTester::toHiveStruct) .collect(toList())); // all null values in simple struct testRoundTripType( rowType, values.stream() .map(value -> toHiveStruct(null)) .collect(toList())); } if (missingStructFieldsTestsEnabled) { Type readType = rowType(type, type, type, type, type, type); Type writeType = rowType(type, type, type); List writeValues = values.stream() .map(OrcTester::toHiveStruct) .collect(toList()); List readValues = values.stream() .map(OrcTester::toHiveStructWithNull) .collect(toList()); assertRoundTrip(writeType, readType, writeValues, readValues, true, ImmutableList.of()); } } private void testMapRoundTrip(Type type, List<?> readValues) throws Exception { Type mapType = mapType(type, type); // maps can not have a null key, so select a value to use for the map key when the value is null Object readNullKeyValue = Iterables.getLast(readValues); // values in simple map testRoundTripType( mapType, readValues.stream() .map(value -> toHiveMap(value, readNullKeyValue)) .collect(toList())); if (structuralNullTestsEnabled) { // values and nulls in simple map testRoundTripType( mapType, insertNullEvery(5, readValues).stream() .map(value -> toHiveMap(value, readNullKeyValue)) .collect(toList())); // all null values in simple map testRoundTripType( mapType, readValues.stream() .map(value -> toHiveMap(null, readNullKeyValue)) .collect(toList())); } } private void testListRoundTrip(Type type, List<?> readValues) throws Exception { Type arrayType = arrayType(type); // values in simple list testRoundTripType( arrayType, readValues.stream() .map(OrcTester::toHiveList) .collect(toList())); if (structuralNullTestsEnabled) { // values and nulls in simple list testRoundTripType( arrayType, insertNullEvery(5, readValues).stream() .map(OrcTester::toHiveList) .collect(toList())); // all null values in simple list testRoundTripType( arrayType, readValues.stream() .map(value -> toHiveList(null)) .collect(toList())); } } private void testRoundTripType(Type type, List<?> readValues) throws Exception { testRoundTripTypes(ImmutableList.of(type), ImmutableList.of(readValues), ImmutableList.of()); } public void testRoundTripTypes(List<Type> types, List<List<?>> readValues, List<Map<Integer, Map<Subfield, TupleDomainFilter>>> filters) throws Exception { testRoundTripTypes(types, readValues, filters, ImmutableList.of()); } public void testRoundTripTypes(List<Type> types, List<List<?>> readValues, List<Map<Integer, Map<Subfield, TupleDomainFilter>>> filters, List<List<Integer>> expectedFilterOrder) throws Exception { assertEquals(types.size(), readValues.size()); if (!expectedFilterOrder.isEmpty()) { assertEquals(filters.size(), expectedFilterOrder.size()); } // forward order assertRoundTrip(types, readValues, filters, expectedFilterOrder); // reverse order if (reverseTestsEnabled) { assertRoundTrip(types, Lists.transform(readValues, OrcTester::reverse), filters, expectedFilterOrder); } if (nullTestsEnabled) { // forward order with nulls assertRoundTrip(types, insertNulls(types, readValues), filters, expectedFilterOrder); // reverse order with nulls if (reverseTestsEnabled) { assertRoundTrip(types, insertNulls(types, Lists.transform(readValues, OrcTester::reverse)), filters, expectedFilterOrder); } } } public void testRoundTripTypesWithOrder(List<Type> types, List<List<?>> readValues, List<Map<Integer, Map<Subfield, TupleDomainFilter>>> filters, List<List<Integer>> expectedFilterOrder) throws Exception { assertNotNull(expectedFilterOrder); assertEquals(filters.size(), expectedFilterOrder.size()); // Forward order testRoundTripTypes(types, readValues, filters, expectedFilterOrder); // Reverse order int columnCount = types.size(); List<Map<Integer, Map<Subfield, TupleDomainFilter>>> reverseFilters = filters.stream() .map(filtersEntry -> filtersEntry.entrySet().stream().collect(toImmutableMap(entry -> columnCount - 1 - entry.getKey(), Entry::getValue))) .collect(toImmutableList()); List<List<Integer>> reverseFilterOrder = expectedFilterOrder.stream() .map(columns -> columns.stream().map(column -> columnCount - 1 - column).collect(toImmutableList())) .collect(toImmutableList()); testRoundTripTypes(Lists.reverse(types), Lists.reverse(readValues), reverseFilters, reverseFilterOrder); } private List<List<?>> insertNulls(List<Type> types, List<List<?>> values) { assertTrue(types.size() <= PRIME_NUMBERS.size()); return IntStream.range(0, types.size()) .mapToObj(i -> insertNullEvery(PRIME_NUMBERS.get(i), values.get(i))) .collect(toList()); } public void assertRoundTrip(Type type, List<?> readValues) throws Exception { assertRoundTrip(type, type, readValues, readValues, true, ImmutableList.of()); } public void assertRoundTripWithSettings(Type type, List<?> readValues, List<OrcReaderSettings> settings) throws Exception { assertRoundTrip(type, type, readValues, readValues, true, settings); } public void assertRoundTrip(Type type, List<?> readValues, List<Map<Integer, Map<Subfield, TupleDomainFilter>>> filters) throws Exception { List<OrcReaderSettings> settings = filters.stream() .map(entry -> OrcReaderSettings.builder().setColumnFilters(entry).build()) .collect(toImmutableList()); assertRoundTrip(type, type, readValues, readValues, true, settings); } public void assertRoundTrip(Type type, List<?> readValues, boolean verifyWithHiveReader) throws Exception { assertRoundTrip(type, type, readValues, readValues, verifyWithHiveReader, ImmutableList.of()); } public void assertRoundTrip(List<Type> types, List<List<?>> readValues, List<Map<Integer, Map<Subfield, TupleDomainFilter>>> filters, List<List<Integer>> expectedFilterOrder) throws Exception { List<OrcReaderSettings> settings = IntStream.range(0, filters.size()) .mapToObj(i -> OrcReaderSettings.builder() .setColumnFilters(filters.get(i)) .setExpectedFilterOrder(expectedFilterOrder.isEmpty() ? ImmutableList.of() : expectedFilterOrder.get(i)) .build()) .collect(toImmutableList()); assertRoundTrip(types, types, readValues, readValues, true, settings); } private void assertRoundTrip(Type writeType, Type readType, List<?> writeValues, List<?> readValues, boolean verifyWithHiveReader, List<OrcReaderSettings> settings) throws Exception { assertRoundTrip(ImmutableList.of(writeType), ImmutableList.of(readType), ImmutableList.of(writeValues), ImmutableList.of(readValues), verifyWithHiveReader, settings); } private void assertRoundTrip(List<Type> writeTypes, List<Type> readTypes, List<List<?>> writeValues, List<List<?>> readValues, boolean verifyWithHiveReader, List<OrcReaderSettings> settings) throws Exception { assertEquals(writeTypes.size(), readTypes.size()); assertEquals(writeTypes.size(), writeValues.size()); assertEquals(writeTypes.size(), readValues.size()); OrcWriterStats stats = new OrcWriterStats(); for (Format format : formats) { if (!readTypes.stream().allMatch(readType -> format.supportsType(readType))) { return; } OrcEncoding orcEncoding = format.getOrcEncoding(); for (CompressionKind compression : compressions) { boolean hiveSupported = (compression != LZ4) && (compression != ZSTD); // write Hive, read Presto if (hiveSupported) { try (TempFile tempFile = new TempFile()) { writeOrcColumnsHive(tempFile.getFile(), format, compression, writeTypes, writeValues); assertFileContentsPresto(readTypes, tempFile, readValues, false, false, orcEncoding, format, true, useSelectiveOrcReader, settings, ImmutableMap.of()); } } // write Presto, read Hive and Presto try (TempFile tempFile = new TempFile()) { writeOrcColumnsPresto(tempFile.getFile(), format, compression, Optional.empty(), writeTypes, writeValues, stats); if (verifyWithHiveReader && hiveSupported) { assertFileContentsHive(readTypes, tempFile, format, readValues); } assertFileContentsPresto(readTypes, tempFile, readValues, false, false, orcEncoding, format, false, useSelectiveOrcReader, settings, ImmutableMap.of()); if (skipBatchTestsEnabled) { assertFileContentsPresto(readTypes, tempFile, readValues, true, false, orcEncoding, format, false, useSelectiveOrcReader, settings, ImmutableMap.of()); } if (skipStripeTestsEnabled) { assertFileContentsPresto(readTypes, tempFile, readValues, false, true, orcEncoding, format, false, useSelectiveOrcReader, settings, ImmutableMap.of()); } } // write presto read presto if (dwrfEncryptionEnabled && format == DWRF) { try (TempFile tempFile = new TempFile()) { DwrfWriterEncryption dwrfWriterEncryption = generateWriterEncryption(); writeOrcColumnsPresto(tempFile.getFile(), format, compression, Optional.of(dwrfWriterEncryption), writeTypes, writeValues, stats); ImmutableMap.Builder<Integer, Slice> intermediateKeysBuilder = ImmutableMap.builder(); for (int i = 0; i < dwrfWriterEncryption.getWriterEncryptionGroups().size(); i++) { for (Integer node : dwrfWriterEncryption.getWriterEncryptionGroups().get(i).getNodes()) { intermediateKeysBuilder.put(node, dwrfWriterEncryption.getWriterEncryptionGroups().get(i).getIntermediateKeyMetadata()); } } Map<Integer, Slice> intermediateKeysMap = intermediateKeysBuilder.build(); assertFileContentsPresto( readTypes, tempFile, readValues, false, false, orcEncoding, format, false, useSelectiveOrcReader, settings, intermediateKeysMap); if (skipBatchTestsEnabled) { assertFileContentsPresto( readTypes, tempFile, readValues, true, false, orcEncoding, format, false, useSelectiveOrcReader, settings, intermediateKeysMap); } if (skipStripeTestsEnabled) { assertFileContentsPresto( readTypes, tempFile, readValues, false, true, orcEncoding, format, false, useSelectiveOrcReader, settings, intermediateKeysMap); } } } } } assertEquals(stats.getWriterSizeInBytes(), 0); } public static class OrcReaderSettings { private final Map<Integer, Map<Subfield, TupleDomainFilter>> columnFilters; private final List<Integer> expectedFilterOrder; private final List<FilterFunction> filterFunctions; private final Map<Integer, Integer> filterFunctionInputMapping; private final Map<Integer, List<Subfield>> requiredSubfields; private final OrcFileTailSource orcFileTailSource; private OrcReaderSettings( Map<Integer, Map<Subfield, TupleDomainFilter>> columnFilters, List<Integer> expectedFilterOrder, List<FilterFunction> filterFunctions, Map<Integer, Integer> filterFunctionInputMapping, Map<Integer, List<Subfield>> requiredSubfields, OrcFileTailSource orcFileTailSource) { this.columnFilters = requireNonNull(columnFilters, "columnFilters is null"); this.expectedFilterOrder = requireNonNull(expectedFilterOrder, "expectedFilterOrder is null"); this.filterFunctions = requireNonNull(filterFunctions, "filterFunctions is null"); this.filterFunctionInputMapping = requireNonNull(filterFunctionInputMapping, "filterFunctionInputMapping is null"); this.requiredSubfields = requireNonNull(requiredSubfields, "requiredSubfields is null"); this.orcFileTailSource = requireNonNull(orcFileTailSource, "orcFileTailSource is null"); } public Map<Integer, Map<Subfield, TupleDomainFilter>> getColumnFilters() { return columnFilters; } public List<Integer> getExpectedFilterOrder() { return expectedFilterOrder; } public List<FilterFunction> getFilterFunctions() { return filterFunctions; } public Map<Integer, Integer> getFilterFunctionInputMapping() { return filterFunctionInputMapping; } public Map<Integer, List<Subfield>> getRequiredSubfields() { return requiredSubfields; } public OrcFileTailSource getOrcFileTailSource() { return orcFileTailSource; } public static Builder builder() { return new Builder(); } public static class Builder { private Map<Integer, Map<Subfield, TupleDomainFilter>> columnFilters = ImmutableMap.of(); private List<Integer> expectedFilterOrder = ImmutableList.of(); private List<FilterFunction> filterFunctions = ImmutableList.of(); private Map<Integer, Integer> filterFunctionInputMapping = ImmutableMap.of(); private Map<Integer, List<Subfield>> requiredSubfields = new HashMap<>(); private OrcFileTailSource orcFileTailSource = new StorageOrcFileTailSource(); public Builder setColumnFilters(Map<Integer, Map<Subfield, TupleDomainFilter>> columnFilters) { this.columnFilters = requireNonNull(columnFilters, "columnFilters is null"); return this; } public Builder setExpectedFilterOrder(List<Integer> expectedFilterOrder) { this.expectedFilterOrder = requireNonNull(expectedFilterOrder, "expectedFilterOrder is null"); return this; } public Builder setFilterFunctions(List<FilterFunction> filterFunctions) { this.filterFunctions = requireNonNull(filterFunctions, "filterFunctions is null"); return this; } public Builder setFilterFunctionMapping(Map<Integer, Integer> filterFunctionInputMapping) { this.filterFunctionInputMapping = requireNonNull(filterFunctionInputMapping, "filterFunctionInputMapping is null"); return this; } public Builder setRequiredSubfields(Map<Integer, List<Subfield>> requiredSubfields) { requireNonNull(requiredSubfields, "requiredSubfields is null"); this.requiredSubfields.clear(); this.requiredSubfields.putAll(requiredSubfields); return this; } public Builder addRequiredSubfields(int column, String... subfields) { this.requiredSubfields.put(column, Arrays.stream(subfields).map(subfield -> new Subfield(subfield)).collect(toImmutableList())); return this; } public Builder setOrcFileTailSource(OrcFileTailSource orcFileTailSource) { this.orcFileTailSource = requireNonNull(orcFileTailSource, "orcFileTailSource is null"); return this; } public OrcReaderSettings build() { return new OrcReaderSettings(columnFilters, expectedFilterOrder, filterFunctions, filterFunctionInputMapping, requiredSubfields, orcFileTailSource); } } } public static void assertFileContentsPresto( List<Type> types, File file, List<List<?>> expectedValues, OrcEncoding orcEncoding, OrcPredicate orcPredicate, Optional<Map<Integer, Map<Subfield, TupleDomainFilter>>> filters, List<FilterFunction> filterFunctions, Map<Integer, Integer> filterFunctionInputMapping, Map<Integer, List<Subfield>> requiredSubfields) throws IOException { Map<Integer, Type> includedColumns = IntStream.range(0, types.size()) .boxed() .collect(toImmutableMap(Function.identity(), types::get)); List<Integer> outputColumns = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList()); assertFileContentsPresto( types, file, expectedValues, orcEncoding, orcPredicate, filters, filterFunctions, filterFunctionInputMapping, requiredSubfields, ImmutableMap.of(), includedColumns, outputColumns); } public static void assertFileContentsPresto( List<Type> types, File file, List<List<?>> expectedValues, OrcEncoding orcEncoding, OrcPredicate orcPredicate, Optional<Map<Integer, Map<Subfield, TupleDomainFilter>>> filters, List<FilterFunction> filterFunctions, Map<Integer, Integer> filterFunctionInputMapping, Map<Integer, List<Subfield>> requiredSubfields, Map<Integer, Slice> intermediateEncryptionKeys, Map<Integer, Type> includedColumns, List<Integer> outputColumns) throws IOException { try (OrcSelectiveRecordReader recordReader = createCustomOrcSelectiveRecordReader( file, orcEncoding, orcPredicate, types, MAX_BATCH_SIZE, filters.orElse(ImmutableMap.of()), filterFunctions, filterFunctionInputMapping, requiredSubfields, intermediateEncryptionKeys, includedColumns, outputColumns, false, new TestingHiveOrcAggregatedMemoryContext())) { assertEquals(recordReader.getReaderPosition(), 0); assertEquals(recordReader.getFilePosition(), 0); int rowsProcessed = 0; while (true) { Page page = recordReader.getNextPage(); if (page == null) { break; } int positionCount = page.getPositionCount(); if (positionCount == 0) { continue; } assertTrue(expectedValues.get(0).size() >= rowsProcessed + positionCount); for (int i = 0; i < outputColumns.size(); i++) { Type type = types.get(outputColumns.get(i)); Block block = page.getBlock(i); assertEquals(block.getPositionCount(), positionCount); checkNullValues(type, block); List<Object> data = new ArrayList<>(positionCount); for (int position = 0; position < positionCount; position++) { data.add(type.getObjectValue(SESSION.getSqlFunctionProperties(), block, position)); } for (int position = 0; position < positionCount; position++) { assertColumnValueEquals(type, data.get(position), expectedValues.get(i).get(rowsProcessed + position)); } } rowsProcessed += positionCount; } assertEquals(rowsProcessed, expectedValues.get(0).size()); } } private static Map<Integer, Map<Subfield, TupleDomainFilter>> addOrderTracking(Map<Integer, Map<Subfield, TupleDomainFilter>> filters, TupleDomainFilterOrderChecker orderChecker) { return Maps.transformEntries(filters, (column, columnFilters) -> Maps.transformValues(columnFilters, filter -> addOrderTracking(filter, orderChecker, column))); } private static TupleDomainFilter addOrderTracking(TupleDomainFilter filter, TupleDomainFilterOrderChecker orderChecker, int column) { if (filter instanceof BigintRange) { return TestBigintRange.of((BigintRange) filter, unused -> orderChecker.call(column)); } if (filter instanceof DoubleRange) { return TestDoubleRange.of((DoubleRange) filter, unused -> orderChecker.call(column)); } throw new UnsupportedOperationException("Unsupported filter type: " + filter.getClass().getSimpleName()); } private static void assertFileContentsPresto( List<Type> types, TempFile tempFile, List<List<?>> expectedValues, boolean skipFirstBatch, boolean skipStripe, OrcEncoding orcEncoding, Format format, boolean isHiveWriter, boolean useSelectiveOrcReader, List<OrcReaderSettings> settings, Map<Integer, Slice> intermediateEncryptionKeys) throws IOException { OrcPredicate orcPredicate = createOrcPredicate(types, expectedValues, format, isHiveWriter); Map<Integer, Type> includedColumns = IntStream.range(0, types.size()) .boxed() .collect(toImmutableMap(Function.identity(), types::get)); List<Integer> outputColumns = IntStream.range(0, types.size()) .boxed() .collect(toImmutableList()); if (useSelectiveOrcReader) { assertFileContentsPresto( types, tempFile.getFile(), expectedValues, orcEncoding, orcPredicate, Optional.empty(), ImmutableList.of(), ImmutableMap.of(), ImmutableMap.of(), intermediateEncryptionKeys, includedColumns, outputColumns); for (OrcReaderSettings entry : settings) { assertTrue(entry.getFilterFunctions().isEmpty(), "Filter functions are not supported yet"); assertTrue(entry.getFilterFunctionInputMapping().isEmpty(), "Filter functions are not supported yet"); Map<Integer, Map<Subfield, TupleDomainFilter>> columnFilters = entry.getColumnFilters(); List<List<?>> prunedAndFilteredRows = pruneValues(types, filterRows(types, expectedValues, columnFilters), entry.getRequiredSubfields()); Optional<TupleDomainFilterOrderChecker> orderChecker = Optional.empty(); List<Integer> expectedFilterOrder = entry.getExpectedFilterOrder(); if (!expectedFilterOrder.isEmpty()) { orderChecker = Optional.of(new TupleDomainFilterOrderChecker(expectedFilterOrder)); } Optional<Map<Integer, Map<Subfield, TupleDomainFilter>>> transformedFilters = Optional.of(orderChecker.map(checker -> addOrderTracking(columnFilters, checker)).orElse(columnFilters)); assertFileContentsPresto( types, tempFile.getFile(), prunedAndFilteredRows, orcEncoding, orcPredicate, transformedFilters, entry.getFilterFunctions(), entry.getFilterFunctionInputMapping(), entry.getRequiredSubfields()); orderChecker.ifPresent(TupleDomainFilterOrderChecker::assertOrder); } return; } try (OrcBatchRecordReader recordReader = createCustomOrcRecordReader(tempFile, orcEncoding, orcPredicate, types, MAX_BATCH_SIZE, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), false, intermediateEncryptionKeys, false)) { assertEquals(recordReader.getReaderPosition(), 0); assertEquals(recordReader.getFilePosition(), 0); boolean isFirst = true; int rowsProcessed = 0; for (int batchSize = toIntExact(recordReader.nextBatch()); batchSize >= 0; batchSize = toIntExact(recordReader.nextBatch())) { if (skipStripe && rowsProcessed < 10000) { // skip recordReader.readBlock } else if (skipFirstBatch && isFirst) { // skip recordReader.readBlock isFirst = false; } else { for (int i = 0; i < types.size(); i++) { Type type = types.get(i); Block block = recordReader.readBlock(i); assertEquals(block.getPositionCount(), batchSize); checkNullValues(type, block); List<Object> data = new ArrayList<>(block.getPositionCount()); for (int position = 0; position < block.getPositionCount(); position++) { data.add(type.getObjectValue(SESSION.getSqlFunctionProperties(), block, position)); } for (int position = 0; position < block.getPositionCount(); position++) { assertColumnValueEquals(type, data.get(position), expectedValues.get(i).get(rowsProcessed + position)); } } } assertEquals(recordReader.getReaderPosition(), rowsProcessed); assertEquals(recordReader.getFilePosition(), rowsProcessed); rowsProcessed += batchSize; } assertEquals(rowsProcessed, expectedValues.get(0).size()); assertEquals(recordReader.getReaderPosition(), rowsProcessed); assertEquals(recordReader.getFilePosition(), rowsProcessed); } } public static List<List<?>> filterRows(List<Type> types, List<List<?>> values, Map<Integer, Map<Subfield, TupleDomainFilter>> columnFilters) { if (columnFilters.isEmpty()) { return values; } List<Integer> passingRows = IntStream.range(0, values.get(0).size()) .filter(row -> testRow(types, values, row, columnFilters)) .boxed() .collect(toList()); return IntStream.range(0, values.size()) .mapToObj(column -> passingRows.stream().map(values.get(column)::get).collect(toList())) .collect(toList()); } private static boolean testRow(List<Type> types, List<List<?>> values, int row, Map<Integer, Map<Subfield, TupleDomainFilter>> columnFilters) { for (int column = 0; column < types.size(); column++) { Map<Subfield, TupleDomainFilter> filters = columnFilters.get(column); if (filters == null) { continue; } Type type = types.get(column); Object value = values.get(column).get(row); for (Map.Entry<Subfield, TupleDomainFilter> entry : filters.entrySet()) { if (!testSubfieldValue(type, value, entry.getKey(), entry.getValue())) { return false; } } } return true; } private static boolean testSubfieldValue(Type type, Object value, Subfield subfield, TupleDomainFilter filter) { Type nestedType = type; Object nestedValue = value; for (Subfield.PathElement pathElement : subfield.getPath()) { if (nestedType instanceof ArrayType) { assertTrue(pathElement instanceof Subfield.LongSubscript); if (nestedValue == null) { return filter == IS_NULL; } int index = toIntExact(((Subfield.LongSubscript) pathElement).getIndex()) - 1; nestedType = ((ArrayType) nestedType).getElementType(); if (index >= ((List) nestedValue).size()) { return true; } nestedValue = ((List) nestedValue).get(index); } else if (nestedType instanceof RowType) { assertTrue(pathElement instanceof Subfield.NestedField); if (nestedValue == null) { return filter.testNull(); } String fieldName = ((Subfield.NestedField) pathElement).getName(); int index = -1; List<RowType.Field> fields = ((RowType) nestedType).getFields(); for (int i = 0; i < fields.size(); i++) { if (fieldName.equalsIgnoreCase(fields.get(i).getName().get())) { index = i; nestedType = fields.get(i).getType(); break; } } assertTrue(index >= 0, "Struct field not found: " + fieldName); nestedValue = ((List) nestedValue).get(index); } else { fail("Unsupported type: " + type); } } return testValue(nestedType, nestedValue, filter); } private static boolean testValue(Type type, Object value, TupleDomainFilter filter) { if (value == null) { return filter.testNull(); } if (filter == IS_NULL) { return false; } if (filter == IS_NOT_NULL) { return true; } if (type == BOOLEAN) { return filter.testBoolean((Boolean) value); } if (type == TINYINT || type == BIGINT || type == INTEGER || type == SMALLINT) { return filter.testLong(((Number) value).longValue()); } if (type == REAL) { return filter.testFloat(((Number) value).floatValue()); } if (type == DOUBLE) { return filter.testDouble((double) value); } if (type == DATE) { return filter.testLong(((SqlDate) value).getDays()); } if (type == TIMESTAMP) { return filter.testLong(((SqlTimestamp) value).getMillisUtc()); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; BigDecimal bigDecimal = ((SqlDecimal) value).toBigDecimal(); if (decimalType.isShort()) { return filter.testLong(bigDecimal.unscaledValue().longValue()); } else { Slice encodedDecimal = Decimals.encodeScaledValue(bigDecimal); return filter.testDecimal(encodedDecimal.getLong(0), encodedDecimal.getLong(Long.BYTES)); } } if (type == VARCHAR) { return filter.testBytes(((String) value).getBytes(), 0, ((String) value).length()); } if (type instanceof CharType) { String charString = String.valueOf(value); return filter.testBytes(charString.getBytes(), 0, charString.length()); } if (type == VARBINARY) { byte[] binary = ((SqlVarbinary) value).getBytes(); return filter.testBytes(binary, 0, binary.length); } fail("Unsupported type: " + type); return false; } private interface SubfieldPruner { Object prune(Object value); } private static SubfieldPruner createSubfieldPruner(Type type, List<Subfield> requiredSubfields) { if (type instanceof ArrayType) { return new ListSubfieldPruner(type, requiredSubfields); } if (type instanceof MapType) { return new MapSubfieldPruner(type, requiredSubfields); } throw new UnsupportedOperationException("Unsupported type: " + type); } private static class ListSubfieldPruner implements SubfieldPruner { private final int maxIndex; private final Optional<SubfieldPruner> nestedSubfieldPruner; public ListSubfieldPruner(Type type, List<Subfield> requiredSubfields) { checkArgument(type instanceof ArrayType, "type is not an array type: " + type); maxIndex = requiredSubfields.stream() .map(Subfield::getPath) .map(path -> path.get(0)) .map(Subfield.LongSubscript.class::cast) .map(Subfield.LongSubscript::getIndex) .mapToInt(Long::intValue) .max() .orElse(-1); List<Subfield> elementSubfields = requiredSubfields.stream() .filter(subfield -> subfield.getPath().size() > 1) .map(subfield -> subfield.tail(subfield.getRootName())) .distinct() .collect(toImmutableList()); if (elementSubfields.isEmpty()) { nestedSubfieldPruner = Optional.empty(); } else { nestedSubfieldPruner = Optional.of(createSubfieldPruner(((ArrayType) type).getElementType(), elementSubfields)); } } @Override public Object prune(Object value) { if (value == null) { return null; } List list = (List) value; List prunedList; if (maxIndex == -1) { prunedList = list; } else { prunedList = list.size() < maxIndex ? list : list.subList(0, maxIndex); } return nestedSubfieldPruner.map(pruner -> prunedList.stream().map(pruner::prune).collect(toList())).orElse(prunedList); } } private static class MapSubfieldPruner implements SubfieldPruner { private final Set<Long> keys; private final Optional<SubfieldPruner> nestedSubfieldPruner; public MapSubfieldPruner(Type type, List<Subfield> requiredSubfields) { checkArgument(type instanceof MapType, "type is not a map type: " + type); keys = requiredSubfields.stream() .map(Subfield::getPath) .map(path -> path.get(0)) .map(Subfield.LongSubscript.class::cast) .map(Subfield.LongSubscript::getIndex) .collect(toImmutableSet()); List<Subfield> elementSubfields = requiredSubfields.stream() .filter(subfield -> subfield.getPath().size() > 1) .map(subfield -> subfield.tail(subfield.getRootName())) .distinct() .collect(toImmutableList()); if (elementSubfields.isEmpty()) { nestedSubfieldPruner = Optional.empty(); } else { nestedSubfieldPruner = Optional.of(createSubfieldPruner(((MapType) type).getValueType(), elementSubfields)); } } @Override public Object prune(Object value) { if (value == null) { return null; } Map map = (Map) value; Map prunedMap; if (keys.isEmpty()) { prunedMap = map; } else { prunedMap = Maps.filterKeys((Map) value, key -> keys.contains(Long.valueOf(((Number) key).longValue()))); } return nestedSubfieldPruner.map(pruner -> Maps.transformValues(prunedMap, pruner::prune)).orElse(prunedMap); } } private static List<List<?>> pruneValues(List<Type> types, List<List<?>> values, Map<Integer, List<Subfield>> requiredSubfields) { if (requiredSubfields.isEmpty()) { return values; } ImmutableList.Builder<List<?>> builder = ImmutableList.builder(); for (int i = 0; i < types.size(); i++) { List<Subfield> subfields = requiredSubfields.get(i); if (subfields.isEmpty()) { builder.add(values.get(i)); continue; } SubfieldPruner subfieldPruner = createSubfieldPruner(types.get(i), subfields); builder.add(values.get(i).stream().map(subfieldPruner::prune).collect(toList())); } return builder.build(); } private static void assertColumnValueEquals(Type type, Object actual, Object expected) { if (actual == null) { assertEquals(actual, expected); return; } String baseType = type.getTypeSignature().getBase(); if (StandardTypes.ARRAY.equals(baseType)) { List<?> actualArray = (List<?>) actual; List<?> expectedArray = (List<?>) expected; assertEquals(actualArray == null, expectedArray == null); assertEquals(actualArray.size(), expectedArray.size()); Type elementType = type.getTypeParameters().get(0); for (int i = 0; i < actualArray.size(); i++) { Object actualElement = actualArray.get(i); Object expectedElement = expectedArray.get(i); assertColumnValueEquals(elementType, actualElement, expectedElement); } } else if (StandardTypes.MAP.equals(baseType)) { Map<?, ?> actualMap = (Map<?, ?>) actual; Map<?, ?> expectedMap = (Map<?, ?>) expected; assertEquals(actualMap.size(), expectedMap.size()); Type keyType = type.getTypeParameters().get(0); Type valueType = type.getTypeParameters().get(1); List<Entry<?, ?>> expectedEntries = new ArrayList<>(expectedMap.entrySet()); for (Entry<?, ?> actualEntry : actualMap.entrySet()) { for (Iterator<Entry<?, ?>> iterator = expectedEntries.iterator(); iterator.hasNext(); ) { Entry<?, ?> expectedEntry = iterator.next(); try { assertColumnValueEquals(keyType, actualEntry.getKey(), expectedEntry.getKey()); assertColumnValueEquals(valueType, actualEntry.getValue(), expectedEntry.getValue()); iterator.remove(); } catch (AssertionError ignored) { } } } assertTrue(expectedEntries.isEmpty(), "Unmatched entries " + expectedEntries); } else if (StandardTypes.ROW.equals(baseType)) { List<Type> fieldTypes = type.getTypeParameters(); List<?> actualRow = (List<?>) actual; List<?> expectedRow = (List<?>) expected; assertEquals(actualRow.size(), fieldTypes.size()); assertEquals(actualRow.size(), expectedRow.size()); for (int fieldId = 0; fieldId < actualRow.size(); fieldId++) { Type fieldType = fieldTypes.get(fieldId); Object actualElement = actualRow.get(fieldId); Object expectedElement = expectedRow.get(fieldId); assertColumnValueEquals(fieldType, actualElement, expectedElement); } } else if (type.equals(DOUBLE)) { Double actualDouble = (Double) actual; Double expectedDouble = (Double) expected; if (actualDouble.isNaN()) { assertTrue(expectedDouble.isNaN(), "expected double to be NaN"); } else { assertEquals(actualDouble, expectedDouble, 0.001); } } else if (!Objects.equals(actual, expected)) { assertEquals(actual, expected); } } static OrcBatchRecordReader createCustomOrcRecordReader(TempFile tempFile, OrcEncoding orcEncoding, OrcPredicate predicate, Type type, int initialBatchSize, boolean cacheable, boolean mapNullKeysEnabled) throws IOException { return createCustomOrcRecordReader(tempFile, orcEncoding, predicate, ImmutableList.of(type), initialBatchSize, cacheable, mapNullKeysEnabled); } static OrcBatchRecordReader createCustomOrcRecordReader(TempFile tempFile, OrcEncoding orcEncoding, OrcPredicate predicate, List<Type> types, int initialBatchSize, boolean cacheable, boolean mapNullKeysEnabled) throws IOException { return createCustomOrcRecordReader(tempFile, orcEncoding, predicate, types, initialBatchSize, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), cacheable, ImmutableMap.of(), mapNullKeysEnabled); } static OrcBatchRecordReader createCustomOrcRecordReader( TempFile tempFile, OrcEncoding orcEncoding, OrcPredicate predicate, List<Type> types, int initialBatchSize, OrcFileTailSource orcFileTailSource, StripeMetadataSource stripeMetadataSource, boolean cacheable, Map<Integer, Slice> intermediateEncryptionKeys, boolean mapNullKeysEnabled) throws IOException { OrcDataSource orcDataSource = new FileOrcDataSource(tempFile.getFile(), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( orcDataSource, orcEncoding, orcFileTailSource, stripeMetadataSource, Optional.empty(), NOOP_ORC_AGGREGATED_MEMORY_CONTEXT, new OrcReaderOptions( new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), MAX_BLOCK_SIZE, false, mapNullKeysEnabled, false), cacheable, new DwrfEncryptionProvider(new UnsupportedEncryptionLibrary(), new TestingEncryptionLibrary())); assertEquals(orcReader.getFooter().getRowsInRowGroup(), 10_000); Map<Integer, Type> columnTypes = IntStream.range(0, types.size()) .boxed() .collect(toImmutableMap(Functions.identity(), types::get)); return orcReader.createBatchRecordReader(columnTypes, predicate, HIVE_STORAGE_TIME_ZONE, new TestingHiveOrcAggregatedMemoryContext(), initialBatchSize, intermediateEncryptionKeys); } public static void writeOrcColumnPresto(File outputFile, Format format, CompressionKind compression, Type type, List<?> values) throws Exception { writeOrcColumnsPresto(outputFile, format, compression, Optional.empty(), ImmutableList.of(type), ImmutableList.of(values), new OrcWriterStats()); } public static void writeOrcColumnsPresto(File outputFile, Format format, CompressionKind compression, Optional<DwrfWriterEncryption> dwrfWriterEncryption, List<Type> types, List<List<?>> values, OrcWriterStats stats) throws Exception { List<String> columnNames = makeColumnNames(types.size()); ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("columns", String.join(", ", columnNames)); metadata.put("columns.types", createSettableStructObjectInspector(types).getTypeName()); OrcWriter writer = new OrcWriter( new OutputStreamDataSink(new FileOutputStream(outputFile)), columnNames, types, format.getOrcEncoding(), compression, dwrfWriterEncryption, new DwrfEncryptionProvider(new UnsupportedEncryptionLibrary(), new TestingEncryptionLibrary()), new OrcWriterOptions(), ImmutableMap.of(), HIVE_STORAGE_TIME_ZONE, true, BOTH, stats); Block[] blocks = new Block[types.size()]; for (int i = 0; i < types.size(); i++) { Type type = types.get(i); BlockBuilder blockBuilder = type.createBlockBuilder(null, 1024); for (Object value : values.get(i)) { writeValue(type, blockBuilder, value); } blocks[i] = blockBuilder.build(); } writer.write(new Page(blocks)); writer.close(); writer.validate(new FileOrcDataSource( outputFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true)); } private static DwrfWriterEncryption generateWriterEncryption() { return new DwrfWriterEncryption( UNKNOWN, ImmutableList.of( new WriterEncryptionGroup( ImmutableList.of(1), Slices.utf8Slice("encryptionKey")))); } static OrcSelectiveRecordReader createCustomOrcSelectiveRecordReader( TempFile tempFile, OrcEncoding orcEncoding, OrcPredicate predicate, Type type, int initialBatchSize, boolean mapNullKeysEnabled) throws IOException { return createCustomOrcSelectiveRecordReader( tempFile.getFile(), orcEncoding, predicate, ImmutableList.of(type), initialBatchSize, ImmutableMap.of(), ImmutableList.of(), ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(), ImmutableMap.of(0, type), ImmutableList.of(0), mapNullKeysEnabled, new TestingHiveOrcAggregatedMemoryContext()); } public static OrcSelectiveRecordReader createCustomOrcSelectiveRecordReader( File file, OrcEncoding orcEncoding, OrcPredicate predicate, List<Type> types, int initialBatchSize, Map<Integer, Map<Subfield, TupleDomainFilter>> filters, List<FilterFunction> filterFunctions, Map<Integer, Integer> filterFunctionInputMapping, Map<Integer, List<Subfield>> requiredSubfields, Map<Integer, Slice> intermediateEncryptionKeys, Map<Integer, Type> includedColumns, List<Integer> outputColumns, boolean mapNullKeysEnabled, OrcAggregatedMemoryContext systemMemoryUsage) throws IOException { OrcDataSource orcDataSource = new FileOrcDataSource(file, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader( orcDataSource, orcEncoding, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), NOOP_ORC_AGGREGATED_MEMORY_CONTEXT, new OrcReaderOptions( new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), MAX_BLOCK_SIZE, false, mapNullKeysEnabled, false), false, new DwrfEncryptionProvider(new UnsupportedEncryptionLibrary(), new TestingEncryptionLibrary())); assertEquals(orcReader.getColumnNames().subList(0, types.size()), makeColumnNames(types.size())); assertEquals(orcReader.getFooter().getRowsInRowGroup(), 10_000); return orcReader.createSelectiveRecordReader( includedColumns, outputColumns, filters, filterFunctions, filterFunctionInputMapping, requiredSubfields, ImmutableMap.of(), ImmutableMap.of(), predicate, 0, orcDataSource.getSize(), HIVE_STORAGE_TIME_ZONE, LEGACY_MAP_SUBSCRIPT, systemMemoryUsage, Optional.empty(), initialBatchSize, intermediateEncryptionKeys); } private static void writeValue(Type type, BlockBuilder blockBuilder, Object value) { if (value == null) { blockBuilder.appendNull(); } else { if (BOOLEAN.equals(type)) { type.writeBoolean(blockBuilder, (Boolean) value); } else if (TINYINT.equals(type) || SMALLINT.equals(type) || INTEGER.equals(type) || BIGINT.equals(type)) { type.writeLong(blockBuilder, ((Number) value).longValue()); } else if (Decimals.isShortDecimal(type)) { type.writeLong(blockBuilder, ((SqlDecimal) value).toBigDecimal().unscaledValue().longValue()); } else if (Decimals.isLongDecimal(type)) { type.writeSlice(blockBuilder, Decimals.encodeUnscaledValue(((SqlDecimal) value).toBigDecimal().unscaledValue())); } else if (DOUBLE.equals(type)) { type.writeDouble(blockBuilder, ((Number) value).doubleValue()); } else if (REAL.equals(type)) { float floatValue = ((Number) value).floatValue(); type.writeLong(blockBuilder, Float.floatToIntBits(floatValue)); } else if (type instanceof VarcharType) { Slice slice = truncateToLength(utf8Slice((String) value), type); type.writeSlice(blockBuilder, slice); } else if (type instanceof CharType) { Slice slice = truncateToLengthAndTrimSpaces(utf8Slice((String) value), type); type.writeSlice(blockBuilder, slice); } else if (VARBINARY.equals(type)) { type.writeSlice(blockBuilder, Slices.wrappedBuffer(((SqlVarbinary) value).getBytes())); } else if (DATE.equals(type)) { long days = ((SqlDate) value).getDays(); type.writeLong(blockBuilder, days); } else if (TIMESTAMP.equals(type)) { long millis = ((SqlTimestamp) value).getMillisUtc(); type.writeLong(blockBuilder, millis); } else { String baseType = type.getTypeSignature().getBase(); if (StandardTypes.ARRAY.equals(baseType)) { List<?> array = (List<?>) value; Type elementType = type.getTypeParameters().get(0); BlockBuilder arrayBlockBuilder = blockBuilder.beginBlockEntry(); for (Object elementValue : array) { writeValue(elementType, arrayBlockBuilder, elementValue); } blockBuilder.closeEntry(); } else if (StandardTypes.MAP.equals(baseType)) { Map<?, ?> map = (Map<?, ?>) value; Type keyType = type.getTypeParameters().get(0); Type valueType = type.getTypeParameters().get(1); BlockBuilder mapBlockBuilder = blockBuilder.beginBlockEntry(); for (Entry<?, ?> entry : map.entrySet()) { writeValue(keyType, mapBlockBuilder, entry.getKey()); writeValue(valueType, mapBlockBuilder, entry.getValue()); } blockBuilder.closeEntry(); } else if (StandardTypes.ROW.equals(baseType)) { List<?> array = (List<?>) value; List<Type> fieldTypes = type.getTypeParameters(); BlockBuilder rowBlockBuilder = blockBuilder.beginBlockEntry(); for (int fieldId = 0; fieldId < fieldTypes.size(); fieldId++) { Type fieldType = fieldTypes.get(fieldId); writeValue(fieldType, rowBlockBuilder, array.get(fieldId)); } blockBuilder.closeEntry(); } else { throw new IllegalArgumentException("Unsupported type " + type); } } } } private static void assertFileContentsHive( List<Type> types, TempFile tempFile, Format format, List<List<?>> expectedValues) throws Exception { if (format == DWRF) { assertFileContentsDwrfHive(types, tempFile, expectedValues); } else { assertFileContentsOrcHive(types, tempFile, expectedValues); } } private static void assertFileContentsOrcHive( List<Type> types, TempFile tempFile, List<List<?>> expectedValues) throws Exception { JobConf configuration = new JobConf(new Configuration(false)); configuration.set(READ_COLUMN_IDS_CONF_STR, "0"); configuration.setBoolean(READ_ALL_COLUMNS, false); Reader reader = OrcFile.createReader( new Path(tempFile.getFile().getAbsolutePath()), new ReaderOptions(configuration)); org.apache.hadoop.hive.ql.io.orc.RecordReader recordReader = reader.rows(); StructObjectInspector rowInspector = (StructObjectInspector) reader.getObjectInspector(); List<StructField> fields = makeColumnNames(types.size()).stream() .map(rowInspector::getStructFieldRef) .collect(toList()); Object rowData = null; int rowCount = 0; while (recordReader.hasNext()) { rowData = recordReader.next(rowData); for (int i = 0; i < fields.size(); i++) { Object actualValue = rowInspector.getStructFieldData(rowData, fields.get(i)); actualValue = decodeRecordReaderValue(types.get(i), actualValue); assertColumnValueEquals(types.get(i), actualValue, expectedValues.get(i).get(rowCount)); } rowCount++; } assertEquals(rowCount, expectedValues.get(0).size()); } private static void assertFileContentsDwrfHive( List<Type> types, TempFile tempFile, List<List<?>> expectedValues) throws Exception { JobConf configuration = new JobConf(new Configuration(false)); configuration.set(READ_COLUMN_IDS_CONF_STR, "0"); configuration.setBoolean(READ_ALL_COLUMNS, false); Path path = new Path(tempFile.getFile().getAbsolutePath()); com.facebook.hive.orc.Reader reader = com.facebook.hive.orc.OrcFile.createReader( path.getFileSystem(configuration), path, configuration); boolean[] include = new boolean[reader.getTypes().size() + 100000]; Arrays.fill(include, true); com.facebook.hive.orc.RecordReader recordReader = reader.rows(include); StructObjectInspector rowInspector = (StructObjectInspector) reader.getObjectInspector(); List<StructField> fields = makeColumnNames(types.size()).stream() .map(rowInspector::getStructFieldRef) .collect(toList()); Object rowData = null; int rowCount = 0; while (recordReader.hasNext()) { rowData = recordReader.next(rowData); for (int i = 0; i < fields.size(); i++) { Object actualValue = rowInspector.getStructFieldData(rowData, fields.get(i)); actualValue = decodeRecordReaderValue(types.get(i), actualValue); assertColumnValueEquals(types.get(i), actualValue, expectedValues.get(i).get(rowCount)); } rowCount++; } assertEquals(rowCount, expectedValues.get(0).size()); } private static List<String> makeColumnNames(int columns) { return IntStream.range(0, columns) .mapToObj(i -> i == 0 ? "test" : "test" + (i + 1)) .collect(toList()); } private static Object decodeRecordReaderValue(Type type, Object actualValue) { if (actualValue instanceof OrcLazyObject) { try { actualValue = ((OrcLazyObject) actualValue).materialize(); } catch (IOException e) { throw new UncheckedIOException(e); } } if (actualValue instanceof BooleanWritable) { actualValue = ((BooleanWritable) actualValue).get(); } else if (actualValue instanceof ByteWritable) { actualValue = ((ByteWritable) actualValue).get(); } else if (actualValue instanceof BytesWritable) { actualValue = new SqlVarbinary(((BytesWritable) actualValue).copyBytes()); } else if (actualValue instanceof DateWritable) { actualValue = new SqlDate(((DateWritable) actualValue).getDays()); } else if (actualValue instanceof DoubleWritable) { actualValue = ((DoubleWritable) actualValue).get(); } else if (actualValue instanceof FloatWritable) { actualValue = ((FloatWritable) actualValue).get(); } else if (actualValue instanceof IntWritable) { actualValue = ((IntWritable) actualValue).get(); } else if (actualValue instanceof HiveCharWritable) { actualValue = ((HiveCharWritable) actualValue).getPaddedValue().toString(); } else if (actualValue instanceof LongWritable) { actualValue = ((LongWritable) actualValue).get(); } else if (actualValue instanceof ShortWritable) { actualValue = ((ShortWritable) actualValue).get(); } else if (actualValue instanceof HiveDecimalWritable) { DecimalType decimalType = (DecimalType) type; HiveDecimalWritable writable = (HiveDecimalWritable) actualValue; // writable messes with the scale so rescale the values to the Presto type BigInteger rescaledValue = rescale(writable.getHiveDecimal().unscaledValue(), writable.getScale(), decimalType.getScale()); actualValue = new SqlDecimal(rescaledValue, decimalType.getPrecision(), decimalType.getScale()); } else if (actualValue instanceof Text) { actualValue = actualValue.toString(); } else if (actualValue instanceof TimestampWritable) { TimestampWritable timestamp = (TimestampWritable) actualValue; actualValue = sqlTimestampOf((timestamp.getSeconds() * 1000) + (timestamp.getNanos() / 1000000L), SESSION); } else if (actualValue instanceof OrcStruct) { List<Object> fields = new ArrayList<>(); OrcStruct structObject = (OrcStruct) actualValue; for (int fieldId = 0; fieldId < structObject.getNumFields(); fieldId++) { fields.add(OrcUtil.getFieldValue(structObject, fieldId)); } actualValue = decodeRecordReaderStruct(type, fields); } else if (actualValue instanceof com.facebook.hive.orc.OrcStruct) { List<Object> fields = new ArrayList<>(); com.facebook.hive.orc.OrcStruct structObject = (com.facebook.hive.orc.OrcStruct) actualValue; for (int fieldId = 0; fieldId < structObject.getNumFields(); fieldId++) { fields.add(structObject.getFieldValue(fieldId)); } actualValue = decodeRecordReaderStruct(type, fields); } else if (actualValue instanceof List) { actualValue = decodeRecordReaderList(type, ((List<?>) actualValue)); } else if (actualValue instanceof Map) { actualValue = decodeRecordReaderMap(type, (Map<?, ?>) actualValue); } return actualValue; } private static List<Object> decodeRecordReaderList(Type type, List<?> list) { Type elementType = type.getTypeParameters().get(0); return list.stream() .map(element -> decodeRecordReaderValue(elementType, element)) .collect(toList()); } private static Object decodeRecordReaderMap(Type type, Map<?, ?> map) { Type keyType = type.getTypeParameters().get(0); Type valueType = type.getTypeParameters().get(1); Map<Object, Object> newMap = new HashMap<>(); for (Entry<?, ?> entry : map.entrySet()) { newMap.put(decodeRecordReaderValue(keyType, entry.getKey()), decodeRecordReaderValue(valueType, entry.getValue())); } return newMap; } private static List<Object> decodeRecordReaderStruct(Type type, List<?> fields) { List<Type> fieldTypes = type.getTypeParameters(); List<Object> newFields = new ArrayList<>(fields.size()); for (int i = 0; i < fields.size(); i++) { Type fieldType = fieldTypes.get(i); Object field = fields.get(i); newFields.add(decodeRecordReaderValue(fieldType, field)); } for (int j = fields.size(); j < fieldTypes.size(); j++) { newFields.add(null); } return newFields; } public static DataSize writeOrcColumnHive(File outputFile, Format format, CompressionKind compression, Type type, List<?> values) throws Exception { return writeOrcColumnsHive(outputFile, format, compression, ImmutableList.of(type), ImmutableList.of(values)); } public static DataSize writeOrcColumnsHive(File outputFile, Format format, CompressionKind compression, List<Type> types, List<List<?>> values) throws Exception { RecordWriter recordWriter; if (DWRF == format) { recordWriter = createDwrfRecordWriter(outputFile, compression, types); } else { recordWriter = createOrcRecordWriter(outputFile, format, compression, types); } return writeOrcFileColumnHive(outputFile, format, recordWriter, types, values); } private static DataSize writeOrcFileColumnHive(File outputFile, Format format, RecordWriter recordWriter, List<Type> types, List<List<?>> values) throws Exception { SettableStructObjectInspector objectInspector = createSettableStructObjectInspector(types); Object row = objectInspector.create(); List<StructField> fields = ImmutableList.copyOf(objectInspector.getAllStructFieldRefs()); @SuppressWarnings("deprecation") Serializer serializer = format.createSerializer(); for (int i = 0; i < values.get(0).size(); i++) { for (int j = 0; j < types.size(); j++) { Object value = preprocessWriteValueHive(types.get(j), values.get(j).get(i)); objectInspector.setStructFieldData(row, fields.get(j), value); } if (DWRF == format) { if (i == 142_345) { setDwrfLowMemoryFlag(recordWriter); } } Writable record = serializer.serialize(row, objectInspector); recordWriter.write(record); } recordWriter.close(false); return succinctBytes(outputFile.length()); } public static DataSize writeOrcFileColumnHive(File outputFile, Format format, RecordWriter recordWriter, Type type, List<?> values) throws Exception { return writeOrcFileColumnHive(outputFile, format, recordWriter, ImmutableList.of(type), ImmutableList.of(values)); } private static ObjectInspector getJavaObjectInspector(Type type) { if (type.equals(BOOLEAN)) { return javaBooleanObjectInspector; } if (type.equals(BIGINT)) { return javaLongObjectInspector; } if (type.equals(INTEGER)) { return javaIntObjectInspector; } if (type.equals(SMALLINT)) { return javaShortObjectInspector; } if (type.equals(TINYINT)) { return javaByteObjectInspector; } if (type.equals(REAL)) { return javaFloatObjectInspector; } if (type.equals(DOUBLE)) { return javaDoubleObjectInspector; } if (type instanceof VarcharType) { return javaStringObjectInspector; } if (type instanceof CharType) { int charLength = ((CharType) type).getLength(); return new JavaHiveCharObjectInspector(getCharTypeInfo(charLength)); } if (type instanceof VarbinaryType) { return javaByteArrayObjectInspector; } if (type.equals(DATE)) { return javaDateObjectInspector; } if (type.equals(TIMESTAMP)) { return javaTimestampObjectInspector; } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; return getPrimitiveJavaObjectInspector(new DecimalTypeInfo(decimalType.getPrecision(), decimalType.getScale())); } if (type.getTypeSignature().getBase().equals(StandardTypes.ARRAY)) { return getStandardListObjectInspector(getJavaObjectInspector(type.getTypeParameters().get(0))); } if (type.getTypeSignature().getBase().equals(StandardTypes.MAP)) { ObjectInspector keyObjectInspector = getJavaObjectInspector(type.getTypeParameters().get(0)); ObjectInspector valueObjectInspector = getJavaObjectInspector(type.getTypeParameters().get(1)); return getStandardMapObjectInspector(keyObjectInspector, valueObjectInspector); } if (type.getTypeSignature().getBase().equals(StandardTypes.ROW)) { return getStandardStructObjectInspector( type.getTypeSignature().getParameters().stream() .map(parameter -> parameter.getNamedTypeSignature().getName().get()) .collect(toList()), type.getTypeParameters().stream() .map(OrcTester::getJavaObjectInspector) .collect(toList())); } throw new IllegalArgumentException("unsupported type: " + type); } private static Object preprocessWriteValueHive(Type type, Object value) { if (value == null) { return null; } if (type.equals(BOOLEAN)) { return value; } else if (type.equals(TINYINT)) { return ((Number) value).byteValue(); } else if (type.equals(SMALLINT)) { return ((Number) value).shortValue(); } else if (type.equals(INTEGER)) { return ((Number) value).intValue(); } else if (type.equals(BIGINT)) { return ((Number) value).longValue(); } else if (type.equals(REAL)) { return ((Number) value).floatValue(); } else if (type.equals(DOUBLE)) { return ((Number) value).doubleValue(); } else if (type instanceof VarcharType) { return value; } else if (type instanceof CharType) { return new HiveChar((String) value, ((CharType) type).getLength()); } else if (type.equals(VARBINARY)) { return ((SqlVarbinary) value).getBytes(); } else if (type.equals(DATE)) { int days = ((SqlDate) value).getDays(); LocalDate localDate = LocalDate.ofEpochDay(days); ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); long millis = SECONDS.toMillis(zonedDateTime.toEpochSecond()); Date date = new Date(0); // millis must be set separately to avoid masking date.setTime(millis); return date; } else if (type.equals(TIMESTAMP)) { long millisUtc = (int) ((SqlTimestamp) value).getMillisUtc(); return new Timestamp(millisUtc); } else if (type instanceof DecimalType) { return HiveDecimal.create(((SqlDecimal) value).toBigDecimal()); } else if (type.getTypeSignature().getBase().equals(StandardTypes.ARRAY)) { Type elementType = type.getTypeParameters().get(0); return ((List<?>) value).stream() .map(element -> preprocessWriteValueHive(elementType, element)) .collect(toList()); } else if (type.getTypeSignature().getBase().equals(StandardTypes.MAP)) { Type keyType = type.getTypeParameters().get(0); Type valueType = type.getTypeParameters().get(1); Map<Object, Object> newMap = new HashMap<>(); for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { newMap.put(preprocessWriteValueHive(keyType, entry.getKey()), preprocessWriteValueHive(valueType, entry.getValue())); } return newMap; } else if (type.getTypeSignature().getBase().equals(StandardTypes.ROW)) { List<?> fieldValues = (List<?>) value; List<Type> fieldTypes = type.getTypeParameters(); List<Object> newStruct = new ArrayList<>(); for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) { newStruct.add(preprocessWriteValueHive(fieldTypes.get(fieldId), fieldValues.get(fieldId))); } return newStruct; } throw new IllegalArgumentException("unsupported type: " + type); } private static void checkNullValues(Type type, Block block) { if (!block.mayHaveNull()) { return; } for (int position = 0; position < block.getPositionCount(); position++) { if (block.isNull(position)) { if (type.equals(TINYINT) || type.equals(SMALLINT) || type.equals(INTEGER) || type.equals(BIGINT) || type.equals(REAL) || type.equals(DATE) || type.equals(TIMESTAMP)) { assertEquals(type.getLong(block, position), 0); } if (type.equals(BOOLEAN)) { assertFalse(type.getBoolean(block, position)); } if (type.equals(DOUBLE)) { assertEquals(type.getDouble(block, position), 0.0); } if (type instanceof VarcharType || type instanceof CharType || type.equals(VARBINARY)) { assertEquals(type.getSlice(block, position).length(), 0); } } } } private static void setDwrfLowMemoryFlag(RecordWriter recordWriter) { Object writer = getFieldValue(recordWriter, "writer"); Object memoryManager = getFieldValue(writer, "memoryManager"); setFieldValue(memoryManager, "lowMemoryMode", true); try { writer.getClass().getMethod("enterLowMemoryMode").invoke(writer); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } private static Object getFieldValue(Object instance, String name) { try { Field writerField = instance.getClass().getDeclaredField(name); writerField.setAccessible(true); return writerField.get(instance); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } private static void setFieldValue(Object instance, String name, Object value) { try { Field writerField = instance.getClass().getDeclaredField(name); writerField.setAccessible(true); writerField.set(instance, value); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } static RecordWriter createOrcRecordWriter(File outputFile, Format format, CompressionKind compression, Type type) throws IOException { return createOrcRecordWriter(outputFile, format, compression, ImmutableList.of(type)); } static RecordWriter createOrcRecordWriter(File outputFile, Format format, CompressionKind compression, List<Type> types) throws IOException { JobConf jobConf = new JobConf(); jobConf.set("hive.exec.orc.write.format", format == ORC_12 ? "0.12" : "0.11"); jobConf.set("hive.exec.orc.default.compress", compression.name()); return new OrcOutputFormat().getHiveRecordWriter( jobConf, new Path(outputFile.toURI()), Text.class, compression != NONE, createTableProperties(types), () -> {}); } private static RecordWriter createDwrfRecordWriter(File outputFile, CompressionKind compressionCodec, List<Type> types) throws IOException { JobConf jobConf = new JobConf(); jobConf.set("hive.exec.orc.default.compress", compressionCodec.name()); jobConf.set("hive.exec.orc.compress", compressionCodec.name()); OrcConf.setIntVar(jobConf, OrcConf.ConfVars.HIVE_ORC_ENTROPY_STRING_THRESHOLD, 1); OrcConf.setIntVar(jobConf, OrcConf.ConfVars.HIVE_ORC_DICTIONARY_ENCODING_INTERVAL, 2); OrcConf.setBoolVar(jobConf, OrcConf.ConfVars.HIVE_ORC_BUILD_STRIDE_DICTIONARY, true); return new com.facebook.hive.orc.OrcOutputFormat().getHiveRecordWriter( jobConf, new Path(outputFile.toURI()), Text.class, compressionCodec != NONE, createTableProperties(types), () -> {}); } static SettableStructObjectInspector createSettableStructObjectInspector(String name, Type type) { return getStandardStructObjectInspector(ImmutableList.of(name), ImmutableList.of(getJavaObjectInspector(type))); } static SettableStructObjectInspector createSettableStructObjectInspector(List<Type> types) { List<ObjectInspector> columnTypes = types.stream() .map(OrcTester::getJavaObjectInspector) .collect(toList()); return getStandardStructObjectInspector(makeColumnNames(types.size()), columnTypes); } private static Properties createTableProperties(List<Type> types) { String columnTypes = types.stream() .map(OrcTester::getJavaObjectInspector) .map(ObjectInspector::getTypeName) .collect(Collectors.joining(", ")); Properties orderTableProperties = new Properties(); orderTableProperties.setProperty("columns", String.join(", ", makeColumnNames(types.size()))); orderTableProperties.setProperty("columns.types", columnTypes); orderTableProperties.setProperty("orc.bloom.filter.columns", String.join(", ", makeColumnNames(types.size()))); orderTableProperties.setProperty("orc.bloom.filter.fpp", "0.50"); orderTableProperties.setProperty("orc.bloom.filter.write.version", "original"); return orderTableProperties; } private static <T> List<T> reverse(List<T> iterable) { return Lists.reverse(ImmutableList.copyOf(iterable)); } private static <T> List<T> insertNullEvery(int n, List<T> iterable) { return newArrayList(() -> new AbstractIterator<T>() { private final Iterator<T> delegate = iterable.iterator(); private int position; private int totalCount; @Override protected T computeNext() { if (totalCount >= iterable.size()) { return endOfData(); } totalCount++; position++; if (position > n) { position = 0; return null; } if (!delegate.hasNext()) { return endOfData(); } return delegate.next(); } }); } public static List<Object> toHiveStruct(Object input) { return asList(input, input, input); } private static List<Object> toHiveStructWithNull(Object input) { return asList(input, input, input, null, null, null); } private static Map<Object, Object> toHiveMap(Object input, Object nullKeyValue) { Map<Object, Object> map = new HashMap<>(); map.put(input != null ? input : nullKeyValue, input); return map; } private static List<Object> toHiveList(Object input) { return asList(input, input, input, input); } private static boolean hasType(Type testType, Set<String> baseTypes) { String testBaseType = testType.getTypeSignature().getBase(); if (StandardTypes.ARRAY.equals(testBaseType)) { Type elementType = testType.getTypeParameters().get(0); return hasType(elementType, baseTypes); } if (StandardTypes.MAP.equals(testBaseType)) { Type keyType = testType.getTypeParameters().get(0); Type valueType = testType.getTypeParameters().get(1); return hasType(keyType, baseTypes) || hasType(valueType, baseTypes); } if (StandardTypes.ROW.equals(testBaseType)) { return testType.getTypeParameters().stream() .anyMatch(fieldType -> hasType(fieldType, baseTypes)); } return baseTypes.contains(testBaseType); } public static Type arrayType(Type elementType) { return FUNCTION_AND_TYPE_MANAGER.getParameterizedType(StandardTypes.ARRAY, ImmutableList.of(TypeSignatureParameter.of(elementType.getTypeSignature()))); } public static Type mapType(Type keyType, Type valueType) { return FUNCTION_AND_TYPE_MANAGER.getParameterizedType(StandardTypes.MAP, ImmutableList.of(TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(valueType.getTypeSignature()))); } public static Type rowType(Type... fieldTypes) { ImmutableList.Builder<TypeSignatureParameter> typeSignatureParameters = ImmutableList.builder(); for (int i = 0; i < fieldTypes.length; i++) { String filedName = "field_" + i; Type fieldType = fieldTypes[i]; typeSignatureParameters.add(TypeSignatureParameter.of(new NamedTypeSignature(Optional.of(new RowFieldName(filedName, false)), fieldType.getTypeSignature()))); } return FUNCTION_AND_TYPE_MANAGER.getParameterizedType(StandardTypes.ROW, typeSignatureParameters.build()); } }
arhimondr/presto
presto-orc/src/test/java/com/facebook/presto/orc/OrcTester.java
Java
apache-2.0
100,255
/* * ModeShape (http://www.modeshape.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.modeshape.connector.cmis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import javax.jcr.Binary; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.PropertyIterator; import javax.jcr.nodetype.NodeType; import javax.jcr.nodetype.NodeTypeIterator; import javax.jcr.nodetype.NodeTypeManager; import javax.jcr.security.AccessControlManager; import javax.jcr.security.AccessControlPolicy; import org.apache.chemistry.opencmis.client.api.Session; import org.apache.chemistry.opencmis.client.api.SessionFactory; import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl; import org.apache.chemistry.opencmis.commons.SessionParameter; import org.apache.chemistry.opencmis.commons.enums.BindingType; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.modeshape.jcr.MultiUseAbstractTest; import org.modeshape.jcr.RepositoryConfiguration; import org.modeshape.jcr.api.Workspace; /** * Provide integration testing of the CMIS connector with OpenCMIS InMemory Repository. * * @author Alexander Voloshyn * @version 1.0 2/20/2013 */ public class CmisConnectorIT extends MultiUseAbstractTest { /** * Test OpenCMIS InMemory Server URL. * <p/> * This OpenCMIS InMemory server instance should be started by maven cargo plugin at pre integration stage. */ private static final String CMIS_URL = "http://localhost:8090/"; private static Logger logger = Logger.getLogger(CmisConnectorIT.class); @BeforeClass public static void beforeAll() throws Exception { RepositoryConfiguration config = RepositoryConfiguration.read("config/repository-1.json"); startRepository(config); // waiting when CMIS repository will be ready boolean isReady = false; // max time for waiting in milliseconds long maxTime = 30000L; // actially waiting time in milliseconds long waitingTime = 0L; // time quant in milliseconds long timeQuant = 500L; logger.info("Waiting for CMIS repository..."); do { try { testDirectChemistryConnect(); isReady = true; } catch (Exception e) { Thread.sleep(timeQuant); waitingTime += timeQuant; } } while (!isReady && waitingTime < maxTime); // checking status if (!isReady) { throw new IllegalStateException("CMIS repository did not respond withing " + maxTime + " milliseconds"); } logger.info("CMIS repository has been started successfuly"); } @AfterClass public static void afterAll() throws Exception { MultiUseAbstractTest.afterAll(); } public static void testDirectChemistryConnect() { // default factory implementation SessionFactory factory = SessionFactoryImpl.newInstance(); Map<String, String> parameter = new HashMap<String, String>(); // connection settings parameter.put(SessionParameter.BINDING_TYPE, BindingType.WEBSERVICES.value()); parameter.put(SessionParameter.WEBSERVICES_ACL_SERVICE, CMIS_URL + "services/ACLService?wsdl"); parameter.put(SessionParameter.WEBSERVICES_DISCOVERY_SERVICE, CMIS_URL + "services/DiscoveryService?wsdl"); parameter.put(SessionParameter.WEBSERVICES_MULTIFILING_SERVICE, CMIS_URL + "services/MultiFilingService?wsdl"); parameter.put(SessionParameter.WEBSERVICES_NAVIGATION_SERVICE, CMIS_URL + "services/NavigationService?wsdl"); parameter.put(SessionParameter.WEBSERVICES_OBJECT_SERVICE, CMIS_URL + "services/ObjectService10?wsdl"); parameter.put(SessionParameter.WEBSERVICES_POLICY_SERVICE, CMIS_URL + "services/PolicyService?wsdl"); parameter.put(SessionParameter.WEBSERVICES_RELATIONSHIP_SERVICE, CMIS_URL + "services/RelationshipService?wsdl"); parameter.put(SessionParameter.WEBSERVICES_REPOSITORY_SERVICE, CMIS_URL + "services/RepositoryService10?wsdl"); parameter.put(SessionParameter.WEBSERVICES_VERSIONING_SERVICE, CMIS_URL + "services/VersioningService?wsdl"); // Default repository id for in memory server is A1 parameter.put(SessionParameter.REPOSITORY_ID, "A1"); // create session final Session session = factory.createSession(parameter); assertTrue("Chemistry session should exists.", session != null); } @Test public void shouldSeeCmisTypesAsJcrTypes() throws Exception { NodeTypeManager manager = getSession().getWorkspace().getNodeTypeManager(); NodeTypeIterator it = manager.getNodeType("nt:file").getDeclaredSubtypes(); while (it.hasNext()) { NodeType nodeType = it.nextNodeType(); assertTrue(nodeType != null); } } @Test public void shouldAccessRootFolder() throws Exception { Node root = getSession().getNode("/cmis"); assertTrue(root != null); } @Test public void testRootFolderName() throws Exception { Node root = getSession().getNode("/cmis"); assertEquals("cmis", root.getName()); } @Test public void shouldAccessRepositoryInfo() throws Exception { Node repoInfo = getSession().getNode("/cmis/repositoryInfo"); // Different Chemistry versions return different things ... assertTrue(repoInfo.getProperty("cmis:productName").getString().contains("OpenCMIS")); assertTrue(repoInfo.getProperty("cmis:productName").getString().contains("InMemory")); assertEquals("Apache Chemistry", repoInfo.getProperty("cmis:vendorName").getString()); assertTrue(repoInfo.getProperty("cmis:productVersion").getString() != null); } @Test public void shouldAccessFolderByPath() throws Exception { Node root = getSession().getNode("/cmis"); assertTrue(root != null); Node node1 = getSession().getNode("/cmis/My_Folder-0-0"); assertTrue(node1 != null); Node node2 = getSession().getNode("/cmis/My_Folder-0-0/My_Folder-1-0"); assertTrue(node2 != null); Node node3 = getSession().getNode("/cmis/My_Folder-0-0/My_Folder-1-0/My_Folder-2-0"); assertTrue(node3 != null); } @Test public void shouldAccessDocumentPath() throws Exception { Node file = getSession().getNode("/cmis/My_Folder-0-0/My_Document-1-0"); assertTrue(file != null); } @Test public void shouldAccessBinaryContent() throws Exception { Node file = getSession().getNode("/cmis/My_Folder-0-0/My_Document-1-0"); Node cnt = file.getNode("jcr:content"); Property value = cnt.getProperty("jcr:data"); Binary bv = value.getValue().getBinary(); InputStream is = bv.getStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); int b = 0; while (b != -1) { b = is.read(); if (b != -1) { bout.write(b); } } byte[] content = bout.toByteArray(); String s = new String(content, 0, content.length); assertFalse("Content shouldn't be empty.", s.trim().isEmpty()); } // -----------------------------------------------------------------------/ // Folder cmis build-in properties // -----------------------------------------------------------------------/ @Test public void shouldAccessObjectIdPropertyForFolder() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0"); String objectId = node.getProperty("jcr:uuid").getString(); assertTrue(objectId != null); } @Test public void shouldAccessNamePropertyForFolder() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0"); String name = node.getName(); assertEquals("My_Folder-0-0", name); } @Test public void shouldAccessCreatedByPropertyForFolder() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0"); String name = node.getProperty("jcr:createdBy").getString(); assertEquals("unknown", name); } @Test public void shouldAccessCreationDatePropertyForFolder() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0"); Calendar date = node.getProperty("jcr:created").getDate(); assertTrue(date != null); } @Test public void shouldAccessModificationDatePropertyForFolder() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0"); Calendar date = node.getProperty("jcr:lastModified").getDate(); assertTrue(date != null); } // -----------------------------------------------------------------------/ // Document cmis build-in properties // -----------------------------------------------------------------------/ @Test public void shouldAccessObjectIdPropertyForDocument() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0/My_Document-1-0"); String objectId = node.getProperty("jcr:uuid").getString(); assertTrue(objectId != null); } @Test public void shouldAccessCreatedByPropertyForDocument() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0/My_Document-1-0"); String name = node.getProperty("jcr:createdBy").getString(); assertEquals("unknown", name); } @Test public void shouldAccessCreationDatePropertyForDocument() throws Exception { Node node = getSession().getNode("/cmis/My_Folder-0-0/My_Document-1-0"); Calendar date = node.getProperty("jcr:created").getDate(); assertTrue(date != null); } @Test public void shouldCreateFolderAndDocument() throws Exception { Node root = getSession().getNode("/cmis"); String name = "test" + System.currentTimeMillis(); Node node = root.addNode(name, "nt:folder"); assertTrue(name.equals(node.getName())); // node.setProperty("name", "test-name"); root = getSession().getNode("/cmis/" + name); Node node1 = root.addNode("test-1", "nt:file"); // System.out.println("Test: creating binary content"); byte[] content = "Hello World".getBytes(); ByteArrayInputStream bin = new ByteArrayInputStream(content); bin.reset(); // System.out.println("Test: creating content node"); Node contentNode = node1.addNode("jcr:content", "nt:resource"); Binary binary = session.getValueFactory().createBinary(bin); contentNode.setProperty("jcr:data", binary); contentNode.setProperty("jcr:lastModified", Calendar.getInstance()); getSession().save(); } @Test public void shouldModifyDocument() throws Exception { Node file = getSession().getNode("/cmis/My_Folder-0-0/My_Document-1-0"); PropertyIterator it = file.getProperties(); while (it.hasNext()) { Object val = it.nextProperty(); printMessage("property=>" + val); } file.setProperty("StringProp", "modeshape"); getSession().save(); } @Test public void shouldBeAbleToMoveExternalNodes() throws Exception { assertNotNull(session.getNode("/cmis/My_Folder-0-0/My_Document-1-0")); ((Workspace)session.getWorkspace()).move("/cmis/My_Folder-0-0/My_Document-1-0", "/cmis/My_Folder-0-1/My_Document-1-X"); Node file = session.getNode("/cmis/My_Folder-0-1/My_Document-1-X"); assertNotNull(file); assertNotNull(session.getNode("/cmis/My_Folder-0-0")); ((Workspace)session.getWorkspace()).move("/cmis/My_Folder-0-0", "/cmis/My_Folder-0-X"); Node folder = session.getNode("/cmis/My_Folder-0-X"); assertNotNull(folder); assertEquals("nt:folder", folder.getPrimaryNodeType().getName()); //undo the moves so that the original folder and document are unchaged (they are used by the other tests as well) ((Workspace) session.getWorkspace()).move("/cmis/My_Folder-0-1/My_Document-1-X", "/cmis/My_Folder-0-X/My_Document-1-0"); ((Workspace) session.getWorkspace()).move("/cmis/My_Folder-0-X", "/cmis/My_Folder-0-0"); } @Test public void shouldContainAccessList() throws Exception { AccessControlManager acm = session.getAccessControlManager(); AccessControlPolicy[] policies = acm.getPolicies("/cmis/My_Folder-0-0"); assertEquals(1, policies.length); } }
pleacu/modeshape
connectors/modeshape-connector-cmis/src/test/java/org/modeshape/connector/cmis/CmisConnectorIT.java
Java
apache-2.0
13,489
package ru.job4j.condition; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** *Class to test 'DummyBot.java'. * *@author Marek Vorp (mailto:[email protected]) *@version $Id$ *@since 23.07.2018 */ public class DummyBotTest { /** * Проверка ответа на вопрос "Привет, Бот.". */ @Test public void whenGreetBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Привет, Бот."), is("Привет, умник.") ); } /** * Проверка ответа на вопрос "Пока.". */ @Test public void whenByuBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Пока."), is("До скорой встречи.") ); } /** * Проверка ответа на любой вопрос кроме "Привет, Бот." и "Пока.". */ @Test public void whenUnknownBot() { DummyBot bot = new DummyBot(); assertThat( bot.answer("Сколько будет 2 + 2?"), is("Это ставит меня в тупик. Спросите другой вопрос.") ); } }
marekvorp777/mvorp
chapter_001/src/test/java/ru/job4j/condition/DummyBotTest.java
Java
apache-2.0
1,340
/* * Copyright 2012 GWTAO * * 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.gwtao.ui.util.client.card; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.Validate; import com.gwtao.ui.util.client.NavigationItem; import com.gwtao.ui.util.client.action.IAction; import com.gwtao.ui.util.client.displayable.DisplayableItem; import com.gwtao.ui.util.client.displayable.IDisplayableItem; /** * A set of displayable actions, organized in groups of cards * * @author Matt * */ public class Card implements ICard { private static final IDisplayableItem ROOT = new DisplayableItem("ROOT"); private IDisplayableItem display; private List<CardItem> list = new ArrayList<CardItem>(); public Card() { this(ROOT); } public Card(IDisplayableItem display) { Validate.notNull(display); this.display = display; } public void add(Card actions) { add(new CardItem(actions)); } public void add(CardItem item) { this.list.add(item); } public void add(IAction action) { add(new CardItem(action)); } public void add(NavigationItem token) { add(new CardItem(token)); } @Override public String getDisplayIcon() { return display.getDisplayIcon(); } @Override public String getDisplayText() { return display.getDisplayText(); } public String getDisplayTooltip() { return display.getDisplayTooltip(); } @Override public Iterator<CardItem> iterator() { return list.iterator(); } public boolean isEmpty() { return list.isEmpty(); } }
mhueb/gwtao
gwtao-client/src/main/java/com/gwtao/ui/util/client/card/Card.java
Java
apache-2.0
2,203
package fr.wseduc.cas.data; import fr.wseduc.cas.http.Request; public interface DataHandlerFactory { public DataHandler create(Request request); }
web-education/cas-server-async
src/main/java/fr/wseduc/cas/data/DataHandlerFactory.java
Java
apache-2.0
152
package rest; import beans.EntityBeanI; import java.util.List; import java.util.stream.Collectors; public class JsonResponse { private int code; private Object body; public static JsonResponse fail(int code, String reason) { JsonResponse jsonResponse = new JsonResponse(); jsonResponse.setCode(code); jsonResponse.setBody(reason); return jsonResponse; } public static JsonResponse success(Object body) { if (body instanceof EntityBeanI) { body = ((EntityBeanI) body).toMap(); } if (body instanceof List) { body = ((List) body).stream().map(obj -> { if (obj instanceof EntityBeanI) { return ((EntityBeanI) obj).toMap(); } return obj; }).collect(Collectors.toList()); } JsonResponse jsonResponse = new JsonResponse(); jsonResponse.setCode(RestCode.VALID); jsonResponse.setBody(body); return jsonResponse; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Object getBody() { return body; } public void setBody(Object body) { this.body = body; } @Override public String toString() { return "JsonResponse{" + "code=" + code + ", body=" + body + '}'; } }
CaoYouXin/serveV2
server/server/src/rest/JsonResponse.java
Java
apache-2.0
1,467
package com.kanomiya.steward.model.overlay.text; /** * @author Kanomiya * */ public interface ISelectableText extends IText { }
kanomiya/Steward
src/com/kanomiya/steward/model/overlay/text/ISelectableText.java
Java
apache-2.0
134
package dk.silverbullet.telemed.questionnaire.node.monica.realtime.communicators; import android.util.Base64; import android.util.Log; import com.google.gson.Gson; import dk.silverbullet.telemed.OpenTeleApplication; import dk.silverbullet.telemed.questionnaire.Questionnaire; import dk.silverbullet.telemed.questionnaire.node.monica.realtime.MilouSoapActions; import dk.silverbullet.telemed.rest.client.lowlevel.HttpHeaderBuilder; import dk.silverbullet.telemed.utils.Util; import org.apache.http.client.HttpResponseException; import org.apache.http.client.methods.HttpPost; import org.w3c.dom.Document; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; import java.io.UnsupportedEncodingException; public class OpenTeleCommunicator extends Communicator { public OpenTeleCommunicator(Questionnaire questionnaire, OpenTeleApplication openTeleApplication) { super(questionnaire, openTeleApplication); } @Override String getTag() { return Util.getTag(OpenTeleCommunicator.class); } @Override protected String getStringFromDocument(Document document, MilouSoapActions action) { try { OpenTeleRealtimeCTG registration = new OpenTeleRealtimeCTG(); registration.soapAction = action.getActionString(); registration.xml = Base64.encodeToString(documentToString(document).getBytes("UTF-8"), Base64.DEFAULT); return new Gson().toJson(registration); } catch (UnsupportedEncodingException e) { openTeleApplication.logException(e); Log.e(getTag(), "Could not serialize document for OpenTele", e); } openTeleApplication.logMessage("Could not serialize xml document"); return "<serializationError/>"; } @Override protected String getServerURL() { return Util.getServerUrl(questionnaire) + "rest/realTimeCTG/save"; } @Override protected void setHeaders(HttpPost post, MilouSoapActions action) { new HttpHeaderBuilder(post, questionnaire) .withAuthentication() .withAcceptTypeJSON() .withContentTypeJSON(); } @Override protected boolean shouldRetry(Exception exception) { HttpResponseException httpError = (exception instanceof HttpResponseException ? (HttpResponseException)exception : null); if (httpError != null && httpError.getStatusCode() == 429) { return false; } return true; } private String documentToString(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException e) { openTeleApplication.logException(e); Log.e(getTag(), "Could not serialize document for OpenTele", e); } openTeleApplication.logMessage("Could not serialize xml document"); return "<serializationError/>"; } }
silverbullet-dk/opentele-client-android
questionnaire-mainapp/src/dk/silverbullet/telemed/questionnaire/node/monica/realtime/communicators/OpenTeleCommunicator.java
Java
apache-2.0
3,450
/* * Copyright 2015 Schedo 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.ncode.android.apps.schedo.io; import com.ncode.android.apps.schedo.Config; import com.ncode.android.apps.schedo.provider.ScheduleContract; import com.ncode.android.apps.schedo.provider.ScheduleContract.Announcements; import com.ncode.android.apps.schedo.provider.ScheduleContract.SyncColumns; import com.ncode.android.apps.schedo.util.Lists; import com.ncode.android.apps.schedo.util.NetUtils; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import android.content.ContentProviderOperation; import android.content.Context; import android.text.TextUtils; import java.io.IOException; import java.util.ArrayList; import static com.ncode.android.apps.schedo.util.LogUtils.LOGE; import static com.ncode.android.apps.schedo.util.LogUtils.LOGI; import static com.ncode.android.apps.schedo.util.LogUtils.makeLogTag; public class AnnouncementsFetcher { private static final String TAG = makeLogTag(AnnouncementsFetcher.class); private Context mContext; public AnnouncementsFetcher(Context context) { mContext = context; } public ArrayList<ContentProviderOperation> fetchAndParse() throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Set up the HTTP transport and JSON factory HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new AndroidJsonFactory(); // Set up the main Google+ class Plus plus = new Plus.Builder(httpTransport, jsonFactory, null) .setApplicationName(NetUtils.getUserAgent(mContext)) .setGoogleClientRequestInitializer( new CommonGoogleClientRequestInitializer(Config.API_KEY)) .build(); ActivityFeed activities; try { activities = plus.activities().list(Config.ANNOUNCEMENTS_PLUS_ID, "public") .setMaxResults(100l) .execute(); if (activities == null || activities.getItems() == null) { throw new IOException("Activities list was null."); } } catch (IOException e) { LOGE(TAG, "Error fetching announcements", e); return batch; } LOGI(TAG, "Updating announcements data"); // Clear out existing announcements batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Announcements.CONTENT_URI)) .build()); StringBuilder sb = new StringBuilder(); for (Activity activity : activities.getItems()) { // Filter out anything not including the conference hashtag. sb.setLength(0); appendIfNotEmpty(sb, activity.getAnnotation()); if (activity.getObject() != null) { appendIfNotEmpty(sb, activity.getObject().getContent()); } if (!sb.toString().contains(Config.CONFERENCE_HASHTAG)) { continue; } // Insert announcement info batch.add(ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Announcements.ANNOUNCEMENT_ID, activity.getId()) .withValue(Announcements.ANNOUNCEMENT_DATE, activity.getUpdated().getValue()) .withValue(Announcements.ANNOUNCEMENT_TITLE, activity.getTitle()) .withValue(Announcements.ANNOUNCEMENT_ACTIVITY_JSON, activity.toPrettyString()) .withValue(Announcements.ANNOUNCEMENT_URL, activity.getUrl()) .build()); } return batch; } private static void appendIfNotEmpty(StringBuilder sb, String s) { if (!TextUtils.isEmpty(s)) { sb.append(s); } } }
ipalermo/schedo
android/src/main/java/com/ncode/android/apps/schedo/io/AnnouncementsFetcher.java
Java
apache-2.0
5,050
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sistemapagoimpuestos.Entity; import java.util.Date; /** * * @author mvissio */ public class EstadoSincronizacionCuentaCliente extends Entity{ private String nombreEstadoSincronizacionCuentaCliente; private String descripcionEstadoSincronizacionCuentaCliente; private Date fechaInhabilitacionEstadoSincronizacionCuentaCliente; public EstadoSincronizacionCuentaCliente() { } public EstadoSincronizacionCuentaCliente(String nombreEstadoSincronizacionCuentaCliente, String descripcionEstadoSincronizacionCuentaCliente, Date fechaInhabilitacionEstadoSincronizacionCuentaCliente) { this.nombreEstadoSincronizacionCuentaCliente = nombreEstadoSincronizacionCuentaCliente; this.descripcionEstadoSincronizacionCuentaCliente = descripcionEstadoSincronizacionCuentaCliente; this.fechaInhabilitacionEstadoSincronizacionCuentaCliente = fechaInhabilitacionEstadoSincronizacionCuentaCliente; } public String getNombreEstadoSincronizacionCuentaCliente() { return nombreEstadoSincronizacionCuentaCliente; } public void setNombreEstadoSincronizacionCuentaCliente(String nombreEstadoSincronizacionCuentaCliente) { this.nombreEstadoSincronizacionCuentaCliente = nombreEstadoSincronizacionCuentaCliente; } public String getDescripcionEstadoSincronizacionCuentaCliente() { return descripcionEstadoSincronizacionCuentaCliente; } public void setDescripcionEstadoSincronizacionCuentaCliente(String descripcionEstadoSincronizacionCuentaCliente) { this.descripcionEstadoSincronizacionCuentaCliente = descripcionEstadoSincronizacionCuentaCliente; } public Date getFechaInhabilitacionEstadoSincronizacionCuentaCliente() { return fechaInhabilitacionEstadoSincronizacionCuentaCliente; } public void setFechaInhabilitacionEstadoSincronizacionCuentaCliente(Date fechaInhabilitacionEstadoSincronizacionCuentaCliente) { this.fechaInhabilitacionEstadoSincronizacionCuentaCliente = fechaInhabilitacionEstadoSincronizacionCuentaCliente; } }
turing2017/Dise-o-2017
SistemaPagoImpuestos/src/sistemapagoimpuestos/Entity/EstadoSincronizacionCuentaCliente.java
Java
apache-2.0
2,256