hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
1de50b3897d4fbaf534875d712efc0adbc02fa53
2,025
/** * HospitalController.java * com.wjw.controller * Function: TODO add descript * * ver date author * ────────────────────────────────── * 2017年11月13日 lyj * * Copyright (c) 2017, TNT All Rights Reserved. */ package com.wjw.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ncme.springboot.footstone.constant.BusinessConst; import com.ncme.springboot.footstone.controller.Controller; import com.ncme.springboot.footstone.response.Record; import com.ncme.springboot.footstone.response.RtnBody; import com.ncme.springboot.footstone.util.StrKit; import com.wjw.service.HospitalService; /** * ClassName:HospitalController * Function: TODO 医院信息控制器 * Reason: TODO ADD REASON * * @author lyj * @version * @since version 1.0 * @Date 2017年11月13日 下午1:54:57 * * @see * */ @RestController @RequestMapping("/hospital") public class HospitalController extends Controller{ /** * hospitalService:TODO 医院服务 * * @since version 1.0 */ @Autowired HospitalService hospitalService; /** * getHospitalByArea:根据地区,关键字获取医院 * TODO(这里描述这个方法适用条件 – 可选) * * @param @param keyWord * @param @return * @return RtnBody * @throws * @since  version 1.0 */ @RequestMapping("/getHospitalByArea") public RtnBody getHospitalByArea(String keyWord){ String countyId = getPara("countyId"); if(StrKit.isBlank(countyId)){ return getRtnBody().code(BusinessConst.CODE_PARAM_EMPTY).message("params must be not empty."); } List<Record> list = hospitalService.getHospitalByArea(countyId,keyWord); //Record record = new Record(); //默认最后加一个其他选项,id定为 0 //record.put("hospitalid", 0); //record.put("hospitalName", "其它"); //list.add(record); return getRtnBody().code(BusinessConst.CODE_RESPONSE_SUCCESS).message("success").data(list); } }
23.823529
97
0.700741
6a5bdff6b265f6ad18070346a0e6d11062285922
5,122
package com.ibm.safr.we.data.dao; /* * Copyright Contributors to the GenevaERS Project. SPDX-License-Identifier: Apache-2.0 (c) Copyright IBM Corporation 2008. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.List; import com.ibm.safr.we.constants.SortType; import com.ibm.safr.we.data.DAOException; import com.ibm.safr.we.data.transfer.LRFieldTransfer; import com.ibm.safr.we.model.query.LogicalRecordFieldQueryBean; /** * This is an interface for all the methods related to LRField metadata * component. All these unimplemented methods are implemented in DB2LRFieldDAO. * */ public interface LRFieldDAO { /** *This method is used to retrieve all the LR fields belonging to the * specified logical record. * * @param environmentId * : The Id of the environment to which the Logical Record * belongs. * @param logicalRecordId * : The Id of the Logical Record to which the LR Fields belong. * @return A List of LRFieldTransfer * @throws DAOException */ List<LRFieldTransfer> getLRFields(Integer environmentId, Integer logicalRecordId) throws DAOException; /** * Retrieve the LRField with the specified ID. The key information may or * may not be retrieved depending on the boolean passed. * * @param environmentId * the ID of the environment the LRField belongs to * @param lrFieldId * the ID of the required LRField * @param retrieveKeyInfo * : A Boolean which specifies whether or not the information * about the primary key is to be retrieved. * @return an LRFieldTransfer * @throws DAOException */ LRFieldTransfer getLRField(Integer environmentId, Integer lrFieldId, Boolean retrieveKeyInfo) throws DAOException; /** * This method is called from the respective model class. This later calls * respective method either to create or update a LRField. * * @param lrFieldTransfer * : The transfer objects whose parameters are set with the * values received from the UI. * @return The transfer objects whose value are set according to the fields * of created or updated LR Field in LRFIELDATTR, LRFIELD * table. * @throws DAOException */ LRFieldTransfer persistLRField(LRFieldTransfer lrFieldTransfer) throws DAOException; /** * This method is called from the respective model class. This later calls * respective method either to create or update a list of LRFields related * to a particular Logical Records. * * @param lrFieldTransfer * : The list of transfer objects for LRField whose parameters * are set with the values received from the UI. * @return The list of transfer objects whose value are set according to the * fields of created or updated LR Field in LRFIELDATTR, * LRFIELD,table. * @throws DAOException */ List<LRFieldTransfer> persistLRField(List<LRFieldTransfer> lrFieldTransfer) throws DAOException; /** * This method is used to remove a LR Field with the specified Id. * * @param fieldIds * : The list of ids of the LR Fields which are to be removed. * @param environmentId * : The id of the environment in which the LR Fields exist. * @throws DAOException * It throws an exception if no LR Field is there with the * specified Id. */ void removeLRField(List<Integer> fieldIds, Integer environmentId) throws DAOException; List<LogicalRecordFieldQueryBean> queryAllLogicalRecordFields( SortType sortType, Integer environmentId, Integer logicalRecordId) throws DAOException; List<LogicalRecordFieldQueryBean> queryAllLogicalRecordFields( SortType sortType, Integer environmentId) throws DAOException; List<LogicalRecordFieldQueryBean> queryLRFields(SortType sortType, Integer environmentId) throws DAOException; /** * This method is used to retrieve all the LR fields in a particular * environment * * @param environmentId * : The Id of the environment * @param ids * : The list of Ids whose LR Fields are to be retrieved * @return A List of LRFieldTransfer * @throws DAOException */ List<LRFieldTransfer> getLRFields(Integer currentEnvironmentId, List<Integer> ids) throws DAOException; /** * @return the next LRField identifier */ Integer getNextKey(); public Integer getLRField(Integer environID, Integer sourceLRID, String fieldName); Integer getLookupLRField(Integer environID, int lookupid, String targetFieldName); }
34.608108
123
0.716712
6b51274d8a8ea5ec13cb37e5057632447b7d5fd4
721
package sg.four.serenity.callisto.tasks; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.Task; import net.serenitybdd.screenplay.actions.Open; import sg.four.serenity.callisto.ui.RateThisSitePage; import sg.four.serenity.callisto.ui.SitefinityDashboardPage; import static net.serenitybdd.screenplay.Tasks.instrumented; public class OpenSitefinityDashboardPage implements Task{ SitefinityDashboardPage page; @Override public <T extends Actor> void performAs(T actor) { actor.attemptsTo( Open.browserOn().the(page) ); } public static OpenSitefinityDashboardPage open() { return instrumented(OpenSitefinityDashboardPage.class); } }
28.84
63
0.761442
b0cf69b0ec5ade21604fa5f4b0066913681d4e86
2,887
/* * SendinBlue API * SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at https://github.com/orgs/sendinblue **Possible responses** | Code | Message | | :-------------: | ------------- | | 200 | OK. Successful Request | | 201 | OK. Successful Creation | | 202 | OK. Request accepted | | 204 | OK. Successful Update/Deletion | | 400 | Error. Bad Request | | 401 | Error. Authentication Needed | | 402 | Error. Not enough credit, plan upgrade needed | | 403 | Error. Permission denied | | 404 | Error. Object does not exist | | 405 | Error. Method not allowed | | 406 | Error. Not Acceptable | * * OpenAPI spec version: 3.0.0 * Contact: [email protected] * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package sendinblue; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import java.io.IOException; import okio.Buffer; import okio.BufferedSink; import okio.ForwardingSink; import okio.Okio; import okio.Sink; public class ProgressRequestBody extends RequestBody { public interface ProgressRequestListener { void onRequestProgress(long bytesWritten, long contentLength, boolean done); } private final RequestBody requestBody; private final ProgressRequestListener progressListener; public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { this.requestBody = requestBody; this.progressListener = progressListener; } @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() throws IOException { return requestBody.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink bufferedSink = Okio.buffer(sink(sink)); requestBody.writeTo(bufferedSink); bufferedSink.flush(); } private Sink sink(Sink sink) { return new ForwardingSink(sink) { long bytesWritten = 0L; long contentLength = 0L; @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); if (contentLength == 0) { contentLength = contentLength(); } bytesWritten += byteCount; progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); } }; } }
37.012821
841
0.662972
c675a3495b7458dca5e14471a0c7ea8e3ba08359
2,538
package controller; import java.io.IOException; import java.io.PrintWriter; import java.util.Hashtable; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import model.Order; /** * Servlet implementation class Home */ @WebServlet("/Formdata") public class Formdata extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Formdata() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("EUC-KR"); response.setContentType("text/html; charset=EUC-KR"); PrintWriter pw = response.getWriter(); //String commamd=request.getParameter("command"); String cardNum=request.getParameter("CreditCardNumber"); String repeatcardNum=request.getParameter("RepeatCreditCardNumber"); String cardType=request.getParameter("CreditCard"); String price=request.getParameter("PriceEach"); String initial=request.getParameter("MiddleIntial"); String itemNum=request.getParameter("ItemNumber"); String address=request.getParameter("ShippingAddress"); String firstName=request.getParameter("FirstName"); String description = request.getParameter("Desription"); String lastName=request.getParameter("LastName"); /*if(cardNum!=repeatcardNum) { pw.println("not equals"); RequestDispatcher dispatcher= request.getRequestDispatcher("/view/form.jsp"); dispatcher.forward(request,response); }*/ Order order= new Order(cardNum, cardType, price, initial, itemNum, address, firstName, lastName, description); Hashtable<String,Order> ht = new Hashtable<>(); ht.put("1", order); request.setAttribute("result", ht);//기존의 자바 코드를 사용하기 위하여생성 request.setAttribute("b",order);//jsp expression로 코드를 사용하기 위하여생성 String page=null; page="/view/order.jsp"; RequestDispatcher dispatcher= request.getRequestDispatcher(page); dispatcher.forward(request,response); } }
32.538462
119
0.720646
1d38796f064519493ad24ae4a0aa4b9dd06e8f00
1,994
package ro.cs.pub.ro.practicaltest02; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class PracticalTest02SecondaryActivity extends Activity { Button ok_button, cancel_button; TextView showMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_practical_test02_secondary); ok_button = (Button) findViewById(R.id.button_ok); cancel_button = (Button) findViewById(R.id.button_cancel); showMessage = (TextView) findViewById(R.id.showCheck); Intent i = getIntent(); if(i != null){ String name_checks = i.getStringExtra("CheckString"); if(name_checks != null){ showMessage.setText(name_checks); } } ok_button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub setResult(RESULT_OK, new Intent()); finish(); } }); cancel_button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub setResult(RESULT_CANCELED, new Intent()); finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.practical_test02_secondary, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
25.564103
74
0.738215
599ac4b41d48433dd644d3ad6fc0716aa2f6c02e
315
/* * Created on Sep 23, 2004 */ package cyrille.lang.reflect; /** * @author <a href="mailto:[email protected]">Cyrille Le Clerc </a> */ public interface Foo { public String doJob(String name); public String doAnotherJob(String name); public String doaThirdJob(String name); }
19.6875
69
0.644444
55c5d3e1258da93d06c6e84acd4855d988543c80
218
package test.connect.myapplication.api; import retrofit2.Call; import retrofit2.http.GET; import test.connect.myapplication.model.Post; public interface PostApi{ @GET("posts/1") Call<Post> getFirstPost(); }
18.166667
45
0.756881
82dcd3adb44f8235d3a280c58e32eb099dd6d62b
2,438
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("14") class Record_4188 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 4188: FirstName is Nellie") void FirstNameOfRecord4188() { assertEquals("Nellie", customers.get(4187).getFirstName()); } @Test @DisplayName("Record 4188: LastName is Goyal") void LastNameOfRecord4188() { assertEquals("Goyal", customers.get(4187).getLastName()); } @Test @DisplayName("Record 4188: Company is Hoag, Hallack W Esq") void CompanyOfRecord4188() { assertEquals("Hoag, Hallack W Esq", customers.get(4187).getCompany()); } @Test @DisplayName("Record 4188: Address is 5900 Hubbard Dr") void AddressOfRecord4188() { assertEquals("5900 Hubbard Dr", customers.get(4187).getAddress()); } @Test @DisplayName("Record 4188: City is Rockville") void CityOfRecord4188() { assertEquals("Rockville", customers.get(4187).getCity()); } @Test @DisplayName("Record 4188: County is Montgomery") void CountyOfRecord4188() { assertEquals("Montgomery", customers.get(4187).getCounty()); } @Test @DisplayName("Record 4188: State is MD") void StateOfRecord4188() { assertEquals("MD", customers.get(4187).getState()); } @Test @DisplayName("Record 4188: ZIP is 20852") void ZIPOfRecord4188() { assertEquals("20852", customers.get(4187).getZIP()); } @Test @DisplayName("Record 4188: Phone is 301-881-8618") void PhoneOfRecord4188() { assertEquals("301-881-8618", customers.get(4187).getPhone()); } @Test @DisplayName("Record 4188: Fax is 301-881-7066") void FaxOfRecord4188() { assertEquals("301-881-7066", customers.get(4187).getFax()); } @Test @DisplayName("Record 4188: Email is [email protected]") void EmailOfRecord4188() { assertEquals("[email protected]", customers.get(4187).getEmail()); } @Test @DisplayName("Record 4188: Web is http://www.nelliegoyal.com") void WebOfRecord4188() { assertEquals("http://www.nelliegoyal.com", customers.get(4187).getWeb()); } }
25.395833
75
0.731747
88c6e8dd4db291e5c368c77183a60917202ab5d5
6,332
package code.ponfee.commons.math; import javax.validation.constraints.Max; import javax.validation.constraints.Min; /** * 数学算术 * 取模:Modulo Operation * * @author Ponfee */ public class Maths { /** * 以2为底n的对数 * * @param n the value * @return a value of log(n)/log(2) */ public static strictfp double log2(double n) { return log(n, 2); } /** * 求以base为底n的对数 * {@link java.lang.Math#log10(double) } 求以10为底n的对数(lg) * {@link java.lang.Math#log(double) } 以e为底n的对数(自然对数,ln) * {@link java.lang.Math#log1p(double) } 以e为底n+1的对数 * * @param n a value * @param base 底数 * @return a double of logarithm */ public static strictfp double log(double n, double base) { return Math.log(n) / Math.log(base); } /** * rotate shift left,循环左移位操作:0<=n<=32 * * @param x the value * @param n shift bit len * @return a number of rotate left result */ public static int rotateLeft(int x, @Min(0) @Max(32) int n) { return (x << n) | (x >>> (32 - n)); } /** * Returns a long value of bit conut mask * calculate the bit counts mask long value * a: (1 << bits) - 1 * b: -1L ^ (-1L << bits) * c: Long.MAX_VALUE >>> (63 - bits) * * @param bits the bit count * @return a long value */ public static long bitsMask(int bits) { return (1L << bits) - 1; } /** * Returns a long value for {@code base}<sup>{@code exponent}</sup>. * * @param base the base * @param exponent the exponent * @return a long value for {@code base}<sup>{@code exponent}</sup>. */ public static long pow(@Min(1) long base, @Min(0) int exponent) { if (exponent == 0) { return 1; } long result = base; while (--exponent > 0) { result *= base; } return result; } public static int abs(int a) { // Integer.MIN_VALUE & 0x7FFFFFFF = 0 return (a == Integer.MIN_VALUE) ? Integer.MAX_VALUE : (a < 0) ? -a : a; } public static long abs(long a) { return (a == Long.MIN_VALUE) ? Long.MAX_VALUE : (a < 0) ? -a : a; } /** * Returns square root of specified double value<p> * Use binary search method * * @param value the value * @return square root */ public static strictfp double sqrtBinary(double value) { if (value < 0.0D) { return Double.NaN; } if (value == 0.0D || value == 1.0D) { return value; } double start, end, square, r; if (value > 1.0D) { start = 1.0D; end = value; } else { start = value; end = 1.0D; } while (!isBorderline(r = start + (end - start) / 2, start, end) && (square = r * r) != value) { if (square > value) { end = r; // lower } else { start = r; // upper } } return r; // cannot find a more rounded value } public static boolean isBorderline(double value, double start, double end) { return value == start || value == end; } /** * Returns square root of specified double value<p> * Use newton iteration method: X(n+1)=[X(n)+p/Xn]/2 * * @param value the value * @return square root */ public static strictfp double sqrtNewton(double value) { if (value < 0) { return Double.NaN; } if (value == 0.0D || value == 1.0D) { return value; } double r = 1.0D; while (r != (r = (r + value / r) / 2)) { // do nothing } return r; } public static boolean isBorderline(int value, int start, int end) { return value == start || value == end; } public static boolean isBorderline(long value, long start, long end) { return value == start || value == end; } // ------------------------------------------------------------------------int plus/minus public static int plus(int a, int b) { if (a > 0 && b > 0) { return Integer.MAX_VALUE - b < a ? Integer.MAX_VALUE : a + b; } else if (a < 0 && b < 0) { return Integer.MIN_VALUE - b > a ? Integer.MIN_VALUE : a + b; } else { return a + b; } } public static int minus(int a, int b) { if (a > 0 && b < 0) { return Integer.MAX_VALUE + b < a ? Integer.MAX_VALUE : a - b; } else if (a < 0 && b > 0) { return Integer.MIN_VALUE + b > a ? Integer.MIN_VALUE : a - b; } else { return a - b; } } // ------------------------------------------------------------------------long plus/minus public static long plus(long a, long b) { if (a > 0 && b > 0) { return Long.MAX_VALUE - b < a ? Long.MAX_VALUE : a + b; } else if (a < 0 && b < 0) { return Long.MIN_VALUE - b > a ? Long.MIN_VALUE : a + b; } else { return a + b; } } public static long minus(long a, long b) { if (a > 0 && b < 0) { return Long.MAX_VALUE + b < a ? Long.MAX_VALUE : a - b; } else if (a < 0 && b > 0) { return Long.MIN_VALUE + b > a ? Long.MIN_VALUE : a - b; } else { return a - b; } } /** * Returns the greatest common divisor * * @param a the first number * @param b the second number * @return gcd */ public static int gcd(int a, int b) { if (a < 0 || b < 0) { throw new ArithmeticException(); } if (a == 0 || b == 0) { return Math.abs(a - b); } for (int c; (c = a % b) != 0;) { a = b; b = c; } return b; } /** * Returns the greatest common divisor in array * * @param array the int array * @return gcd */ public static int gcd(int[] array) { int result = array[0]; for (int i = 1; i < array.length; i++) { result = gcd(result, array[i]); } return result; } }
26.383333
103
0.472521
55c73cdbe2f075a2303994e2046c1f8275016570
44,344
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.file.remote.gateway; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.file.FileHeaders; import org.springframework.integration.file.filters.AbstractSimplePatternFileListFilter; import org.springframework.integration.file.remote.AbstractFileInfo; import org.springframework.integration.file.remote.RemoteFileTemplate; import org.springframework.integration.file.remote.handler.FileTransferringMessageHandler; import org.springframework.integration.file.remote.session.Session; import org.springframework.integration.file.remote.session.SessionFactory; import org.springframework.integration.file.support.FileExistsMode; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; /** * @author Gary Russell * @author Liu Jiong * @author Artem Bilan * * @since 2.1 */ @SuppressWarnings("rawtypes") public class RemoteFileOutboundGatewayTests { private static final SpelExpressionParser PARSER = new SpelExpressionParser(); private final String tmpDir = System.getProperty("java.io.tmpdir"); @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @Test public void testBad() { SessionFactory sessionFactory = mock(SessionFactory.class); assertThatIllegalArgumentException() .isThrownBy(() -> new TestRemoteFileOutboundGateway(sessionFactory, "bad", "payload")); } @Test public void testBadFilterGet() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setFilter(new TestPatternFilter("")); assertThatIllegalArgumentException() .isThrownBy(gw::afterPropertiesSet) .withMessageStartingWith("Filters are not supported"); } @Test public void testBadFilterRm() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "rm", "payload"); gw.setFilter(new TestPatternFilter("")); assertThatIllegalArgumentException() .isThrownBy(gw::afterPropertiesSet) .withMessageStartingWith("Filters are not supported"); } @Test public void testLs() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/x/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<TestLsEntry>> out = (MessageBuilder<List<TestLsEntry>>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(2); assertThat(out.getPayload().get(0)).isSameAs(files[1]); // sort by default assertThat(out.getPayload().get(1)).isSameAs(files[0]); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } @Test public void testMGetWild() { testMGetWildGuts("f1", "f2"); } @Test public void testMGetWildFullPath() { testMGetWildGuts("testremote/f1", "testremote/f2"); } private void testMGetWildGuts(final String path1, final String path2) { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mget", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); gw.afterPropertiesSet(); new File(this.tmpDir + "/f1").delete(); new File(this.tmpDir + "/f2").delete(); when(sessionFactory.getSession()).thenReturn(new TestSession() { int n; @Override public void read(String source, OutputStream outputStream) throws IOException { if (n++ == 0) { assertThat(source).isEqualTo("testremote/f1"); } else { assertThat(source).isEqualTo("testremote/f2"); } outputStream.write("testData".getBytes()); } @Override public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry(path1.replaceFirst("testremote/", ""), 123, false, false, 1234, "-r--r--r--"), new TestLsEntry(path2.replaceFirst("testremote/", ""), 123, false, false, 1234, "-r--r--r--") }; } }); @SuppressWarnings("unchecked") MessageBuilder<List<File>> out = (MessageBuilder<List<File>>) gw .handleRequestMessage(new GenericMessage<>("testremote/*")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(2); assertThat(out.getPayload().get(0).getName()).isEqualTo("f1"); assertThat(out.getPayload().get(1).getName()).isEqualTo("f2"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/"); } @Test public void testMGetSingle() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mget", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); gw.afterPropertiesSet(); new File(this.tmpDir + "/f1").delete(); when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override public void read(String source, OutputStream outputStream) throws IOException { outputStream.write("testData".getBytes()); } @Override public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 123, false, false, 1234, "-r--r--r--") }; } }); @SuppressWarnings("unchecked") MessageBuilder<List<File>> out = (MessageBuilder<List<File>>) gw .handleRequestMessage(new GenericMessage<>("testremote/f1")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(1); assertThat(out.getPayload().get(0).getName()).isEqualTo("f1"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/"); } @Test(expected = MessagingException.class) public void testMGetEmpty() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mget", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); gw.setOptions(" -x "); gw.afterPropertiesSet(); new File(this.tmpDir + "/f1").delete(); new File(this.tmpDir + "/f2").delete(); when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override public void read(String source, OutputStream outputStream) throws IOException { outputStream.write("testData".getBytes()); } }); gw.handleRequestMessage(new GenericMessage<>("testremote/*")); } @Test public void testMove() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mv", "payload"); gw.afterPropertiesSet(); Session<?> session = mock(Session.class); final AtomicReference<String> args = new AtomicReference<>(); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); args.set((String) arguments[0] + arguments[1]); return null; }).when(session).rename(anyString(), anyString()); when(sessionFactory.getSession()).thenReturn(session); Message<String> requestMessage = MessageBuilder.withPayload("foo") .setHeader(FileHeaders.RENAME_TO, "bar") .build(); MessageBuilder<?> out = (MessageBuilder<?>) gw.handleRequestMessage(requestMessage); assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); assertThat(args.get()).isEqualTo("foobar"); assertThat(out.getPayload()).isEqualTo(Boolean.TRUE); } @Test public void testMoveWithExpression() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mv", "payload"); gw.setRenameExpression(PARSER.parseExpression("payload.substring(1)")); gw.afterPropertiesSet(); Session<?> session = mock(Session.class); final AtomicReference<String> args = new AtomicReference<>(); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); args.set((String) arguments[0] + arguments[1]); return null; }).when(session).rename(anyString(), anyString()); when(sessionFactory.getSession()).thenReturn(session); MessageBuilder<?> out = (MessageBuilder<?>) gw.handleRequestMessage(new GenericMessage<>("foo")); assertThat(out.getHeaders().get(FileHeaders.RENAME_TO)).isEqualTo("oo"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); assertThat(args.get()).isEqualTo("foooo"); assertThat(out.getPayload()).isEqualTo(Boolean.TRUE); } @Test public void testMoveWithMkDirs() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mv", "payload"); gw.setRenameExpression(PARSER.parseExpression("'foo/bar/baz'")); gw.afterPropertiesSet(); Session<?> session = mock(Session.class); final AtomicReference<String> args = new AtomicReference<>(); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); args.set((String) arguments[0] + arguments[1]); return null; }).when(session).rename(anyString(), anyString()); final List<String> madeDirs = new ArrayList<>(); doAnswer(invocation -> { madeDirs.add(invocation.getArgument(0)); return true; }).when(session).mkdir(anyString()); when(sessionFactory.getSession()).thenReturn(session); Message<String> requestMessage = MessageBuilder.withPayload("foo") .setHeader(FileHeaders.RENAME_TO, "bar") .build(); MessageBuilder<?> out = (MessageBuilder<?>) gw.handleRequestMessage(requestMessage); assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); assertThat(args.get()).isEqualTo("foofoo/bar/baz"); assertThat(out.getPayload()).isEqualTo(Boolean.TRUE); assertThat(madeDirs.size()).isEqualTo(2); assertThat(madeDirs.get(0)).isEqualTo("foo"); assertThat(madeDirs.get(1)).isEqualTo("foo/bar"); } public TestLsEntry[] fileList() { TestLsEntry[] files = new TestLsEntry[6]; files[0] = new TestLsEntry("f2", 123, false, false, 1234, "-r--r--r--"); files[1] = new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--"); files[2] = new TestLsEntry("f3", 12345, true, false, 123456, "drw-r--r--"); files[3] = new TestLsEntry("f4", 12346, false, true, 1234567, "lrw-r--r--"); files[4] = new TestLsEntry(".f5", 12347, false, false, 12345678, "-rw-r--r--"); files[5] = new TestLsEntry(".f6", 12347, true, false, 123456789, "drw-r--r--"); return files; } @Test public void testLs_f() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-f"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/x/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<TestLsEntry>> out = (MessageBuilder<List<TestLsEntry>>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(2); assertThat(out.getPayload().get(0)).isSameAs(files[0]); assertThat(out.getPayload().get(1)).isSameAs(files[1]); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } public TestLsEntry[] level1List() { return new TestLsEntry[] { new TestLsEntry("f1", 123, false, false, 1234, "-r--r--r--"), new TestLsEntry("d1", 0, true, false, 12345, "drw-r--r--"), new TestLsEntry("f2", 12345, false, false, 123456, "-rw-r--r--") }; } public TestLsEntry[] level2List() { return new TestLsEntry[] { new TestLsEntry("d2", 0, true, false, 12345, "drw-r--r--"), new TestLsEntry("f3", 12345, false, false, 123456, "-rw-r--r--") }; } public TestLsEntry[] level3List() { return new TestLsEntry[] { new TestLsEntry("f4", 12345, false, false, 123456, "-rw-r--r--") }; } @Test public void testLs_f_R() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-f -R"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] level1 = level1List(); TestLsEntry[] level2 = level2List(); TestLsEntry[] level3 = level3List(); when(session.list("testremote/x/")).thenReturn(level1); when(session.list("testremote/x/d1/")).thenReturn(level2); when(session.list("testremote/x/d1/d2/")).thenReturn(level3); @SuppressWarnings("unchecked") MessageBuilder<List<TestLsEntry>> out = (MessageBuilder<List<TestLsEntry>>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(4); assertThat(out.getPayload().get(0).getFilename()).isEqualTo("f1"); assertThat(out.getPayload().get(1).getFilename()).isEqualTo("d1/d2/f4"); assertThat(out.getPayload().get(2).getFilename()).isEqualTo("d1/f3"); assertThat(out.getPayload().get(3).getFilename()).isEqualTo("f2"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } @Test public void testLs_f_R_dirs() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-f -R -dirs"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] level1 = level1List(); TestLsEntry[] level2 = level2List(); TestLsEntry[] level3 = level3List(); when(session.list("testremote/x/")).thenReturn(level1); when(session.list("testremote/x/d1/")).thenReturn(level2); when(session.list("testremote/x/d1/d2/")).thenReturn(level3); @SuppressWarnings("unchecked") MessageBuilder<List<TestLsEntry>> out = (MessageBuilder<List<TestLsEntry>>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(5); assertThat(out.getPayload().get(0).getFilename()).isEqualTo("f1"); assertThat(out.getPayload().get(1).getFilename()).isEqualTo("d1"); assertThat(out.getPayload().get(2).getFilename()).isEqualTo("d1/d2"); assertThat(out.getPayload().get(3).getFilename()).isEqualTo("d1/f3"); assertThat(out.getPayload().get(4).getFilename()).isEqualTo("f2"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } @Test public void testLs_None() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = new TestLsEntry[0]; when(session.list("testremote/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<TestLsEntry>> out = (MessageBuilder<List<TestLsEntry>>) gw .handleRequestMessage(new GenericMessage<>("testremote")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(0); } @Test public void testLs_1() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-1"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<String>> out = (MessageBuilder<List<String>>) gw .handleRequestMessage(new GenericMessage<>("testremote")); assertThat(out).isNotNull(); assertThat(out.getPayload()).hasSize(2); assertThat(out.getPayload().get(0)).isEqualTo("f1"); assertThat(out.getPayload().get(1)).isEqualTo("f2"); } @Test public void testLs_1_f() throws Exception { //no sort SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-1 -f"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<String>> out = (MessageBuilder<List<String>>) gw .handleRequestMessage(new GenericMessage<>("testremote")); assertThat(out.getPayload()).hasSize(2); assertThat(out.getPayload().get(0)).isEqualTo("f2"); assertThat(out.getPayload().get(1)).isEqualTo("f1"); } @Test public void testLs_1_dirs() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-1 -dirs"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<String>> out = (MessageBuilder<List<String>>) gw .handleRequestMessage(new GenericMessage<>("testremote")); assertThat(out.getPayload()).hasSize(3); assertThat(out.getPayload().get(0)).isEqualTo("f1"); assertThat(out.getPayload().get(1)).isEqualTo("f2"); assertThat(out.getPayload().get(2)).isEqualTo("f3"); } @Test public void testLs_1_dirs_links() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-1 -dirs -links"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<String>> out = (MessageBuilder<List<String>>) gw .handleRequestMessage(new GenericMessage<>("testremote")); assertThat(out.getPayload()).hasSize(4); assertThat(out.getPayload().get(0)).isEqualTo("f1"); assertThat(out.getPayload().get(1)).isEqualTo("f2"); assertThat(out.getPayload().get(2)).isEqualTo("f3"); assertThat(out.getPayload().get(3)).isEqualTo("f4"); } @Test public void testLs_1_a_f_dirs_links() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-1 -a -f -dirs -links"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<String>> out = (MessageBuilder<List<String>>) gw .handleRequestMessage(new GenericMessage<>("testremote")); assertThat(out.getPayload()).hasSize(6); assertThat(out.getPayload().get(0)).isEqualTo("f2"); assertThat(out.getPayload().get(1)).isEqualTo("f1"); assertThat(out.getPayload().get(2)).isEqualTo("f3"); assertThat(out.getPayload().get(3)).isEqualTo("f4"); assertThat(out.getPayload().get(4)).isEqualTo(".f5"); assertThat(out.getPayload().get(5)).isEqualTo(".f6"); } @Test public void testLs_1_a_f_dirs_links_filtered() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "ls", "payload"); gw.setOptions("-1 -a -f -dirs -links"); gw.setFilter(new TestPatternFilter("*4")); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); TestLsEntry[] files = fileList(); when(session.list("testremote/")).thenReturn(files); @SuppressWarnings("unchecked") MessageBuilder<List<String>> out = (MessageBuilder<List<String>>) gw .handleRequestMessage(new GenericMessage<>("testremote")); assertThat(out.getPayload()).hasSize(1); assertThat(out.getPayload().get(0)).isEqualTo("f4"); } @Test public void testGet() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); gw.afterPropertiesSet(); new File(this.tmpDir + "/f1").delete(); when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @Override public void read(String source, OutputStream outputStream) throws IOException { outputStream.write("testfile".getBytes()); } }); @SuppressWarnings("unchecked") MessageBuilder<File> out = (MessageBuilder<File>) gw.handleRequestMessage(new GenericMessage<>("f1")); File outFile = new File(this.tmpDir + "/f1"); assertThat(out.getPayload()).isEqualTo(outFile); assertThat(outFile.exists()).isTrue(); outFile.delete(); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isNull(); assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("f1"); } @SuppressWarnings("unchecked") @Test public void testGetExists() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); gw.afterPropertiesSet(); File outFile = new File(this.tmpDir + "/f1"); FileOutputStream fos = new FileOutputStream(outFile); fos.write("foo".getBytes()); fos.close(); when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @Override public void read(String source, OutputStream outputStream) throws IOException { outputStream.write("testfile".getBytes()); } }); // default (null) MessageBuilder<File> out; assertThatExceptionOfType(MessageHandlingException.class) .isThrownBy(() -> gw.handleRequestMessage(new GenericMessage<>("f1"))) .withMessageContaining("already exists"); gw.setFileExistsMode(FileExistsMode.FAIL); assertThatExceptionOfType(MessageHandlingException.class) .isThrownBy(() -> gw.handleRequestMessage(new GenericMessage<>("f1"))) .withMessageContaining("already exists"); gw.setFileExistsMode(FileExistsMode.IGNORE); out = (MessageBuilder<File>) gw.handleRequestMessage(new GenericMessage<>("f1")); assertThat(out.getPayload()).isEqualTo(outFile); assertContents("foo", outFile); gw.setFileExistsMode(FileExistsMode.APPEND); out = (MessageBuilder<File>) gw.handleRequestMessage(new GenericMessage<>("f1")); assertThat(out.getPayload()).isEqualTo(outFile); assertContents("footestfile", outFile); gw.setFileExistsMode(FileExistsMode.REPLACE); out = (MessageBuilder<File>) gw.handleRequestMessage(new GenericMessage<>("f1")); assertThat(out.getPayload()).isEqualTo(outFile); assertContents("testfile", outFile); outFile.delete(); } private void assertContents(String expected, File outFile) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(outFile)); assertThat(reader.readLine()).isEqualTo(expected); reader.close(); } @Test public void testGetTempFileDelete() { @SuppressWarnings("unchecked") SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); gw.afterPropertiesSet(); new File(this.tmpDir + "/f1").delete(); when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @Override public void read(String source, OutputStream outputStream) { throw new RuntimeException("test remove .writing"); } }); assertThatExceptionOfType(MessagingException.class) .isThrownBy(() -> gw.handleRequestMessage(new GenericMessage<>("f1"))) .withCauseInstanceOf(RuntimeException.class) .withMessageContaining("test remove .writing"); RemoteFileTemplate<?> template = new RemoteFileTemplate<>(sessionFactory); File outFile = new File(this.tmpDir + "/f1" + template.getTemporaryFileSuffix()); assertThat(outFile.exists()).isFalse(); } @Test public void testGet_P() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); gw.setOptions("-P"); gw.afterPropertiesSet(); new File(this.tmpDir + "/f1").delete(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); final Date modified = new Date(cal.getTime().getTime() / 1000 * 1000); when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, modified.getTime(), "-rw-r--r--") }; } @Override public void read(String source, OutputStream outputStream) throws IOException { outputStream.write("testfile".getBytes()); } }); @SuppressWarnings("unchecked") MessageBuilder<File> out = (MessageBuilder<File>) gw.handleRequestMessage(new GenericMessage<>("x/f1")); File outFile = new File(this.tmpDir + "/f1"); assertThat(out.getPayload()).isEqualTo(outFile); assertThat(outFile.exists()).isTrue(); assertThat(outFile.lastModified()).isEqualTo(modified.getTime()); outFile.delete(); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("x/"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("f1"); } @Test public void testGet_create_dir() { new File(this.tmpDir + "/x/f1").delete(); new File(this.tmpDir + "/x").delete(); SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setLocalDirectory(new File(this.tmpDir + "/x")); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @Override public void read(String source, OutputStream outputStream) throws IOException { outputStream.write("testfile".getBytes()); } }); gw.handleRequestMessage(new GenericMessage<>("f1")); File out = new File(this.tmpDir + "/x/f1"); assertThat(out.exists()).isTrue(); out.delete(); } @Test public void testRm() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); Session session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "rm", "payload"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); when(session.remove("testremote/x/f1")).thenReturn(Boolean.TRUE); @SuppressWarnings("unchecked") MessageBuilder<Boolean> out = (MessageBuilder<Boolean>) gw .handleRequestMessage(new GenericMessage<>("testremote/x/f1")); assertThat(out.getPayload()).isTrue(); verify(session).remove("testremote/x/f1"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("f1"); } @Test public void testPut() throws Exception { @SuppressWarnings("unchecked") SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class); @SuppressWarnings("unchecked") Session<TestLsEntry> session = mock(Session.class); RemoteFileTemplate<TestLsEntry> template = new RemoteFileTemplate<TestLsEntry>(sessionFactory) { @Override public boolean exists(String path) { return false; } }; template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload"); FileTransferringMessageHandler<TestLsEntry> handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpressionString("'foo/'"); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); Message<String> requestMessage = MessageBuilder.withPayload("hello") .setHeader(FileHeaders.FILENAME, "bar.txt") .build(); String path = (String) gw.handleRequestMessage(requestMessage); assertThat(path).isEqualTo("foo/bar.txt"); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(session).write(any(InputStream.class), captor.capture()); assertThat(captor.getValue()).isEqualTo("foo/bar.txt.writing"); verify(session).rename("foo/bar.txt.writing", "foo/bar.txt"); } @Test public void testPutExists() throws Exception { @SuppressWarnings("unchecked") SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class); @SuppressWarnings("unchecked") Session<TestLsEntry> session = mock(Session.class); willReturn(Boolean.TRUE) .given(session) .exists(anyString()); RemoteFileTemplate<TestLsEntry> template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload"); FileTransferringMessageHandler<TestLsEntry> handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression("foo/")); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); Message<String> requestMessage = MessageBuilder.withPayload("hello") .setHeader(FileHeaders.FILENAME, "bar.txt") .build(); // default (null) == REPLACE String path = (String) gw.handleRequestMessage(requestMessage); assertThat(path).isEqualTo("foo/bar.txt"); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(session).write(any(InputStream.class), captor.capture()); assertThat(captor.getValue()).isEqualTo("foo/bar.txt.writing"); verify(session).rename("foo/bar.txt.writing", "foo/bar.txt"); gw.setFileExistsMode(FileExistsMode.FAIL); assertThatExceptionOfType(MessageDeliveryException.class) .isThrownBy(() -> gw.handleRequestMessage(requestMessage)) .withMessageContaining("The destination file already exists"); gw.setFileExistsMode(FileExistsMode.REPLACE); path = (String) gw.handleRequestMessage(requestMessage); assertThat(path).isEqualTo("foo/bar.txt"); captor = ArgumentCaptor.forClass(String.class); verify(session, times(2)).write(any(InputStream.class), captor.capture()); assertThat(captor.getValue()).isEqualTo("foo/bar.txt.writing"); verify(session, times(2)).rename("foo/bar.txt.writing", "foo/bar.txt"); gw.setFileExistsMode(FileExistsMode.APPEND); path = (String) gw.handleRequestMessage(requestMessage); assertThat(path).isEqualTo("foo/bar.txt"); captor = ArgumentCaptor.forClass(String.class); verify(session).append(any(InputStream.class), captor.capture()); assertThat(captor.getValue()).isEqualTo("foo/bar.txt"); gw.setFileExistsMode(FileExistsMode.IGNORE); path = (String) gw.handleRequestMessage(requestMessage); assertThat(path).isEqualTo("foo/bar.txt"); // no more writes/appends verify(session, times(2)).write(any(InputStream.class), anyString()); verify(session, times(1)).append(any(InputStream.class), anyString()); } @Test @SuppressWarnings("unchecked") public void testMput() throws Exception { SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class); Session<TestLsEntry> session = mock(Session.class); RemoteFileTemplate<TestLsEntry> template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "mput", "payload"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); final AtomicReference<String> written = new AtomicReference<>(); doAnswer(invocation -> { written.set(invocation.getArgument(1)); return null; }).when(session).write(any(InputStream.class), anyString()); tempFolder.newFile("baz.txt"); tempFolder.newFile("qux.txt"); Message<File> requestMessage = MessageBuilder.withPayload(tempFolder.getRoot()) .build(); List<String> out = (List<String>) gw.handleRequestMessage(requestMessage); assertThat(out).hasSize(2); assertThat(out.get(0)).isNotEqualTo(out.get(1)); assertThat(out.get(0)).isIn("foo/baz.txt", "foo/qux.txt"); assertThat(out.get(1)).isIn("foo/baz.txt", "foo/qux.txt"); } @Test @SuppressWarnings("unchecked") public void testMputRecursive() throws Exception { SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class); Session<TestLsEntry> session = mock(Session.class); RemoteFileTemplate<TestLsEntry> template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "mput", null); gw.setOptions("-R"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); final AtomicReference<String> written = new AtomicReference<>(); doAnswer(invocation -> { written.set(invocation.getArgument(1)); return null; }).when(session).write(any(InputStream.class), anyString()); tempFolder.newFile("baz.txt"); tempFolder.newFile("qux.txt"); File dir1 = tempFolder.newFolder(); File file3 = File.createTempFile("foo", ".txt", dir1); Message<File> requestMessage = MessageBuilder.withPayload(tempFolder.getRoot()) .build(); List<String> out = (List<String>) gw.handleRequestMessage(requestMessage); assertThat(out).hasSize(3); assertThat(out.get(0)).isNotEqualTo(out.get(1)); assertThat(out.get(0)).isIn("foo/baz.txt", "foo/qux.txt", "foo/" + dir1.getName() + "/" + file3.getName()); assertThat(out.get(1)).isIn("foo/baz.txt", "foo/qux.txt", "foo/" + dir1.getName() + "/" + file3.getName()); assertThat(out.get(2)).isIn("foo/baz.txt", "foo/qux.txt", "foo/" + dir1.getName() + "/" + file3.getName()); } @Test @SuppressWarnings("unchecked") public void testRemoteFileTemplateImmutability() { SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class); RemoteFileTemplate<TestLsEntry> template = new RemoteFileTemplate<>(sessionFactory); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "mput", null); assertThatIllegalStateException() .isThrownBy(() -> gw.setRemoteDirectoryExpression(new LiteralExpression("testRemoteDirectory"))) .withMessageContaining("The 'remoteDirectoryExpression' must be set on the externally provided"); } @Test @SuppressWarnings("unchecked") public void testMputCollection() throws Exception { SessionFactory<TestLsEntry> sessionFactory = mock(SessionFactory.class); Session<TestLsEntry> session = mock(Session.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mput", "payload"); gw.setRemoteDirectoryExpression(new LiteralExpression("foo/")); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); final AtomicReference<String> written = new AtomicReference<>(); doAnswer(invocation -> { written.set(invocation.getArgument(1)); return null; }).when(session).write(any(InputStream.class), anyString()); List<File> files = new ArrayList<>(); files.add(tempFolder.newFile("fiz.txt")); files.add(tempFolder.newFile("buz.txt")); Message<List<File>> requestMessage = MessageBuilder.withPayload(files) .build(); List<String> out = (List<String>) gw.handleRequestMessage(requestMessage); assertThat(out).isNotNull().hasSize(2); assertThat(out.get(0)).isNotEqualTo(out.get(1)); assertThat(out.get(0)).isEqualTo("foo/fiz.txt"); assertThat(out.get(1)).isEqualTo("foo/buz.txt"); assertThat(written.get()).isEqualTo("foo/buz.txt.writing"); verify(session).rename("foo/buz.txt.writing", "foo/buz.txt"); } abstract static class TestSession implements Session<TestLsEntry> { private boolean open; @Override public boolean remove(String path) { return false; } @Override public TestLsEntry[] list(String path) { return null; } @Override public void read(String source, OutputStream outputStream) throws IOException { } @Override public void write(InputStream inputStream, String destination) { } @Override public void append(InputStream inputStream, String destination) { } @Override public boolean mkdir(String directory) { return true; } @Override public boolean rmdir(String directory) { return true; } @Override public void rename(String pathFrom, String pathTo) { } @Override public void close() { open = false; } @Override public boolean isOpen() { return this.open; } @Override public boolean exists(String path) { return true; } @Override public String[] listNames(String path) { return null; } @Override public InputStream readRaw(String source) { return null; } @Override public boolean finalizeRaw() { return false; } @Override public Object getClientInstance() { return null; } @Override public String getHostPort() { return null; } } static class TestRemoteFileOutboundGateway extends AbstractRemoteFileOutboundGateway<TestLsEntry> { @SuppressWarnings("unchecked") TestRemoteFileOutboundGateway(SessionFactory sessionFactory, String command, String expression) { super(sessionFactory, Command.toCommand(command), expression); this.setBeanFactory(mock(BeanFactory.class)); remoteFileTemplateExplicitlySet(false); } TestRemoteFileOutboundGateway(RemoteFileTemplate<TestLsEntry> remoteFileTemplate, String command, String expression) { super(remoteFileTemplate, command, expression); this.setBeanFactory(mock(BeanFactory.class)); } @Override protected boolean isDirectory(TestLsEntry file) { return file.isDirectory(); } @Override protected boolean isLink(TestLsEntry file) { return file.isLink(); } @Override protected String getFilename(TestLsEntry file) { return file.getFilename(); } @Override protected String getFilename(AbstractFileInfo<TestLsEntry> file) { return file.getFilename(); } @Override protected long getModified(TestLsEntry file) { return file.getModified(); } @Override protected List<AbstractFileInfo<TestLsEntry>> asFileInfoList( Collection<TestLsEntry> files) { return new ArrayList<>(files); } @Override protected TestLsEntry enhanceNameWithSubDirectory(TestLsEntry file, String directory) { file.setFilename(directory + file.getFilename()); return file; } } static class TestLsEntry extends AbstractFileInfo<TestLsEntry> { private volatile String filename; private final long size; private final boolean dir; private final boolean link; private final long modified; private final String permissions; TestLsEntry(String filename, long size, boolean dir, boolean link, long modified, String permissions) { this.filename = filename; this.size = size; this.dir = dir; this.link = link; this.modified = modified; this.permissions = permissions; } @Override public boolean isDirectory() { return this.dir; } @Override public long getModified() { return this.modified; } @Override public String getFilename() { return this.filename; } @Override public boolean isLink() { return this.link; } @Override public long getSize() { return this.size; } @Override public String getPermissions() { return this.permissions; } @Override public TestLsEntry getFileInfo() { return this; } public void setFilename(String filename) { this.filename = filename; } } static class TestPatternFilter extends AbstractSimplePatternFileListFilter<TestLsEntry> { TestPatternFilter(String path) { super(path); } @Override protected String getFilename(TestLsEntry file) { return file.getFilename(); } @Override protected boolean isDirectory(TestLsEntry file) { return file.isDirectory(); } } }
37.295206
109
0.738431
4d59f01b6946d7f5d0ae5a52e9536b0efa535355
2,586
package ca.corefacility.bioinformatics.irida.security.permissions.files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import ca.corefacility.bioinformatics.irida.model.run.SequencingRun; import ca.corefacility.bioinformatics.irida.model.user.Role; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.repositories.SequencingRunRepository; import ca.corefacility.bioinformatics.irida.repositories.user.UserRepository; import ca.corefacility.bioinformatics.irida.security.permissions.BasePermission; /** * Permission checking if a user is the owner of a {@link SequencingRun} or if * they are ROLE_SEQUENCER */ @Component public class UpdateSequencingRunPermission extends BasePermission<SequencingRun, Long> { private static final String PERMISSION_PROVIDED = "canUpdateSequencingRun"; private static final Logger logger = LoggerFactory.getLogger(UpdateSequencingRunPermission.class); private UserRepository userRepository; /** * Construct an instance of {@link UpdateSequencingRunPermission}. * * @param sequencingRunRepository * a {@link SequencingRunRepository} * @param userRepository * a {@link UserRepository} */ @Autowired public UpdateSequencingRunPermission(SequencingRunRepository sequencingRunRepository, UserRepository userRepository) { super(SequencingRun.class, Long.class, sequencingRunRepository); this.userRepository = userRepository; } /** * {@inheritDoc} */ @Override protected boolean customPermissionAllowed(Authentication authentication, SequencingRun targetDomainObject) { User user = userRepository.loadUserByUsername(authentication.getName()); logger.trace("Checking if [" + authentication + "] can modify [" + targetDomainObject + "]"); if (user.getSystemRole().equals(Role.ROLE_SEQUENCER)) { logger.trace("Permission GRANTED: " + user + " is a sequencer so can update " + targetDomainObject); return true; } if (targetDomainObject.getUser() != null && targetDomainObject.getUser().equals(user)) { logger.trace("Permission GRANTED: " + user + " is the owner of " + targetDomainObject); return true; } logger.trace("Permission DENIED: " + user + " is NOT the owner of " + targetDomainObject); return false; } /** * {@inheritDoc} */ @Override public String getPermissionProvided() { return PERMISSION_PROVIDED; } }
33.584416
109
0.772622
d5a2f8e0cdb2609722295841e143d2d2e3ca84ce
77,855
/************************************************************************************** * dandelion_tree * Copyright (c) 2014-2016 National University of Colombia, https://github.com/remixlab * @author Jean Pierre Charalambos, http://otrolado.info/ * * All rights reserved. Library that eases the creation of interactive * scenes, released under the terms of the GNU Public License v3.0 * which is available at http://www.gnu.org/licenses/gpl.html **************************************************************************************/ package remixlab.dandelion.core; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import remixlab.bias.core.*; import remixlab.bias.event.*; import remixlab.dandelion.constraint.*; import remixlab.dandelion.geom.*; import remixlab.fpstiming.*; /** * A 2D or 3D {@link remixlab.bias.core.Grabber} scene. * * Main package class representing an interface between Dandelion and the outside world. * For an introduction to DANDELION please refer to * <a href="http://nakednous.github.io/projects/dandelion">this</a>. * <p> * Instantiated scene {@link remixlab.dandelion.core.GenericFrame}s form a scene-graph of * transformations which may be traverse with {@link #traverseGraph()}. The frame * collection belonging to the scene may be retrieved with {@link #frames(boolean)}. The * scene provides other useful routines to handle the hierarchy, such as * {@link #pruneBranch(GenericFrame)}, {@link #appendBranch(List)}, * {@link #isFrameReachable(GenericFrame)}, {@link #branch(GenericFrame, boolean)}, and * {@link #clearGraph()}. * <p> * Each AbstractScene provides the following main object instances: * <ol> * <li>An {@link #eye()} which represents the 2D ( {@link remixlab.dandelion.core.Window}) * or 3D ( {@link remixlab.dandelion.core.Camera}) controlling object. For details please * refer to the {@link remixlab.dandelion.core.Eye} class.</li> * <li>A {@link #timingHandler()} which control (single-threaded) timing operations. For * details please refer to the {@link remixlab.fpstiming.TimingHandler} class.</li> * <li>An {@link #inputHandler()} which handles all user input through * {@link remixlab.bias.core.Agent}s (for details please refer to the * {@link remixlab.bias.core.InputHandler} class). The {@link #inputHandler()} holds a * (default) {@link #motionAgent()} and a (default) {@link #keyboardAgent()} which should * be instantiated by derived classes at construction time.</li> * <li>A {@link #matrixHelper()} which handles matrix operations either through the * {@link remixlab.dandelion.core.MatrixStackHelper} or through a third party matrix stack * (like it's done with Processing). For details please refer to the * {@link remixlab.dandelion.core.MatrixHelper} interface.</li> * </ol> * <h3>Animation mechanisms</h3> The AbstractScene provides two animation mechanisms to * define how your scene evolves over time: * <ol> * <li>Overriding the Dandelion {@link #animate()} method. In this case, once you declare * a Scene derived class, you should implement {@link #animate()} which defines how your * scene objects evolve over time. * <li>By checking if the scene's {@link #timer()} was triggered within the frame. * </ol> * <p> * A grabber scene implements the {@link remixlab.bias.core.Grabber} interface and thus * can react to user (keyboard) gestures, (see {@link #performInteraction(KeyboardEvent)} * and {@link #checkIfGrabsInput(KeyboardEvent)}). For example, with the following code: * * <pre> * {@code * protected void performInteraction(KeyboardEvent event) { * if(event.key() == 'z') * toggleCameraType(); * } * } * </pre> * * your custom scene will {@link #toggleCameraType()} when the key 'z' is pressed * (provided that scene is the {@link #keyboardAgent()} * {@link remixlab.bias.core.Agent#inputGrabber()}). */ public abstract class AbstractScene extends AnimatorObject implements Grabber { protected boolean dottedGrid; // O B J E C T S protected MatrixHelper matrixHelper; protected Eye eye; protected Trackable trck; // E X C E P T I O N H A N D L I N G protected int startCoordCalls; // NUMBER OF FRAMES SINCE THE FIRST SCENE WAS INSTANTIATED static public long frameCount; // InputHandler protected InputHandler iHandler; // D I S P L A Y F L A G S protected int visualHintMask; // LEFT vs RIGHT_HAND protected boolean rightHanded; // S I Z E protected int width, height; // offscreen protected Point upperLeftCorner; protected boolean offscreen; protected long lastEqUpdate; // FRAME SYNC requires this: protected final long deltaCount; protected Agent defMotionAgent, defKeyboardAgent; /** * Visual hints as "the last shall be first" */ public final static int AXES = 1 << 0; public final static int GRID = 1 << 1; public final static int PICKING = 1 << 2; public final static int PATHS = 1 << 3; public final static int ZOOM = 1 << 4; // prosceneMouse.zoomOnRegion public final static int ROTATE = 1 << 5; // prosceneMouse.screenRotate protected static Platform platform; public enum Platform { PROCESSING_DESKTOP, PROCESSING_ANDROID, PROCESSING_JS } protected List<GenericFrame> seeds; // public final static int PUP = 1 << 6; // public final static int ARP = 1 << 7; /** * Default constructor which defines a right-handed OpenGL compatible Scene with its own * {@link remixlab.dandelion.core.MatrixStackHelper}. The constructor also instantiates * the {@link #inputHandler()} and the {@link #timingHandler()}, and sets the AXES and * GRID visual hint flags. * <p> * Third party (concrete) Scenes should additionally: * <ol> * <li>(Optionally) Define a custom {@link #matrixHelper()}. Only if the target platform * (such as Processing) provides its own matrix handling.</li> * <li>Call {@link #setEye(Eye)} to set the {@link #eye()}, once it's known if the Scene * {@link #is2D()} or {@link #is3D()}.</li> * <li>Instantiate the {@link #motionAgent()} and the {@link #keyboardAgent()} and * enable them (register them at the {@link #inputHandler()}) and possibly some other * {@link remixlab.bias.core.Agent}s as well and .</li> * <li>Define whether or not the Scene {@link #isOffscreen()}.</li> * <li>Call {@link #init()} at the end of the constructor.</li> * </ol> * * @see #timingHandler() * @see #inputHandler() * @see #setMatrixHelper(MatrixHelper) * @see #setRightHanded() * @see #setVisualHints(int) * @see #setEye(Eye) */ public AbstractScene() { seeds = new ArrayList<GenericFrame>(); setPlatform(); setTimingHandler(new TimingHandler(this)); deltaCount = frameCount; iHandler = new InputHandler(); setMatrixHelper(new MatrixStackHelper(this)); setRightHanded(); setVisualHints(AXES | GRID); upperLeftCorner = new Point(0, 0); } /** * Returns the top-level frames (those which referenceFrame is null). * <p> * All leading frames are also reachable by the {@link #traverseGraph()} algorithm for * which they are the seeds. * * @see #frames() * @see #isFrameReachable(GenericFrame) * @see #pruneBranch(GenericFrame) */ public List<GenericFrame> leadingFrames() { return seeds; } /** * Returns {@code true} if the frame is top-level. */ protected boolean isLeadingFrame(GenericFrame gFrame) { for (GenericFrame frame : leadingFrames()) if (frame == gFrame) return true; return false; } /** * Add the frame as top-level if its reference frame is null and it isn't already added. */ protected boolean addLeadingFrame(GenericFrame gFrame) { if (gFrame == null || gFrame.referenceFrame() != null) return false; if (isLeadingFrame(gFrame)) return false; return leadingFrames().add(gFrame); } /** * Removes the leading frame if present. Typically used when re-parenting the frame. */ protected boolean removeLeadingFrame(GenericFrame iFrame) { boolean result = false; Iterator<GenericFrame> it = leadingFrames().iterator(); while (it.hasNext()) { if (it.next() == iFrame) { it.remove(); result = true; break; } } return result; } /** * Traverse the frame hierarchy, successively applying the local transformation defined * by each traversed frame, and calling * {@link remixlab.dandelion.core.GenericFrame#visit()} on it. * <p> * Note that only reachable frames are visited by this algorithm. * * @see #isFrameReachable(GenericFrame) * @see #pruneBranch(GenericFrame) */ public void traverseGraph() { for (GenericFrame frame : leadingFrames()) visitFrame(frame); } /** * Used by the traverse frame graph algorithm. */ protected void visitFrame(GenericFrame frame) { pushModelView(); applyTransformation(frame); frame.visitCallback(); for (GenericFrame child : frame.children()) visitFrame(child); popModelView(); } /** * Same as {@code for(GenericFrame frame : leadingFrames()) pruneBranch(frame)}. * * @see #pruneBranch(GenericFrame) */ public void clearGraph() { for (GenericFrame frame : leadingFrames()) pruneBranch(frame); } /** * Make all the frames in the {@code frame} branch eligible for garbage collection. * <p> * A call to {@link #isFrameReachable(GenericFrame)} on all {@code frame} descendants * (including {@code frame}) will return false, after issuing this method. It also means * that all frames in the {@code frame} branch will become unreachable by the * {@link #traverseGraph()} algorithm. * <p> * Frames in the {@code frame} branch will also be removed from all the agents currently * registered in the {@link #inputHandler()}. * <p> * To make all the frames in the branch reachable again, first cache the frames * belonging to the branch (i.e., {@code branch=pruneBranch(frame)}) and then call * {@link #appendBranch(List)} on the cached branch. Note that calling * {@link remixlab.dandelion.core.GenericFrame#setReferenceFrame(GenericFrame)} on a * frame belonging to the pruned branch will become reachable again by the traversal * algorithm. In this case, the frame should be manually added to some agents to * interactively handle it. * <p> * //TODO Note that if frame is not reachable ({@link #isFrameReachable(GenericFrame)}) * this method returns {@code null}. * <p> * When collected, pruned frames behave like {@link remixlab.dandelion.geom.Frame}, * otherwise they are eligible for garbage collection. * * @see #clearGraph() * @see #appendBranch(List) * @see #isFrameReachable(GenericFrame) */ public ArrayList<GenericFrame> pruneBranch(GenericFrame frame) { // /* // TODO if (!isFrameReachable(frame)) return null; // */ ArrayList<GenericFrame> list = new ArrayList<GenericFrame>(); collectFrames(list, frame, true); for (GenericFrame gFrame : list) { inputHandler().removeGrabber(gFrame); if (gFrame.referenceFrame() != null) gFrame.referenceFrame().removeChild(gFrame); else removeLeadingFrame(gFrame); } return list; } /** * Appends the branch which typically should come from the one pruned (and cached) with * {@link #pruneBranch(GenericFrame)}. * <p> * All frames belonging to the branch are automatically added to all scene agents. * * {@link #pruneBranch(GenericFrame)} */ public void appendBranch(List<GenericFrame> branch) { if (branch == null) return; for (GenericFrame gFrame : branch) { inputHandler().addGrabber(gFrame); if (gFrame.referenceFrame() != null) gFrame.referenceFrame().addChild(gFrame); else addLeadingFrame(gFrame); } } /** * Returns {@code true} if the frame is reachable by the {@link #traverseGraph()} * algorithm and {@code false} otherwise. * <p> * Frames are make unreachable with {@link #pruneBranch(GenericFrame)} and reachable * again with * {@link remixlab.dandelion.core.GenericFrame#setReferenceFrame(GenericFrame)}. * * @see #traverseGraph() * @see #frames(boolean) */ public boolean isFrameReachable(GenericFrame frame) { if (frame == null) return false; return frame.referenceFrame() == null ? isLeadingFrame(frame) : frame.referenceFrame().hasChild(frame); } /** * Returns a list of all the frames that are reachable by the {@link #traverseGraph()} * algorithm, including the EyeFrames (when {@code eyeframes} is {@code true}). * * @ see {@link #isFrameReachable(GenericFrame)} * * @see remixlab.dandelion.core.GenericFrame#isEyeFrame() */ public ArrayList<GenericFrame> frames(boolean eyeframes) { ArrayList<GenericFrame> list = new ArrayList<GenericFrame>(); for (GenericFrame gFrame : leadingFrames()) collectFrames(list, gFrame, eyeframes); return list; } /** * Collects {@code frame} and all its descendant frames. When {@code eyeframes} is * {@code true} eye-frames will also be collected. Note that for a frame to be collected * it must be reachable. * * @see #isFrameReachable(GenericFrame) */ public ArrayList<GenericFrame> branch(GenericFrame frame, boolean eyeframes) { ArrayList<GenericFrame> list = new ArrayList<GenericFrame>(); collectFrames(list, frame, eyeframes); return list; } /** * Collects {@code frame} and all its descendant frames. When {@code eyeframes} is * {@code true} eye-frames will also be collected. Note that for a frame to be collected * it must be reachable. * * @see #isFrameReachable(GenericFrame) */ protected void collectFrames(List<GenericFrame> list, GenericFrame frame, boolean eyeframes) { if (frame == null) return; if (!frame.isEyeFrame() || eyeframes) list.add(frame); for (GenericFrame child : frame.children()) collectFrames(list, child, eyeframes); } // Actions /** * Same as {@code eye().addKeyFrameToPath(1)}. * * @see remixlab.dandelion.core.Eye#addKeyFrameToPath(int) */ public void addKeyFrameToPath1() { eye().addKeyFrameToPath(1); } /** * Same as {@code eye().addKeyFrameToPath(2)}. * * @see remixlab.dandelion.core.Eye#addKeyFrameToPath(int) */ public void addKeyFrameToPath2() { eye().addKeyFrameToPath(2); } /** * Same as {@code eye().addKeyFrameToPath(1)}. * * @see remixlab.dandelion.core.Eye#addKeyFrameToPath(int) */ public void addKeyFrameToPath3() { eye().addKeyFrameToPath(3); } /** * Same as {@code eye().deletePath(1)}. * * @see remixlab.dandelion.core.Eye#deletePath(int) */ public void deletePath1() { eye().deletePath(1); } /** * Same as {@code eye().deletePath(2)}. * * @see remixlab.dandelion.core.Eye#deletePath(int) */ public void deletePath2() { eye().deletePath(2); } /** * Same as {@code eye().deletePath(3)}. * * @see remixlab.dandelion.core.Eye#deletePath(int) */ public void deletePath3() { eye().deletePath(3); } /** * Same as {@code eye().playPath(1)}. * * @see remixlab.dandelion.core.Eye#playPath(int) */ public void playPath1() { eye().playPath(1); } /** * Same as {@code eye().playPath(2)}. * * @see remixlab.dandelion.core.Eye#playPath(int) */ public void playPath2() { eye().playPath(2); } /** * Same as {@code eye().playPath(3)}. * * @see remixlab.dandelion.core.Eye#playPath(int) */ public void playPath3() { eye().playPath(3); } /** * Same as {@code eye().interpolateToFitScene()}. * * @see remixlab.dandelion.core.Eye#interpolateToFitScene() */ public void interpolateToFitScene() { eye().interpolateToFitScene(); } /** * Same as {@code eye().setAnchor(new Vec(0, 0, 0))}. * * @see remixlab.dandelion.core.Eye#setAnchor(Vec) */ public void resetAnchor() { eye().setAnchor(new Vec(0, 0, 0)); // looks horrible, but works ;) eye().anchorFlag = true; eye().runResetAnchorHintTimer(1000); } // Grabber Implementation @Override public void performInteraction(BogusEvent event) { if (event instanceof KeyboardEvent) performInteraction((KeyboardEvent) event); } @Override public boolean checkIfGrabsInput(BogusEvent event) { if (event instanceof KeyboardEvent) return checkIfGrabsInput((KeyboardEvent) event); return false; } /** * Override this method when you want the object to perform an interaction from a * {@link remixlab.bias.event.KeyboardEvent}. */ protected void performInteraction(KeyboardEvent event) { AbstractScene.showMissingImplementationWarning("performInteraction(KeyboardEvent event)", this.getClass().getName()); } boolean vkeyAction; /** * Internal use. Inspired in Processing key event flow. Bypasses the key event so that * {@link remixlab.bias.event.KeyboardShortcut}s work smoothly. Call it at the beginning * of your {@link #performInteraction(KeyboardEvent)} method to discard useless keyboard * events. */ protected boolean bypassKey(BogusEvent event) { if (event instanceof KeyboardEvent) { if (event.fired()) if (event.id() == 0)// TYPE event return vkeyAction; else { vkeyAction = true; return false; } if (event.flushed()) { if (event.flushed() && vkeyAction) vkeyAction = false; return true; } } return false; } /** * Override this method when you want the object to be picked from a * {@link remixlab.bias.event.KeyboardEvent}. */ protected boolean checkIfGrabsInput(KeyboardEvent event) { AbstractScene.showMissingImplementationWarning("checkIfGrabsInput(KeyboardEvent event)", this.getClass().getName()); return false; } /** * Check if this object is the {@link remixlab.bias.core.Agent#inputGrabber()} . Returns * {@code true} if this object grabs the agent and {@code false} otherwise. */ public boolean grabsInput(Agent agent) { return agent.inputGrabber() == this; } /** * Checks if the scene grabs input from any agent registered at the input handler. */ public boolean grabsInput() { for (Agent agent : inputHandler().agents()) { if (agent.inputGrabber() == this) return true; } return false; } // /** * Returns the upper left corner of the Scene window. It's always (0,0) for on-screen * scenes, but off-screen scenes may be defined elsewhere on a canvas. */ public Point originCorner() { return upperLeftCorner; } /** * Determines under which platform dandelion is running. Either DESKTOP, ANDROID or JS. */ protected abstract void setPlatform(); /** * Returns the platform where dandelion is running. Either DESKTOP, ANDROID or JS. */ public static Platform platform() { return platform; } // AGENTs // Keyboard /** * Returns the default {@link remixlab.bias.core.Agent} keyboard agent. * * @see #motionAgent() */ public Agent keyboardAgent() { return defKeyboardAgent; } /** * Returns {@code true} if the {@link #keyboardAgent()} is enabled and {@code false} * otherwise. * * @see #enableKeyboardAgent() * @see #disableKeyboardAgent() * @see #isMotionAgentEnabled() */ public boolean isKeyboardAgentEnabled() { return inputHandler().isAgentRegistered(keyboardAgent()); } /** * Enables keyboard handling through the {@link #keyboardAgent()}. * * @see #isKeyboardAgentEnabled() * @see #disableKeyboardAgent() * @see #enableMotionAgent() */ public void enableKeyboardAgent() { if (!inputHandler().isAgentRegistered(keyboardAgent())) { inputHandler().registerAgent(keyboardAgent()); } } // Motion agent /** * Returns the default motion agent. * * @see #keyboardAgent() */ public Agent motionAgent() { return defMotionAgent; } /** * Returns {@code true} if the {@link #motionAgent()} is enabled and {@code false} * otherwise. * * @see #enableMotionAgent() * @see #disableMotionAgent() * @see #isKeyboardAgentEnabled() */ public boolean isMotionAgentEnabled() { return inputHandler().isAgentRegistered(motionAgent()); } /** * Enables motion handling through the {@link #motionAgent()}. * * @see #isMotionAgentEnabled() * @see #disableMotionAgent() * @see #enableKeyboardAgent() */ public void enableMotionAgent() { if (!inputHandler().isAgentRegistered(motionAgent())) { inputHandler().registerAgent(motionAgent()); } } /** * Disables the default {@link remixlab.bias.core.Agent} and returns it. * * @see #isKeyboardAgentEnabled() * @see #enableKeyboardAgent() * @see #disableMotionAgent() */ public boolean disableKeyboardAgent() { return inputHandler().unregisterAgent(keyboardAgent()); } /** * Disables the default motion agent and returns it. * * @see #isMotionAgentEnabled() * @see #enableMotionAgent() * @see #enableKeyboardAgent() */ public boolean disableMotionAgent() { return inputHandler().unregisterAgent(motionAgent()); } // FPSTiming STUFF /** * Returns the number of frames displayed since the scene was instantiated. * <p> * Use {@code AbstractScene.frameCount} to retrieve the number of frames displayed since * the first scene was instantiated. */ public long frameCount() { return timingHandler().frameCount(); } /** * Convenience wrapper function that simply calls * {@code timingHandler().registerTask(task)}. * * @see remixlab.fpstiming.TimingHandler#registerTask(TimingTask) */ public void registerTimingTask(TimingTask task) { timingHandler().registerTask(task); } /** * Convenience wrapper function that simply calls * {@code timingHandler().unregisterTask(task)}. */ public void unregisterTimingTask(TimingTask task) { timingHandler().unregisterTask(task); } /** * Convenience wrapper function that simply returns * {@code timingHandler().isTaskRegistered(task)}. */ public boolean isTimingTaskRegistered(TimingTask task) { return timingHandler().isTaskRegistered(task); } /** * Convenience wrapper function that simply calls * {@code timingHandler().registerAnimator(object)}. */ public void registerAnimator(Animator object) { timingHandler().registerAnimator(object); } /** * Convenience wrapper function that simply calls * {@code timingHandler().unregisterAnimator(object)}. * * @see remixlab.fpstiming.TimingHandler#unregisterAnimator(Animator) */ public void unregisterAnimator(Animator object) { timingHandler().unregisterAnimator(object); } /** * Convenience wrapper function that simply returns * {@code timingHandler().isAnimatorRegistered(object)}. * * @see remixlab.fpstiming.TimingHandler#isAnimatorRegistered(Animator) */ public boolean isAnimatorRegistered(Animator object) { return timingHandler().isAnimatorRegistered(object); } // E V E N T H A N D L I N G /** * Returns the scene {@link remixlab.bias.core.InputHandler}. */ public InputHandler inputHandler() { return iHandler; } /** * Convenience function that simply returns {@code inputHandler().info()}. * * @see #displayInfo(boolean) */ public abstract String info(); /** * Convenience function that simply calls {@code displayInfo(true)}. */ public void displayInfo() { displayInfo(true); } /** * Displays the {@link #info()} bindings. * * @param onConsole * if this flag is true displays the help on console. Otherwise displays it on * the applet * * @see #info() */ public void displayInfo(boolean onConsole) { if (onConsole) System.out.println(info()); else AbstractScene.showMissingImplementationWarning("displayInfo", getClass().getName()); } // 1. Scene overloaded // MATRIX and TRANSFORMATION STUFF /** * Sets the {@link remixlab.dandelion.core.MatrixHelper} defining how dandelion matrices * are to be handled. * * @see #matrixHelper() */ public void setMatrixHelper(MatrixHelper r) { matrixHelper = r; } /** * Returns the {@link remixlab.dandelion.core.MatrixHelper}. * * @see #setMatrixHelper(MatrixHelper) */ public MatrixHelper matrixHelper() { return matrixHelper; } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#beginScreenDrawing()}. Adds * exception when no properly closing the screen drawing with a call to * {@link #endScreenDrawing()}. * * @see remixlab.dandelion.core.MatrixHelper#beginScreenDrawing() */ public void beginScreenDrawing() { if (startCoordCalls != 0) throw new RuntimeException("There should be exactly one beginScreenDrawing() call followed by a " + "endScreenDrawing() and they cannot be nested. Check your implementation!"); startCoordCalls++; disableDepthTest(); matrixHelper.beginScreenDrawing(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#endScreenDrawing()} . Adds * exception if {@link #beginScreenDrawing()} wasn't properly called before * * @see remixlab.dandelion.core.MatrixHelper#endScreenDrawing() */ public void endScreenDrawing() { startCoordCalls--; if (startCoordCalls != 0) throw new RuntimeException("There should be exactly one beginScreenDrawing() call followed by a " + "endScreenDrawing() and they cannot be nested. Check your implementation!"); matrixHelper.endScreenDrawing(); enableDepthTest(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#bind()} */ protected void bindMatrices() { matrixHelper.bind(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#pushModelView()} */ public void pushModelView() { matrixHelper.pushModelView(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#popModelView()} */ public void popModelView() { matrixHelper.popModelView(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#pushProjection()} */ public void pushProjection() { matrixHelper.pushProjection(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#popProjection()} */ public void popProjection() { matrixHelper.popProjection(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#translate(float, float)} */ public void translate(float tx, float ty) { matrixHelper.translate(tx, ty); } /** * Wrapper for * {@link remixlab.dandelion.core.MatrixHelper#translate(float, float, float)} */ public void translate(float tx, float ty, float tz) { matrixHelper.translate(tx, ty, tz); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#rotate(float)} */ public void rotate(float angle) { matrixHelper.rotate(angle); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#rotateX(float)} */ public void rotateX(float angle) { matrixHelper.rotateX(angle); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#rotateY(float)} */ public void rotateY(float angle) { matrixHelper.rotateY(angle); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#rotateZ(float)} */ public void rotateZ(float angle) { matrixHelper.rotateZ(angle); } /** * Wrapper for * {@link remixlab.dandelion.core.MatrixHelper#rotate(float, float, float, float)} */ public void rotate(float angle, float vx, float vy, float vz) { matrixHelper.rotate(angle, vx, vy, vz); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#scale(float)} */ public void scale(float s) { matrixHelper.scale(s); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#scale(float, float)} */ public void scale(float sx, float sy) { matrixHelper.scale(sx, sy); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#scale(float, float, float)} */ public void scale(float x, float y, float z) { matrixHelper.scale(x, y, z); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#resetModelView()} */ public void resetModelView() { matrixHelper.resetModelView(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#resetProjection()} */ public void resetProjection() { matrixHelper.resetProjection(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#applyModelView(Mat)} */ public void applyModelView(Mat source) { matrixHelper.applyModelView(source); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#applyProjection(Mat)} */ public void applyProjection(Mat source) { matrixHelper.applyProjection(source); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#modelView()} */ public Mat modelView() { return matrixHelper.modelView(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#projection()} */ public Mat projection() { return matrixHelper.projection(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#getModelView(Mat)} */ public Mat getModelView(Mat target) { return matrixHelper.getModelView(target); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#getProjection(Mat)} */ public Mat getProjection(Mat target) { return matrixHelper.getProjection(target); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#setModelView(Mat)} */ public void setModelView(Mat source) { matrixHelper.setModelView(source); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#setProjection(Mat)} */ public void setProjection(Mat source) { matrixHelper.setProjection(source); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#printModelView()} */ public void printModelView() { matrixHelper.printModelView(); } /** * Wrapper for {@link remixlab.dandelion.core.MatrixHelper#printProjection()} */ public void printProjection() { matrixHelper.printProjection(); } /** * Wrapper for * {@link remixlab.dandelion.core.MatrixHelper#isProjectionViewInverseCached()} . * <p> * Use it only when continuously calling {@link #unprojectedCoordinatesOf(Vec)}. * * @see #optimizeUnprojectedCoordinatesOf(boolean) * @see #unprojectedCoordinatesOf(Vec) */ public boolean isUnprojectedCoordinatesOfOptimized() { return matrixHelper.isProjectionViewInverseCached(); } /** * Wrapper for * {@link remixlab.dandelion.core.MatrixHelper#cacheProjectionViewInverse(boolean)} . * <p> * Use it only when continuously calling {@link #unprojectedCoordinatesOf(Vec)}. * * @see #isUnprojectedCoordinatesOfOptimized() * @see #unprojectedCoordinatesOf(Vec) */ public void optimizeUnprojectedCoordinatesOf(boolean optimise) { matrixHelper.cacheProjectionViewInverse(optimise); } // DRAWING STUFF /** * Returns the visual hints flag. */ public int visualHints() { return this.visualHintMask; } /** * Low level setting of visual flags. You'd prefer {@link #setAxesVisualHint(boolean)}, * {@link #setGridVisualHint(boolean)}, {@link #setPathsVisualHint(boolean)} and * {@link #setPickingVisualHint(boolean)}, unless you want to set them all at once, * e.g., * {@code setVisualHints(Constants.AXES | Constants.GRID | Constants.PATHS | Constants.PICKING)} * . */ public void setVisualHints(int flag) { visualHintMask = flag; } /** * Toggles the state of {@link #axesVisualHint()}. * * @see #axesVisualHint() * @see #setAxesVisualHint(boolean) */ public void toggleAxesVisualHint() { setAxesVisualHint(!axesVisualHint()); } /** * Toggles the state of {@link #gridVisualHint()}. * * @see #setGridVisualHint(boolean) */ public void toggleGridVisualHint() { setGridVisualHint(!gridVisualHint()); } /** * Toggles the state of {@link #pickingVisualHint()}. * * @see #setPickingVisualHint(boolean) */ public void togglePickingVisualhint() { setPickingVisualHint(!pickingVisualHint()); } /** * Toggles the state of {@link #pathsVisualHint()}. * * @see #setPathsVisualHint(boolean) */ public void togglePathsVisualHint() { setPathsVisualHint(!pathsVisualHint()); } /** * Internal :p */ protected void toggleZoomVisualHint() { setZoomVisualHint(!zoomVisualHint()); } /** * Internal :p */ protected void toggleRotateVisualHint() { setRotateVisualHint(!rotateVisualHint()); } /** * Returns {@code true} if axes are currently being drawn and {@code false} otherwise. */ public boolean axesVisualHint() { return ((visualHintMask & AXES) != 0); } /** * Returns {@code true} if grid is currently being drawn and {@code false} otherwise. */ public boolean gridVisualHint() { return ((visualHintMask & GRID) != 0); } /** * Returns {@code true} if the picking selection visual hint is currently being drawn * and {@code false} otherwise. */ public boolean pickingVisualHint() { return ((visualHintMask & PICKING) != 0); } /** * Returns {@code true} if the eye paths visual hints are currently being drawn and * {@code false} otherwise. */ public boolean pathsVisualHint() { return ((visualHintMask & PATHS) != 0); } /** * Internal. Third parties should not call this. */ public boolean zoomVisualHint() { return ((visualHintMask & ZOOM) != 0); } /** * Internal. Third parties should not call this. */ public boolean rotateVisualHint() { return ((visualHintMask & ROTATE) != 0); } /** * Sets the display of the axes according to {@code draw} */ public void setAxesVisualHint(boolean draw) { if (draw) visualHintMask |= AXES; else visualHintMask &= ~AXES; } /** * Sets the display of the grid according to {@code draw} */ public void setGridVisualHint(boolean draw) { if (draw) visualHintMask |= GRID; else visualHintMask &= ~GRID; } /** * Sets the display of the interactive frames' selection hints according to {@code draw} */ public void setPickingVisualHint(boolean draw) { if (draw) visualHintMask |= PICKING; else visualHintMask &= ~PICKING; } /** * Sets the display of the camera key frame paths according to {@code draw} */ public void setPathsVisualHint(boolean draw) { if (draw) { if (eye() != null) { visualHintMask |= PATHS; eye().attachPaths(); } else System.err.println("Warning: null eye, no path attached!"); } else { if (eye() != null) { visualHintMask &= ~PATHS; eye().detachPaths(); } else System.err.println("Warning: null eye, no path dettached!"); } } /** * Internal. Third parties should not call this. */ public void setZoomVisualHint(boolean draw) { if (draw) visualHintMask |= ZOOM; else visualHintMask &= ~ZOOM; } /** * Internal. Third parties should not call this. */ public void setRotateVisualHint(boolean draw) { if (draw) visualHintMask |= ROTATE; else visualHintMask &= ~ROTATE; } /** * Called before your main drawing, e.g., P5.pre(). * <p> * Handles the {@link #avatar()}, then calls {@link #bindMatrices()} and finally * {@link remixlab.dandelion.core.Eye#updateBoundaryEquations()} if * {@link #areBoundaryEquationsEnabled()}. */ public void preDraw() { if (avatar() != null && (!eye().anyInterpolationStarted())) { // works: /* * eye().frame().setPosition(avatar().trackingEyeFrame().position()); * eye().frame().setOrientation(avatar().trackingEyeFrame().orientation()) ; * eye().frame().setScaling(avatar().trackingEyeFrame().scaling()); // */ // but prefer this one: eye().frame().fromFrame(avatar().trackingEyeFrame()); // this one is buggy: // GenericFrame.sync(eye().frame(), avatar().trackingEyeFrame()); } bindMatrices(); if (areBoundaryEquationsEnabled() && (eye().lastUpdate() > lastEqUpdate || lastEqUpdate == 0)) { eye().updateBoundaryEquations(); lastEqUpdate = timingHandler().frameCount(); } } /** * Called after your main drawing, e.g., P5.draw(). * <p> * Calls: * <ol> * <li>{@link remixlab.fpstiming.TimingHandler#handle()}</li> * <li>{@link remixlab.bias.core.InputHandler#handle()}</li> * <li>{@link #proscenium()}</li> * <li>{@link #invokeGraphicsHandler()}</li> * <li>{@link #displayVisualHints()}.</li> * </ol> * * @see #proscenium() * @see #invokeGraphicsHandler() * @see #gridVisualHint() * @see #visualHints() */ public void postDraw() { // 1. timers timingHandler().handle(); if (frameCount < frameCount()) frameCount = frameCount(); if (frameCount < frameCount() + deltaCount) frameCount = frameCount() + deltaCount; // 2. Agents inputHandler().handle(); // 3. Alternative use only proscenium(); // 4. Draw external registered method (only in java sub-classes) invokeGraphicsHandler(); // abstract // 5. Display visual hints displayVisualHints(); // abstract } /** * Invokes an external drawing method (if registered). Called by {@link #postDraw()}. * <p> * Requires reflection and thus default implementation is empty. See proscene.Scene for * an implementation. */ protected boolean invokeGraphicsHandler() { return false; } /** * Internal use. Display various on-screen visual hints to be called from * {@link #postDraw()}. */ protected void displayVisualHints() { if (gridVisualHint()) drawGridHint(); if (axesVisualHint()) drawAxesHint(); if (pickingVisualHint()) drawPickingHint(); if (pathsVisualHint()) drawPathsHint(); if (zoomVisualHint()) drawZoomWindowHint(); if (rotateVisualHint()) drawScreenRotateHint(); if (eye().anchorFlag) drawAnchorHint(); if (eye().pupFlag) drawPointUnderPixelHint(); } /** * Internal use. */ protected void drawPickingHint() { drawPickingTargets(); } protected void drawPickingTargets() { List<GenericFrame> gList = new ArrayList<GenericFrame>(); for (Grabber mg : motionAgent().grabbers()) if (mg instanceof GenericFrame) if (!((GenericFrame) mg).isEyeFrame()) gList.add((GenericFrame) mg); gList.removeAll(eye.keyFrames()); for (GenericFrame g : gList) this.drawPickingTarget(g); } /** * Internal use. */ protected void drawAxesHint() { drawAxes(eye().sceneRadius()); } /** * Internal use. */ protected void drawGridHint() { if (gridIsDotted()) drawDottedGrid(eye().sceneRadius()); else drawGrid(eye().sceneRadius()); } /** * Internal use. */ protected void drawPathsHint() { drawPaths(); } protected void drawPaths() { /* * Iterator<Integer> itrtr = eye.kfi.keySet().iterator(); while (itrtr.hasNext()) { * Integer key = itrtr.next(); drawPath(eye.keyFrameInterpolatorMap().get(key), 3, * is3D() ? 5 : 2, radius()); } */ // alternative: // /* KeyFrameInterpolator[] k = eye.keyFrameInterpolatorArray(); for (int i = 0; i < k.length; i++) drawPath(k[i], 3, 5, radius()); // */ for (GenericFrame gFrame : eye.keyFrames()) drawPickingTarget(gFrame); } /** * Convenience function that simply calls {@code drawPath(kfi, 1, 6, 100)}. * * @see #drawPath(KeyFrameInterpolator, int, int, float) */ public void drawPath(KeyFrameInterpolator kfi) { drawPath(kfi, 1, 6, 100); } /** * Convenience function that simply calls {@code drawPath(kfi, 1, 6, scale)} * * @see #drawPath(KeyFrameInterpolator, int, int, float) */ public void drawPath(KeyFrameInterpolator kfi, float scale) { drawPath(kfi, 1, 6, scale); } /** * Convenience function that simply calls {@code drawPath(kfi, mask, nbFrames, * 100)} * * @see #drawPath(KeyFrameInterpolator, int, int, float) */ public void drawPath(KeyFrameInterpolator kfi, int mask, int nbFrames) { drawPath(kfi, mask, nbFrames, 100); } /** * Convenience function that simply calls {@code drawAxis(100)}. */ public void drawAxes() { drawAxes(100); } /** * Convenience function that simplt calls {@code drawDottedGrid(100, 10)}. */ public void drawDottedGrid() { drawDottedGrid(100, 10); } /** * Convenience function that simply calls {@code drawGrid(100, 10)} * * @see #drawGrid(float, int) */ public void drawGrid() { drawGrid(100, 10); } /** * Convenience function that simplt calls {@code drawDottedGrid(size, 10)}. */ public void drawDottedGrid(float size) { drawDottedGrid(size, 10); } /** * Convenience function that simply calls {@code drawGrid(size, 10)} * * @see #drawGrid(float, int) */ public void drawGrid(float size) { drawGrid(size, 10); } /** * Convenience function that simplt calls {@code drawDottedGrid(100, nbSubdivisions)}. */ public void drawDottedGrid(int nbSubdivisions) { drawDottedGrid(100, nbSubdivisions); } /** * Convenience function that simply calls {@code drawGrid(100, nbSubdivisions)} * * @see #drawGrid(float, int) */ public void drawGrid(int nbSubdivisions) { drawGrid(100, nbSubdivisions); } /** * Convenience function that simply calls {@code drawTorusSolenoid(6)}. * * @see #drawTorusSolenoid(int, int, float, float) */ public void drawTorusSolenoid() { drawTorusSolenoid(6); } /** * Convenience function that simply calls * {@code drawTorusSolenoid(faces, 0.07f * radius())}. * * @see #drawTorusSolenoid(int, int, float, float) */ public void drawTorusSolenoid(int faces) { drawTorusSolenoid(faces, 0.07f * radius()); } /** * Convenience function that simply calls {@code drawTorusSolenoid(6, insideRadius)}. * * @see #drawTorusSolenoid(int, int, float, float) */ public void drawTorusSolenoid(float insideRadius) { drawTorusSolenoid(6, insideRadius); } /** * Convenience function that simply calls * {@code drawTorusSolenoid(faces, 100, insideRadius, insideRadius * 1.3f)}. * * @see #drawTorusSolenoid(int, int, float, float) */ public void drawTorusSolenoid(int faces, float insideRadius) { drawTorusSolenoid(faces, 100, insideRadius, insideRadius * 1.3f); } /** * Draws a torus solenoid. Dandelion logo. * * @param faces * @param detail * @param insideRadius * @param outsideRadius */ public abstract void drawTorusSolenoid(int faces, int detail, float insideRadius, float outsideRadius); /** * Same as {@code cone(det, 0, 0, r, h);} * * @see #drawCone(int, float, float, float, float) */ public void drawCone(int det, float r, float h) { drawCone(det, 0, 0, r, h); } /** * Same as {@code cone(12, 0, 0, r, h);} * * @see #drawCone(int, float, float, float, float) */ public void drawCone(float r, float h) { drawCone(12, 0, 0, r, h); } /** * Same as {@code cone(det, 0, 0, r1, r2, h);} * * @see #drawCone(int, float, float, float, float, float) */ public void drawCone(int det, float r1, float r2, float h) { drawCone(det, 0, 0, r1, r2, h); } /** * Same as {@code cone(18, 0, 0, r1, r2, h);} * * @see #drawCone(int, float, float, float, float, float) */ public void drawCone(float r1, float r2, float h) { drawCone(18, 0, 0, r1, r2, h); } /** * Simply calls {@code drawArrow(length, 0.05f * length)} * * @see #drawArrow(float, float) */ public void drawArrow(float length) { drawArrow(length, 0.05f * length); } /** * Draws a 3D arrow along the positive Z axis. * <p> * {@code length} and {@code radius} define its geometry. * <p> * Use {@link #drawArrow(Vec, Vec, float)} to place the arrow in 3D. */ public void drawArrow(float length, float radius) { float head = 2.5f * (radius / length) + 0.1f; float coneRadiusCoef = 4.0f - 5.0f * head; drawCylinder(radius, length * (1.0f - head / coneRadiusCoef)); translate(0.0f, 0.0f, length * (1.0f - head)); drawCone(coneRadiusCoef * radius, head * length); translate(0.0f, 0.0f, -length * (1.0f - head)); } /** * Draws a 3D arrow between the 3D point {@code from} and the 3D point {@code to}, both * defined in the current world coordinate system. * * @see #drawArrow(float, float) */ public void drawArrow(Vec from, Vec to, float radius) { pushModelView(); translate(from.x(), from.y(), from.z()); applyModelView(new Quat(new Vec(0, 0, 1), Vec.subtract(to, from)).matrix()); drawArrow(Vec.subtract(to, from).magnitude(), radius); popModelView(); } /** * Convenience function that simply calls * {@code drawCross(pg3d.color(255, 255, 255), px, py, 15, 3)}. */ public void drawCross(float px, float py) { drawCross(px, py, 30); } /** * Convenience function that simply calls {@code drawFilledCircle(40, center, radius)}. * * @see #drawFilledCircle(int, Vec, float) */ public void drawFilledCircle(Vec center, float radius) { drawFilledCircle(40, center, radius); } // abstract drawing methods /** * Draws a cylinder of width {@code w} and height {@code h}, along the positive * {@code z} axis. */ public abstract void drawCylinder(float w, float h); /** * Draws a cylinder whose bases are formed by two cutting planes ({@code m} and * {@code n}), along the Camera positive {@code z} axis. * * @param detail * @param w * radius of the cylinder and h is its height * @param h * height of the cylinder * @param m * normal of the plane that intersects the cylinder at z=0 * @param n * normal of the plane that intersects the cylinder at z=h * * @see #drawCylinder(float, float) */ public abstract void drawHollowCylinder(int detail, float w, float h, Vec m, Vec n); /** * Draws a cone along the positive {@code z} axis, with its base centered at * {@code (x,y)}, height {@code h}, and radius {@code r}. * * @see #drawCone(int, float, float, float, float, float) */ public abstract void drawCone(int detail, float x, float y, float r, float h); /** * Draws a truncated cone along the positive {@code z} axis, with its base centered at * {@code (x,y)}, height {@code h} , and radii {@code r1} and {@code r2} (basis and * height respectively). * * @see #drawCone(int, float, float, float, float) */ public abstract void drawCone(int detail, float x, float y, float r1, float r2, float h); /** * Draws axes of length {@code length} which origin correspond to the world coordinate * system origin. * * @see #drawGrid(float, int) */ public abstract void drawAxes(float length); /** * Draws a grid in the XY plane, centered on (0,0,0) (defined in the current coordinate * system). * <p> * {@code size} and {@code nbSubdivisions} define its geometry. * * @see #drawAxes(float) */ public abstract void drawGrid(float size, int nbSubdivisions); /** * Draws a dotted-grid in the XY plane, centered on (0,0,0) (defined in the current * coordinate system). * <p> * {@code size} and {@code nbSubdivisions} define its geometry. * * @see #drawAxes(float) */ public abstract void drawDottedGrid(float size, int nbSubdivisions); /** * Draws the path used to interpolate the * {@link remixlab.dandelion.core.KeyFrameInterpolator#frame()} * <p> * {@code mask} controls what is drawn: If ( (mask &amp; 1) != 0 ), the position path is * drawn. If ( (mask &amp; 2) != 0 ), a camera representation is regularly drawn and if * ( (mask &amp; 4) != 0 ), oriented axes are regularly drawn. Examples: * <p> * {@code drawPath(); // Simply draws the interpolation path} <br> * {@code drawPath(3); // Draws path and cameras} <br> * {@code drawPath(5); // Draws path and axes} <br> * <p> * In the case where camera or axes are drawn, {@code nbFrames} controls the number of * objects (axes or camera) drawn between two successive keyFrames. When * {@code nbFrames = 1}, only the path KeyFrames are drawn. {@code nbFrames = 2} also * draws the intermediate orientation, etc. The maximum value is 30. {@code nbFrames} * should divide 30 so that an object is drawn for each KeyFrame. Default value is 6. * <p> * {@code scale} controls the scaling of the camera and axes drawing. A value of * {@link #radius()} should give good results. */ public abstract void drawPath(KeyFrameInterpolator kfi, int mask, int nbFrames, float scale); /** * Draws a representation of the {@code eye} in the scene. * <p> * The near and far planes are drawn as quads, the frustum is drawn using lines and the * camera up vector is represented by an arrow to disambiguate the drawing. * <p> * <b>Note:</b> The drawing of a Scene's own Scene.camera() should not be visible, but * may create artifacts due to numerical imprecisions. */ public abstract void drawEye(Eye eye); /** * Internal use. */ protected abstract void drawKFIEye(float scale); /** * Draws a rectangle on the screen showing the region where a zoom operation is taking * place. */ protected abstract void drawZoomWindowHint(); /** * Draws visual hint (a line on the screen) when a screen rotation is taking place. */ protected abstract void drawScreenRotateHint(); /** * Draws visual hint (a cross on the screen) when the * {@link remixlab.dandelion.core.Eye#anchor()} is being set. * <p> * Simply calls {@link #drawCross(float, float, float)} on * {@link remixlab.dandelion.core.Eye#projectedCoordinatesOf()} from * {@link remixlab.dandelion.core.Eye#anchor()}. * * @see #drawCross(float, float, float) */ protected abstract void drawAnchorHint(); /** * Internal use. */ protected abstract void drawPointUnderPixelHint(); /** * Draws a cross on the screen centered under pixel {@code (px, py)}, and edge of size * {@code size}. * * @see #drawAnchorHint() */ public abstract void drawCross(float px, float py, float size); /** * Draws a filled circle using screen coordinates. * * @param subdivisions * Number of triangles approximating the circle. * @param center * Circle screen center. * @param radius * Circle screen radius. */ public abstract void drawFilledCircle(int subdivisions, Vec center, float radius); /** * Draws a filled square using screen coordinates. * * @param center * Square screen center. * @param edge * Square edge length. */ public abstract void drawFilledSquare(Vec center, float edge); /** * Draws the classical shooter target on the screen. * * @param center * Center of the target on the screen * @param length * Length of the target in pixels */ public abstract void drawShooterTarget(Vec center, float length); /** * Draws all GrabberFrames' picking targets: a shooter target visual hint of * {@link remixlab.dandelion.core.GenericFrame#grabsInputThreshold()} pixels size. * * <b>Attention:</b> the target is drawn either if the iFrame is part of camera path and * keyFrame is {@code true}, or if the iFrame is not part of camera path and keyFrame is * {@code false}. */ public abstract void drawPickingTarget(GenericFrame gFrame); // end wrapper // 0. Optimization stuff // public abstract long frameCount(); // 1. Associated objects // AVATAR STUFF /** * Returns the avatar object to be tracked by the Camera when it is in Third Person * mode. * <p> * Simply returns {@code null} if no avatar has been set. */ public Trackable avatar() { return trck; } /** * Sets the avatar object to be tracked by the Camera when it is in Third Person mode. * * @see #unsetAvatar() */ public void setAvatar(Trackable t) { trck = t; if (avatar() == null) return; eye().frame().stopSpinning(); if (avatar() instanceof GenericFrame) ((GenericFrame) (avatar())).stopSpinning(); // perform small animation ;) if (eye().anyInterpolationStarted()) eye().stopInterpolations(); // eye().interpolateTo(avatar().eyeFrame());//works only when eyeFrame // scaling = magnitude GenericFrame eyeFrameCopy = avatar().trackingEyeFrame().get(); eyeFrameCopy.setMagnitude(avatar().trackingEyeFrame().scaling()); eye().interpolateTo(eyeFrameCopy); pruneBranch(eyeFrameCopy); if (avatar() instanceof GenericFrame) inputHandler().setDefaultGrabber((GenericFrame) avatar()); } /** * If there's an avatar unset it. Returns previous avatar. * * @see #setAvatar(Trackable) */ public Trackable unsetAvatar() { Trackable prev = trck; if (prev != null) { inputHandler().resetTrackedGrabber(); inputHandler().setDefaultGrabber(eye().frame()); eye().interpolateToFitScene(); } trck = null; return prev; } // 3. EYE STUFF /** * Returns the associated Eye, never {@code null}. This is the high level version of * {@link #window()} and {@link #camera()} which holds that which is common of the two. * <p> * 2D applications should simply use {@link #window()} and 3D applications should simply * use {@link #camera()}. If you plan to implement two versions of the same application * one in 2D and the other in 3D, use this method. * <p> * <b>Note</b> that not all methods defined in the Camera class are available in the Eye * class and that all methods defined in the Window class are. */ public Eye eye() { return eye; } public GenericFrame eyeFrame() { return eye.frame(); } /** * Replaces the current {@link #eye()} with {@code vp}. * <p> * The {@link #inputHandler()} will attempt to add the {@link #eyeFrame()} to all its * {@link remixlab.bias.core.InputHandler#agents()}, such as the {@link #motionAgent()} * and {@link #keyboardAgent()}. */ public void setEye(Eye vp) { if (vp == null) return; if (vp.scene() != this) return; if (!replaceEye(vp)) { eye = vp; inputHandler().addGrabber(eye.frame()); inputHandler().setDefaultGrabber(eye.frame()); } eye().setSceneRadius(radius()); eye().setSceneCenter(center()); eye().setScreenWidthAndHeight(width(), height()); showAll(); } protected boolean replaceEye(Eye vp) { if (vp == null || vp == eye()) return false; if (eye() != null) { // /* option 1 for (Agent agent : inputHandler().agents()) if (agent.defaultGrabber() != null) if (agent.defaultGrabber() == eye.frame()) { agent.addGrabber(vp.frame()); agent.setDefaultGrabber(vp.frame()); } // inputHandler().removeGrabber(eye.frame()); pruneBranch(eye.frame());// better than remove grabber // */ // option 2 // inputHandler().shiftDefaultGrabber(vp.frame(), eye.frame()); // //inputHandler().removeGrabber(eye.frame()); // pruneBranch(eye.frame());// better than remove grabber eye = vp;// eye() changed return true; } return false; } /** * If {@link #isLeftHanded()} calls {@link #setRightHanded()}, otherwise calls * {@link #setLeftHanded()}. */ public void flip() { if (isLeftHanded()) setRightHanded(); else setLeftHanded(); } /** * If {@link #is3D()} returns the associated Camera, never {@code null}. If * {@link #is2D()} throws an exception. * * @see #eye() */ public Camera camera() { if (this.is3D()) return (Camera) eye; else throw new RuntimeException("Camera type is only available in 3D"); } /** * If {@link #is3D()} sets the Camera. If {@link #is2D()} throws an exception. * * @see #setEye(Eye) */ public void setCamera(Camera cam) { if (this.is2D()) { System.out.println("Warning: Camera Type is only available in 3D"); } else setEye(cam); } /** * If {@link #is2D()} returns the associated Window, never {@code null}. If * {@link #is3D()} throws an exception. * * @see #eye() */ public Window window() { if (this.is2D()) return (Window) eye; else throw new RuntimeException("Window type is only available in 2D"); } /** * If {@link #is2D()} sets the Window. If {@link #is3D()} throws an exception. * * @see #setEye(Eye) */ public void setWindow(Window win) { if (this.is3D()) { System.out.println("Warning: Window Type is only available in 2D"); } else setEye(win); } /** * Same as {@code eye().frame().setConstraint(constraint)}. * * @see remixlab.dandelion.core.GenericFrame#setConstraint(Constraint) */ public void setEyeConstraint(Constraint constraint) { eye().frame().setConstraint(constraint); } /** * Same as {@code return eye().pointIsVisible(point)}. * * @see remixlab.dandelion.core.Eye#isPointVisible(Vec) */ public boolean isPointVisible(Vec point) { return eye().isPointVisible(point); } /** * Same as {@code return eye().ballIsVisible(center, radius)}. * * @see remixlab.dandelion.core.Eye#ballVisibility(Vec, float) */ public Eye.Visibility ballVisibility(Vec center, float radius) { return eye().ballVisibility(center, radius); } /** * Same as {@code return eye().boxIsVisible(p1, p2)}. * * @see remixlab.dandelion.core.Eye#boxVisibility(Vec, Vec) */ public Eye.Visibility boxVisibility(Vec p1, Vec p2) { return eye().boxVisibility(p1, p2); } /** * Returns {@code true} if automatic update of the camera frustum plane equations is * enabled and {@code false} otherwise. Computation of the equations is expensive and * hence is disabled by default. * * @see #toggleBoundaryEquations() * @see #disableBoundaryEquations() * @see #enableBoundaryEquations() * @see #enableBoundaryEquations(boolean) * @see remixlab.dandelion.core.Camera#updateBoundaryEquations() */ public boolean areBoundaryEquationsEnabled() { return eye().areBoundaryEquationsEnabled(); } /** * Toggles automatic update of the camera frustum plane equations every frame. * Computation of the equations is expensive and hence is disabled by default. * * @see #areBoundaryEquationsEnabled() * @see #disableBoundaryEquations() * @see #enableBoundaryEquations() * @see #enableBoundaryEquations(boolean) * @see remixlab.dandelion.core.Camera#updateBoundaryEquations() */ public void toggleBoundaryEquations() { if (areBoundaryEquationsEnabled()) disableBoundaryEquations(); else enableBoundaryEquations(); } /** * Disables automatic update of the camera frustum plane equations every frame. * Computation of the equations is expensive and hence is disabled by default. * * @see #areBoundaryEquationsEnabled() * @see #toggleBoundaryEquations() * @see #enableBoundaryEquations() * @see #enableBoundaryEquations(boolean) * @see remixlab.dandelion.core.Camera#updateBoundaryEquations() */ public void disableBoundaryEquations() { enableBoundaryEquations(false); } /** * Enables automatic update of the camera frustum plane equations every frame. * Computation of the equations is expensive and hence is disabled by default. * * @see #areBoundaryEquationsEnabled() * @see #toggleBoundaryEquations() * @see #disableBoundaryEquations() * @see #enableBoundaryEquations(boolean) * @see remixlab.dandelion.core.Camera#updateBoundaryEquations() */ public void enableBoundaryEquations() { enableBoundaryEquations(true); } /** * Enables or disables automatic update of the camera frustum plane equations every * frame according to {@code flag}. Computation of the equations is expensive and hence * is disabled by default. * * @see #areBoundaryEquationsEnabled() * @see #toggleBoundaryEquations() * @see #disableBoundaryEquations() * @see #enableBoundaryEquations() * @see remixlab.dandelion.core.Camera#updateBoundaryEquations() */ public void enableBoundaryEquations(boolean flag) { eye().enableBoundaryEquations(flag); } /** * Toggles the {@link #eye()} type between PERSPECTIVE and ORTHOGRAPHIC. */ public void toggleCameraType() { if (this.is2D()) { AbstractScene.showDepthWarning("toggleCameraType"); return; } else { if (((Camera) eye()).type() == Camera.Type.PERSPECTIVE) setCameraType(Camera.Type.ORTHOGRAPHIC); else setCameraType(Camera.Type.PERSPECTIVE); } } /** * Same as {@code return camera().isFaceBackFacing(a, b, c)}. * <p> * This method is only available in 3D. * * @see remixlab.dandelion.core.Camera#isFaceBackFacing(Vec, Vec, Vec) */ public boolean isFaceBackFacing(Vec a, Vec b, Vec c) { if (this.is2D()) { AbstractScene.showDepthWarning("isFaceBackFacing"); return false; } return camera().isFaceBackFacing(a, b, c); } /** * Same as {@code return camera().isConeBackFacing(vertex, normals)}. * <p> * This method is only available in 3D. * * @see remixlab.dandelion.core.Camera#isConeBackFacing(Vec, Vec[]) */ public boolean isConeBackFacing(Vec vertex, Vec[] normals) { if (this.is2D()) { AbstractScene.showDepthWarning("isConeBackFacing"); return false; } return camera().isConeBackFacing(vertex, normals); } /** * Same as {@code return camera().isConeBackFacing(vertex, axis, angle)}. * <p> * This method is only available in 3D. * * @see remixlab.dandelion.core.Camera#isConeBackFacing(Vec, Vec, float) */ public boolean isConeBackFacing(Vec vertex, Vec axis, float angle) { if (this.is2D()) { AbstractScene.showDepthWarning("isConeBackFacing"); return false; } return camera().isConeBackFacing(vertex, axis, angle); } /** * Returns the world coordinates of the 3D point located at {@code pixel} (x,y) on * screen. May be null if no pixel is under pixel. */ public Vec pointUnderPixel(Point pixel) { float depth = pixelDepth(pixel); Vec point = unprojectedCoordinatesOf(new Vec(pixel.x(), pixel.y(), depth)); return (depth < 1.0f) ? point : null; } /** * Same as {@code return pointUnderPixel(new Point(x, y))}. * * @see #pointUnderPixel(Point) */ public Vec pointUnderPixel(float x, float y) { return pointUnderPixel(new Point(x, y)); } /** * Returns the depth (z-value) of the object under the {@code pixel}. * <p> * The z-value ranges in [0..1] (near and far plane respectively). In 3D Note that this * value is not a linear interpolation between * {@link remixlab.dandelion.core.Camera#zNear()} and * {@link remixlab.dandelion.core.Camera#zFar()}; * {@code z = zFar() / (zFar() - zNear()) * (1.0f - zNear() / z');} where {@code z'} is * the distance from the point you project to the camera, along the * {@link remixlab.dandelion.core.Camera#viewDirection()}. See the {@code gluUnProject} * man page for details. */ public abstract float pixelDepth(Point pixel); public float pixelDepth(float x, float y) { return pixelDepth(new Point(x, y)); } /** * Same as {@link remixlab.dandelion.core.Eye#projectedCoordinatesOf(Mat, Vec)}. */ public Vec projectedCoordinatesOf(Vec src) { return eye().projectedCoordinatesOf(this.matrixHelper().projectionView(), src); } /** * If {@link remixlab.dandelion.core.MatrixHelper#isProjectionViewInverseCached()} * (cache version) returns * {@link remixlab.dandelion.core.Eye#unprojectedCoordinatesOf(Mat, Vec)} (Mat is * {@link remixlab.dandelion.core.MatrixHelper#projectionViewInverse()}). Otherwise * (non-cache version) returns * {@link remixlab.dandelion.core.Eye#unprojectedCoordinatesOf(Vec)}. */ public Vec unprojectedCoordinatesOf(Vec src) { if (isUnprojectedCoordinatesOfOptimized()) return eye().unprojectedCoordinatesOf(this.matrixHelper().projectionViewInverse(), src); else return eye().unprojectedCoordinatesOf(src); } /** * Returns the scene radius. * <p> * Convenience wrapper function that simply calls {@code camera().sceneRadius()} * * @see #setRadius(float) * @see #center() */ public float radius() { return eye().sceneRadius(); } /** * Returns the scene center. * <p> * Convenience wrapper function that simply returns {@code camera().sceneCenter()} * * @see #setCenter(Vec) {@link #radius()} */ public Vec center() { return eye().sceneCenter(); } /** * Returns the {@link remixlab.dandelion.core.Eye#anchor()}. * <p> * Convenience wrapper function that simply returns {@code eye().anchor()} * * @see #setCenter(Vec) {@link #radius()} */ public Vec anchor() { return eye().anchor(); } /** * Same as {@link remixlab.dandelion.core.Eye#setAnchor(Vec)}. */ public void setAnchor(Vec anchor) { eye().setAnchor(anchor); } /** * Sets the {@link #radius()} of the Scene. * <p> * Convenience wrapper function that simply calls * {@code camera().setSceneRadius(radius)}. * * @see #setCenter(Vec) */ public void setRadius(float radius) { eye().setSceneRadius(radius); } /** * Sets the {@link #center()} of the Scene. * <p> * Convenience wrapper function that simply calls {@code } * * @see #setRadius(float) */ public void setCenter(Vec center) { eye().setSceneCenter(center); } /** * Sets the {@link #center()} and {@link #radius()} of the Scene from the {@code min} * and {@code max} vectors. * <p> * Convenience wrapper function that simply calls * {@code camera().setSceneBoundingBox(min,max)} * * @see #setRadius(float) * @see #setCenter(Vec) */ public void setBoundingBox(Vec min, Vec max) { if (this.is2D()) System.out.println("setBoundingBox is available only in 3D. Use setBoundingRect instead"); else ((Camera) eye()).setSceneBoundingBox(min, max); } public void setBoundingRect(Vec min, Vec max) { if (this.is3D()) System.out.println("setBoundingRect is available only in 2D. Use setBoundingBox instead"); else ((Window) eye()).setSceneBoundingBox(min, max); } /** * Convenience wrapper function that simply calls {@code camera().showEntireScene()} * * @see remixlab.dandelion.core.Camera#showEntireScene() */ public void showAll() { eye().showEntireScene(); } /** * Convenience wrapper function that simply returns * {@code eye().setAnchorFromPixel(pixel)}. * <p> * Current implementation set no {@link remixlab.dandelion.core.Eye#anchor()}. Override * {@link remixlab.dandelion.core.Camera#pointUnderPixel(Point)} in your openGL based * camera for this to work. * * @see remixlab.dandelion.core.Eye#setAnchorFromPixel(Point) * @see remixlab.dandelion.core.Camera#pointUnderPixel(Point) */ public boolean setAnchorFromPixel(Point pixel) { return eye().setAnchorFromPixel(pixel); } public boolean setAnchorFromPixel(float x, float y) { return setAnchorFromPixel(new Point(x, y)); } /** * Convenience wrapper function that simply returns * {@code camera().setSceneCenterFromPixel(pixel)} * <p> * Current implementation set no {@link remixlab.dandelion.core.Camera#sceneCenter()}. * Override {@link remixlab.dandelion.core.Camera#pointUnderPixel(Point)} in your openGL * based camera for this to work. * * @see remixlab.dandelion.core.Camera#setSceneCenterFromPixel(Point) * @see remixlab.dandelion.core.Camera#pointUnderPixel(Point) */ public boolean setCenterFromPixel(Point pixel) { return eye().setSceneCenterFromPixel(pixel); } public boolean setCenterFromPixel(float x, float y) { return setCenterFromPixel(new Point(x, y)); } /** * Returns the current {@link #eye()} type. */ public final Camera.Type cameraType() { if (this.is2D()) { System.out.println("Warning: Camera Type is only available in 3D"); return null; } else return ((Camera) eye()).type(); } /** * Sets the {@link #eye()} type. */ public void setCameraType(Camera.Type type) { if (this.is2D()) { System.out.println("Warning: Camera Type is only available in 3D"); } else if (type != ((Camera) eye()).type()) ((Camera) eye()).setType(type); } // WARNINGS and EXCEPTIONS STUFF static protected HashMap<String, Object> warnings; /** * Show warning, and keep track of it so that it's only shown once. * * @param msg * the error message (which will be stored for later comparison) */ static public void showWarning(String msg) { // ignore if (warnings == null) { warnings = new HashMap<String, Object>(); } if (!warnings.containsKey(msg)) { System.err.println(msg); warnings.put(msg, new Object()); } } /** * Display a warning that the specified method is only available in 3D. * * @param method * The method name (no parentheses) */ static public void showDepthWarning(String method) { showWarning(method + "() is not available in 2d"); } /** * Display a warning that the specified method lacks implementation. */ static public void showMissingImplementationWarning(String method, String theclass) { showWarning(method + "(), should be implemented by your " + theclass + " derived class."); } /** * Display a warning that the specified method can only be implemented from a relative * bogus event. */ static public void showEventVariationWarning(String method) { showWarning(method + " can only be performed using a relative event."); } static public void showOnlyEyeWarning(String method) { showOnlyEyeWarning(method, true); } /** * Display a warning that the specified method is only available for a frame (but not an * eye-frame). */ static public void showOnlyEyeWarning(String method, boolean eye) { if (eye) showWarning(method + "() is meaningful only when frame is attached to an eye."); else showWarning(method + "() is meaningful only when frame is detached from an eye."); } /** * Display a warning that the specified method is not available under the specified * platform. */ static public void showPlatformVariationWarning(String themethod, Platform platform) { showWarning(themethod + " is not available under the " + platform + " platform."); } static public void showMinDOFsWarning(String themethod, int dofs) { showWarning(themethod + "() requires at least a " + dofs + " dofs."); } // NICE STUFF /** * Apply the local transformation defined by {@code frame}, i.e., respect to the frame * {@link remixlab.dandelion.geom.Frame#referenceFrame()}. The Frame is first translated * and then rotated around the new translated origin. * <p> * This method may be used to modify the modelview matrix from a Frame hierarchy. For * example, with this Frame hierarchy: * <p> * {@code Frame body = new Frame();} <br> * {@code Frame leftArm = new Frame();} <br> * {@code Frame rightArm = new Frame();} <br> * {@code leftArm.setReferenceFrame(body);} <br> * {@code rightArm.setReferenceFrame(body);} <br> * <p> * The associated drawing code should look like: * <p> * {@code pushModelView();} <br> * {@code applyTransformation(body);} <br> * {@code drawBody();} <br> * {@code pushModelView();} <br> * {@code applyTransformation(leftArm);} <br> * {@code drawArm();} <br> * {@code popMatrix();} <br> * {@code pushMatrix();} <br> * {@code applyTransformation(rightArm);} <br> * {@code drawArm();} <br> * {@code popModelView();} <br> * {@code popModelView();} <br> * <p> * Note the use of nested {@link #pushModelView()} and {@link #popModelView()} blocks to * represent the frame hierarchy: {@code leftArm} and {@code rightArm} are both * correctly drawn with respect to the {@code body} coordinate system. * <p> * <b>Attention:</b> When drawing a frame hierarchy as above, this method should be used * whenever possible. * * @see #applyWorldTransformation(Frame) */ public void applyTransformation(Frame frame) { if (is2D()) { translate(frame.translation().x(), frame.translation().y()); rotate(frame.rotation().angle()); scale(frame.scaling(), frame.scaling()); } else { translate(frame.translation().vec[0], frame.translation().vec[1], frame.translation().vec[2]); rotate(frame.rotation().angle(), ((Quat) frame.rotation()).axis().vec[0], ((Quat) frame.rotation()).axis().vec[1], ((Quat) frame.rotation()).axis().vec[2]); scale(frame.scaling(), frame.scaling(), frame.scaling()); } } /** * Same as {@link #applyTransformation(Frame)} but applies the global transformation * defined by the frame. */ public void applyWorldTransformation(Frame frame) { // TODO check for beta2 doing these with frames position(), orientation() // and magnitude() Frame refFrame = frame.referenceFrame(); if (refFrame != null) { applyWorldTransformation(refFrame); applyTransformation(frame); } else { applyTransformation(frame); } } /** * This method is called before the first drawing happen and should be overloaded to * initialize stuff. The default implementation is empty. * <p> * Typical usage include {@link #eye()} initialization ({@link #showAll()}) and Scene * state setup ( {@link #setAxesVisualHint(boolean)} and * {@link #setGridVisualHint(boolean)}. */ public void init() { } /** * The method that actually defines the scene. * <p> * If you build a class that inherits from Scene, this is the method you should * overload, but no if you instantiate your own Scene object (for instance, in * Processing you should just overload {@code PApplet.draw()} to define your scene). * <p> * The eye matrices set in {@link #bindMatrices()} converts from the world to the camera * coordinate systems. Thus vertices given here can then be considered as being given in * the world coordinate system. The eye is moved in this world using the mouse. This * representation is much more intuitive than a camera-centric system (which for * instance is the standard in OpenGL). */ public void proscenium() { } // GENERAL STUFF /** * Returns true if scene is left handed. Note that the scene is right handed by default. * However in proscene we set it as right handed (same as with P5). * * @see #setLeftHanded() */ public boolean isLeftHanded() { return !rightHanded; } /** * Returns true if scene is right handed. Note that the scene is right handed by * default. However in proscene we set it as right handed (same as with P5). * * @see #setRightHanded() */ public boolean isRightHanded() { return rightHanded; } /** * Set the scene as right handed. * * @see #isRightHanded() */ public void setRightHanded() { rightHanded = true; } /** * Set the scene as left handed. * * @see #isLeftHanded() */ public void setLeftHanded() { rightHanded = false; } /** * Returns {@code true} if this Scene is associated to an off-screen renderer and * {@code false} otherwise. */ public boolean isOffscreen() { return offscreen; } /** * @return true if the scene is 2D. */ public boolean is2D() { return !is3D(); } /** * @return true if the scene is 3D. */ public abstract boolean is3D(); // dimensions /** * Returns the {@link #width()} to {@link #height()} aspect ratio of the display window. */ public float aspectRatio() { return (float) width() / (float) height(); } /** * Returns true grid is dotted. */ public boolean gridIsDotted() { return dottedGrid; } /** * Sets the drawing of the grid visual hint as dotted or not. */ public void setDottedGrid(boolean dotted) { dottedGrid = dotted; } // ABSTRACT STUFF /** * @return width of the screen window. */ public abstract int width(); /** * @return height of the screen window. */ public abstract int height(); /** * Disables z-buffer. */ public abstract void disableDepthTest(); /** * Enables z-buffer. */ public abstract void enableDepthTest(); }
29.13735
120
0.651622
dffb5606dc25204b00b135ca7265bcea0114da4d
1,202
package org.willemsens.player.persistence.entities; import android.arch.persistence.room.Entity; import android.arch.persistence.room.ForeignKey; import android.arch.persistence.room.Index; import android.arch.persistence.room.PrimaryKey; import android.support.annotation.NonNull; import java.util.Objects; @Entity(foreignKeys = { @ForeignKey(entity = Image.class, parentColumns = "id", childColumns = "imageId")}, indices = { @Index(value = {"name"}, unique = true), @Index(value = {"imageId"}) }) public class Artist implements Comparable<Artist> { @PrimaryKey(autoGenerate = true) public long id; @NonNull public String name; public Long imageId; public Artist(@NonNull String name) { this.name = name; } @Override public int compareTo(@NonNull Artist that) { return this.name.compareTo(that.name); } @Override public boolean equals(Object o) { return this == o || o instanceof Artist && this.id == ((Artist) o).id; } @Override public int hashCode() { return Objects.hash(id); } }
25.041667
78
0.618968
764e96bb0fdd42fe695fdaf289ead00f9531e7a6
123
package com.example.designpattern.creationalpattern.builderpattern.makefastfood; interface Packing { String pack(); }
20.5
80
0.804878
72866fd0f04bb6fae91a9ee93b7ce25b5210c03e
15,924
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.couchbase; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ExtendedPropertyConfigurerGetter; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class CouchbaseEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { CouchbaseEndpoint target = (CouchbaseEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionalhosts": case "additionalHosts": target.setAdditionalHosts(property(camelContext, java.lang.String.class, value)); return true; case "autostartidforinserts": case "autoStartIdForInserts": target.setAutoStartIdForInserts(property(camelContext, boolean.class, value)); return true; case "backofferrorthreshold": case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true; case "backoffidlethreshold": case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true; case "backoffmultiplier": case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "bucket": target.setBucket(property(camelContext, java.lang.String.class, value)); return true; case "collection": target.setCollection(property(camelContext, java.lang.String.class, value)); return true; case "connecttimeout": case "connectTimeout": target.setConnectTimeout(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "consumerprocessedstrategy": case "consumerProcessedStrategy": target.setConsumerProcessedStrategy(property(camelContext, java.lang.String.class, value)); return true; case "delay": target.setDelay(property(camelContext, long.class, value)); return true; case "descending": target.setDescending(property(camelContext, boolean.class, value)); return true; case "designdocumentname": case "designDocumentName": target.setDesignDocumentName(property(camelContext, java.lang.String.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "fulldocument": case "fullDocument": target.setFullDocument(property(camelContext, boolean.class, value)); return true; case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true; case "initialdelay": case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true; case "key": target.setKey(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "limit": target.setLimit(property(camelContext, int.class, value)); return true; case "operation": target.setOperation(property(camelContext, java.lang.String.class, value)); return true; case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true; case "persistto": case "persistTo": target.setPersistTo(property(camelContext, int.class, value)); return true; case "pollstrategy": case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true; case "producerretryattempts": case "producerRetryAttempts": target.setProducerRetryAttempts(property(camelContext, int.class, value)); return true; case "producerretrypause": case "producerRetryPause": target.setProducerRetryPause(property(camelContext, int.class, value)); return true; case "querytimeout": case "queryTimeout": target.setQueryTimeout(property(camelContext, java.time.Duration.class, value).toMillis()); return true; case "rangeendkey": case "rangeEndKey": target.setRangeEndKey(property(camelContext, java.lang.String.class, value)); return true; case "rangestartkey": case "rangeStartKey": target.setRangeStartKey(property(camelContext, java.lang.String.class, value)); return true; case "repeatcount": case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true; case "replicateto": case "replicateTo": target.setReplicateTo(property(camelContext, int.class, value)); return true; case "runlogginglevel": case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true; case "scheduledexecutorservice": case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true; case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true; case "schedulerproperties": case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true; case "scope": target.setScope(property(camelContext, java.lang.String.class, value)); return true; case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true; case "skip": target.setSkip(property(camelContext, int.class, value)); return true; case "startscheduler": case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true; case "startingidforinsertsfrom": case "startingIdForInsertsFrom": target.setStartingIdForInsertsFrom(property(camelContext, long.class, value)); return true; case "timeunit": case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "usefixeddelay": case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true; case "username": target.setUsername(property(camelContext, java.lang.String.class, value)); return true; case "viewname": case "viewName": target.setViewName(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "additionalhosts": case "additionalHosts": return java.lang.String.class; case "autostartidforinserts": case "autoStartIdForInserts": return boolean.class; case "backofferrorthreshold": case "backoffErrorThreshold": return int.class; case "backoffidlethreshold": case "backoffIdleThreshold": return int.class; case "backoffmultiplier": case "backoffMultiplier": return int.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "bucket": return java.lang.String.class; case "collection": return java.lang.String.class; case "connecttimeout": case "connectTimeout": return long.class; case "consumerprocessedstrategy": case "consumerProcessedStrategy": return java.lang.String.class; case "delay": return long.class; case "descending": return boolean.class; case "designdocumentname": case "designDocumentName": return java.lang.String.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "fulldocument": case "fullDocument": return boolean.class; case "greedy": return boolean.class; case "initialdelay": case "initialDelay": return long.class; case "key": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "limit": return int.class; case "operation": return java.lang.String.class; case "password": return java.lang.String.class; case "persistto": case "persistTo": return int.class; case "pollstrategy": case "pollStrategy": return org.apache.camel.spi.PollingConsumerPollStrategy.class; case "producerretryattempts": case "producerRetryAttempts": return int.class; case "producerretrypause": case "producerRetryPause": return int.class; case "querytimeout": case "queryTimeout": return long.class; case "rangeendkey": case "rangeEndKey": return java.lang.String.class; case "rangestartkey": case "rangeStartKey": return java.lang.String.class; case "repeatcount": case "repeatCount": return long.class; case "replicateto": case "replicateTo": return int.class; case "runlogginglevel": case "runLoggingLevel": return org.apache.camel.LoggingLevel.class; case "scheduledexecutorservice": case "scheduledExecutorService": return java.util.concurrent.ScheduledExecutorService.class; case "scheduler": return java.lang.Object.class; case "schedulerproperties": case "schedulerProperties": return java.util.Map.class; case "scope": return java.lang.String.class; case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": return boolean.class; case "skip": return int.class; case "startscheduler": case "startScheduler": return boolean.class; case "startingidforinsertsfrom": case "startingIdForInsertsFrom": return long.class; case "timeunit": case "timeUnit": return java.util.concurrent.TimeUnit.class; case "usefixeddelay": case "useFixedDelay": return boolean.class; case "username": return java.lang.String.class; case "viewname": case "viewName": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { CouchbaseEndpoint target = (CouchbaseEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "additionalhosts": case "additionalHosts": return target.getAdditionalHosts(); case "autostartidforinserts": case "autoStartIdForInserts": return target.isAutoStartIdForInserts(); case "backofferrorthreshold": case "backoffErrorThreshold": return target.getBackoffErrorThreshold(); case "backoffidlethreshold": case "backoffIdleThreshold": return target.getBackoffIdleThreshold(); case "backoffmultiplier": case "backoffMultiplier": return target.getBackoffMultiplier(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "bucket": return target.getBucket(); case "collection": return target.getCollection(); case "connecttimeout": case "connectTimeout": return target.getConnectTimeout(); case "consumerprocessedstrategy": case "consumerProcessedStrategy": return target.getConsumerProcessedStrategy(); case "delay": return target.getDelay(); case "descending": return target.isDescending(); case "designdocumentname": case "designDocumentName": return target.getDesignDocumentName(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "fulldocument": case "fullDocument": return target.isFullDocument(); case "greedy": return target.isGreedy(); case "initialdelay": case "initialDelay": return target.getInitialDelay(); case "key": return target.getKey(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "limit": return target.getLimit(); case "operation": return target.getOperation(); case "password": return target.getPassword(); case "persistto": case "persistTo": return target.getPersistTo(); case "pollstrategy": case "pollStrategy": return target.getPollStrategy(); case "producerretryattempts": case "producerRetryAttempts": return target.getProducerRetryAttempts(); case "producerretrypause": case "producerRetryPause": return target.getProducerRetryPause(); case "querytimeout": case "queryTimeout": return target.getQueryTimeout(); case "rangeendkey": case "rangeEndKey": return target.getRangeEndKey(); case "rangestartkey": case "rangeStartKey": return target.getRangeStartKey(); case "repeatcount": case "repeatCount": return target.getRepeatCount(); case "replicateto": case "replicateTo": return target.getReplicateTo(); case "runlogginglevel": case "runLoggingLevel": return target.getRunLoggingLevel(); case "scheduledexecutorservice": case "scheduledExecutorService": return target.getScheduledExecutorService(); case "scheduler": return target.getScheduler(); case "schedulerproperties": case "schedulerProperties": return target.getSchedulerProperties(); case "scope": return target.getScope(); case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle(); case "skip": return target.getSkip(); case "startscheduler": case "startScheduler": return target.isStartScheduler(); case "startingidforinsertsfrom": case "startingIdForInsertsFrom": return target.getStartingIdForInsertsFrom(); case "timeunit": case "timeUnit": return target.getTimeUnit(); case "usefixeddelay": case "useFixedDelay": return target.isUseFixedDelay(); case "username": return target.getUsername(); case "viewname": case "viewName": return target.getViewName(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "schedulerproperties": case "schedulerProperties": return java.lang.Object.class; default: return null; } } }
56.070423
173
0.702022
7642e710b1619037f7cfe3d013ba6f0cbb80b778
6,034
package com.sequenceiq.redbeams.configuration; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.SQLException; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.core.env.Environment; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.sequenceiq.cloudbreak.common.database.BatchProperties; import com.sequenceiq.cloudbreak.common.database.JpaPropertiesFacory; import com.sequenceiq.cloudbreak.common.tx.CircuitBreakerType; import com.sequenceiq.cloudbreak.util.DatabaseUtil; import com.sequenceiq.flow.ha.NodeConfig; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; @Configuration @EnableTransactionManagement public class DatabaseConfig { @Value("${redbeams.db.env.user:}") private String dbUser; @Value("${redbeams.db.env.pass:}") private String dbPassword; @Value("${redbeams.db.env.db:}") private String dbName; @Value("${redbeams.db.env.poolsize:10}") private int poolSize; @Value("${redbeams.db.env.connectiontimeout:30}") private long connectionTimeout; @Value("${redbeams.db.env.minidle:2}") private int minimumIdle; @Value("${redbeams.db.env.idletimeout:10}") private long idleTimeout; @Value("${redbeams.db.env.schema:" + DatabaseUtil.DEFAULT_SCHEMA_NAME + '}') private String dbSchemaName; @Value("${redbeams.db.env.ssl:}") private boolean ssl; @Value("#{'${redbeams.cert.dir:}/${redbeams.db.env.cert.file:}'}") private String certFile; @Value("${redbeams.hbm2ddl.strategy:validate}") private String hbm2ddlStrategy; @Value("${redbeams.hibernate.debug:false}") private boolean debug; @Value("${redbeams.hibernate.circuitbreaker:LOG}") private CircuitBreakerType circuitBreakerType; @Inject @Named("databaseAddress") private String databaseAddress; @Inject private NodeConfig nodeConfig; @Inject private Environment environment; @Bean public DataSource dataSource() throws SQLException { DatabaseUtil.createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName); HikariConfig config = new HikariConfig(); if (ssl && Files.exists(Paths.get(certFile))) { config.addDataSourceProperty("ssl", "true"); config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory"); config.addDataSourceProperty("sslfactoryarg", "file://" + certFile); } if (nodeConfig.isNodeIdSpecified()) { config.addDataSourceProperty("ApplicationName", nodeConfig.getId()); } config.setDriverClassName("io.opentracing.contrib.jdbc.TracingDriver"); config.setJdbcUrl(String.format("jdbc:tracing:postgresql://%s/%s?currentSchema=%s&traceWithActiveSpanOnly=true", databaseAddress, dbName, dbSchemaName)); config.setUsername(dbUser); config.setPassword(dbPassword); config.setMaximumPoolSize(poolSize); config.setMinimumIdle(minimumIdle); config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout)); config.setIdleTimeout(MINUTES.toMillis(idleTimeout)); return new HikariDataSource(config); } @Bean public PlatformTransactionManager transactionManager() throws SQLException { JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(); jpaTransactionManager.setEntityManagerFactory(entityManagerFactory()); jpaTransactionManager.afterPropertiesSet(); return jpaTransactionManager; } @Bean @DependsOn("databaseUpMigration") public EntityManagerFactory entityManagerFactory() throws SQLException { LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean(); entityManagerFactory.setPackagesToScan("com.sequenceiq.redbeams", "com.sequenceiq.flow", "com.sequenceiq.cloudbreak.ha"); entityManagerFactory.setDataSource(dataSource()); entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter()); entityManagerFactory.setJpaProperties(JpaPropertiesFacory.create(hbm2ddlStrategy, debug, dbSchemaName, circuitBreakerType, createBatchProperties())); entityManagerFactory.afterPropertiesSet(); return entityManagerFactory.getObject(); } @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); hibernateJpaVendorAdapter.setShowSql(true); hibernateJpaVendorAdapter.setDatabase(Database.POSTGRESQL); return hibernateJpaVendorAdapter; } private BatchProperties createBatchProperties() { return new BatchProperties(environment.getProperty("spring.jpa.properties.hibernate.jdbc.batch_size", Integer.class), environment.getProperty("spring.jpa.properties.hibernate.order_inserts", Boolean.class), environment.getProperty("spring.jpa.properties.hibernate.order_updates", Boolean.class), environment.getProperty("spring.jpa.properties.hibernate.jdbc.batch_versioned_data", Boolean.class)); } }
40.496644
161
0.755718
fbe461a9bdda414a945b4f7219ec4e88e8d317c9
11,137
package com.alibaba.jstorm.task.execute.spout; import backtype.storm.task.ICollectorCallback; import backtype.storm.task.TopologyContext; import backtype.storm.tuple.*; import backtype.storm.utils.DisruptorQueue; import com.alibaba.jstorm.common.metric.AsmGauge; import com.alibaba.jstorm.metric.*; import com.alibaba.jstorm.task.Task; import com.alibaba.jstorm.task.TaskTransfer; import com.alibaba.jstorm.task.acker.Acker; import com.alibaba.jstorm.task.comm.TaskSendTargets; import com.alibaba.jstorm.task.comm.TupleInfo; import com.alibaba.jstorm.task.comm.UnanchoredSend; import com.alibaba.jstorm.task.execute.BatchCollector; import com.alibaba.jstorm.task.execute.MsgInfo; import com.alibaba.jstorm.utils.JStormUtils; import com.alibaba.jstorm.utils.Pair; import com.alibaba.jstorm.utils.TimeOutMap; import com.alibaba.jstorm.utils.TimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * @author xiaojian.fxj * @since 2.1.1 */ public class SpoutBatchCollector extends SpoutCollector { private static Logger LOG = LoggerFactory.getLogger(SpoutBatchCollector.class); protected BatchCollector batchCollector; protected int batchSize; private CallIntervalGauge timeIntervalGauge; private final Map<Integer, Map<String, List<Object>>> pendingSendMsgs = new HashMap<Integer, Map<String, List<Object>>>(); public SpoutBatchCollector(Task task, TimeOutMap<Long, TupleInfo> pending, DisruptorQueue disruptorAckerQueue) { super(task, pending, disruptorAckerQueue); String componentId = topology_context.getThisComponentId(); timeIntervalGauge = new CallIntervalGauge(); JStormMetrics.registerTaskMetric(MetricUtils.taskMetricName(task.getTopologyId(), componentId, task.getTaskId(), MetricDef.TASK_BATCH_INTERVAL_TIME, MetricType.GAUGE), new AsmGauge(timeIntervalGauge)); batchCollector = new BatchCollector(task_id, componentId, storm_conf) { public void pushAndSend(String streamId, List<Object> tuple, Integer outTaskId, Collection<Tuple> anchors, Object messageId, Long rootId, ICollectorCallback callback) { if (outTaskId != null) { synchronized (directBatches) { List<MsgInfo> batchTobeFlushed = addToBatches(outTaskId.toString() + "-" + streamId, directBatches, streamId, tuple, outTaskId, messageId, rootId, batchSize, callback); if (batchTobeFlushed != null && batchTobeFlushed.size() > 0) { timeIntervalGauge.incrementAndGet(); sendBatch(streamId, (outTaskId != null ? outTaskId.toString() : null), batchTobeFlushed); } } } else { synchronized (streamToBatches) { List<MsgInfo> batchTobeFlushed = addToBatches(streamId, streamToBatches, streamId, tuple, outTaskId, messageId, rootId, batchSize, callback); if (batchTobeFlushed != null && batchTobeFlushed.size() > 0) { timeIntervalGauge.incrementAndGet(); sendBatch(streamId, (outTaskId != null ? outTaskId.toString() : null), batchTobeFlushed); } } } } public synchronized void flush() { synchronized (streamToBatches) { for (Map.Entry<String, List<MsgInfo>> entry : streamToBatches.entrySet()) { List<MsgInfo> batch = streamToBatches.put(entry.getKey(), null); if (batch != null && batch.size() > 0) { sendBatch(entry.getKey(), null, batch); } } } synchronized (directBatches) { for (Map.Entry<String, List<MsgInfo>> entry : directBatches.entrySet()) { List<MsgInfo> batch = directBatches.put(entry.getKey(), null); if (batch != null && batch.size() > 0) { // TaskId-StreamId --> [taskId, streamId] String[] strings = entry.getKey().split("-", 2); sendBatch(strings[1], strings[0], batch); } } } } }; batchSize = batchCollector.getConfigBatchSize(); } /** * @return if size of pending batch is bigger than the configured one, return the batch for sending, otherwise, return null */ private List<Object> addToPendingSendBatch(int targetTask, String streamId, List<Object> values) { Map<String, List<Object>> streamToBatch = pendingSendMsgs.get(targetTask); if (streamToBatch == null) { streamToBatch = new HashMap<String, List<Object>>(); pendingSendMsgs.put(targetTask, streamToBatch); } List<Object> batch = streamToBatch.get(streamId); if (batch == null) { batch = new ArrayList<Object>(); streamToBatch.put(streamId, batch); } batch.addAll(values); if (batch.size() >= batchSize) { return batch; } else { return null; } } protected List<Integer> sendSpoutMsg(String outStreamId, List<Object> values, Object messageId, Integer outTaskId, ICollectorCallback callback) { /*java.util.List<Integer> outTasks = null; // LOG.info("spout push message to " + out_stream_id); List<MsgInfo> batchTobeFlushed = batchCollector.push(outStreamId, values, outTaskId, null, messageId, getRootId(messageId), callback); if (batchTobeFlushed != null && batchTobeFlushed.size() > 0) { outTasks = sendBatch(outStreamId, (outTaskId != null ? outTaskId.toString() : null), batchTobeFlushed); } return outTasks;*/ batchCollector.pushAndSend(outStreamId, values, outTaskId, null, messageId, getRootId(messageId), callback); return null; } public List<Integer> sendBatch(String outStreamId, String outTaskId, List<MsgInfo> batchTobeFlushed) { long startTime = emitTotalTimer.getTime(); try { List<Integer> ret = null; Map<Object, List<MsgInfo>> outTasks; if (outTaskId != null) { outTasks = sendTargets.getBatch(Integer.valueOf(outTaskId), outStreamId, batchTobeFlushed); } else { outTasks = sendTargets.getBatch(outStreamId, batchTobeFlushed); } if (outTasks == null || outTasks.size() == 0) { // don't need send tuple to other task return new ArrayList<Integer>(); } Map<Long, MsgInfo> ackBatch = new HashMap<Long, MsgInfo>(); for (Map.Entry<Object, List<MsgInfo>> entry : outTasks.entrySet()) { Object target = entry.getKey(); List<Integer> tasks = (target instanceof Integer) ? JStormUtils.mk_list((Integer) target) : ((List<Integer>) target); List<MsgInfo> batch = entry.getValue(); for(int i = 0; i < tasks.size(); i++){ Integer t = tasks.get(i); List<Object> batchValues = new ArrayList<Object>(); for (MsgInfo msg : batch) { SpoutMsgInfo msgInfo = (SpoutMsgInfo) msg; Pair<MessageId, List<Object>> pair = new Pair<MessageId, List<Object>>(getMessageId(msgInfo, ackBatch), msgInfo.values); batchValues.add(pair); } TupleImplExt batchTuple = new TupleImplExt(topology_context, batchValues, task_id, outStreamId, null); batchTuple.setTargetTaskId(t); batchTuple.setBatchTuple(true); transfer_fn.transfer(batchTuple); } for (MsgInfo msg : batch) { if (msg.callback != null) { msg.callback.execute(outStreamId, tasks, msg.values); } } } if (ackBatch.size() > 0) { sendBatch(Acker.ACKER_INIT_STREAM_ID, null, new ArrayList<MsgInfo>(ackBatch.values())); } return ret; } finally { emitTotalTimer.updateTime(startTime); } } protected MessageId getMessageId(SpoutMsgInfo msg, Map<Long, MsgInfo> ackBatch) { MessageId msgId = null; if (msg.rootId != null) { Long as = MessageId.generateId(random); msgId = MessageId.makeRootId(msg.rootId, as); MsgInfo msgInfo = ackBatch.get(msg.rootId); List<Object> ackerTuple; if (msgInfo == null) { TupleInfo info = new TupleInfo(); info.setStream(msg.streamId); info.setValues(msg.values); info.setMessageId(msg.messageId); info.setTimestamp(System.currentTimeMillis()); pending.putHead(msg.rootId, info); ackerTuple = JStormUtils.mk_list((Object) msg.rootId, JStormUtils.bit_xor_vals(as), task_id); msgInfo = new SpoutMsgInfo(Acker.ACKER_INIT_STREAM_ID, ackerTuple, null, null, null, null); ackBatch.put(msg.rootId, msgInfo); } else { ackerTuple = msgInfo.values; ackerTuple.set(1, JStormUtils.bit_xor_vals(ackerTuple.get(1), as)); } } return msgId; } private List<MsgInfo> addToBatches(String key, Map<String, List<MsgInfo>> batches, String streamId, List<Object> tuple, Integer outTaskId, Object messageId, Long rootId, int batchSize, ICollectorCallback callback) { List<MsgInfo> batch = batches.get(key); if (batch == null) { batch = new ArrayList<MsgInfo>(); batches.put(key, batch); } batch.add(new SpoutMsgInfo(streamId, tuple, outTaskId, messageId, rootId, callback)); if (batch.size() > batchSize) { List<MsgInfo> ret = batch; batches.put(key, null); return ret; } else { return null; } } class SpoutMsgInfo extends MsgInfo { public Long rootId; public Object messageId; public SpoutMsgInfo(String streamId, List<Object> values, Integer outTaskId, Object messageId, Long rootId, ICollectorCallback callback) { super(streamId, values, outTaskId, callback); this.messageId = messageId; this.rootId = rootId; } } @Override public void flush() { batchCollector.flush(); } }
42.185606
181
0.588668
8a6f971a19fc67b43c100f1b23d2deee4e8d7969
5,620
/**************************************************************************** * Copyright (c) 2007 Composent, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Composent, Inc. - initial API and implementation *****************************************************************************/ package org.eclipse.ecf.internal.example.collab.ui.hyperlink; import org.eclipse.ecf.example.collab.share.EclipseCollabSharedObject.SharedMarker; import org.eclipse.jface.text.*; import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector; import org.eclipse.jface.text.hyperlink.IHyperlink; public class EclipseCollabHyperlinkDetector extends AbstractHyperlinkDetector { //$NON-NLS-1$ public static final String SHARE_FILE_HYPERLINK_END = "/>"; //$NON-NLS-1$ public static final String SHARE_FILE_HYPERLINK_START = "<open file=\""; //$NON-NLS-1$ public static final String SHARE_FILE_HYPERLINK_SELECTION = " selection="; /* (non-Javadoc) * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean) */ public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { if (region == null || textViewer == null) return null; final IDocument document = textViewer.getDocument(); if (document == null) return null; final int offset = region.getOffset(); IRegion lineInfo; String line; try { lineInfo = document.getLineInformationOfOffset(offset); line = document.get(lineInfo.getOffset(), lineInfo.getLength()); } catch (final BadLocationException ex) { return null; } final IRegion detectedRegion = detectSubRegion(lineInfo, line); if (detectedRegion == null) return null; final int detectedStart = detectedRegion.getOffset() - lineInfo.getOffset(); final String substring = line.substring(detectedStart, detectedStart + detectedRegion.getLength()); final String fileName = detectFileName(substring); if (fileName == null) return null; final Selection selection = detectSelection(substring); return new IHyperlink[] { new EclipseCollabHyperlink(detectedRegion, fileName, selection) }; } private Selection detectSelection(String linkString) { final int beginIndex = linkString.indexOf(SHARE_FILE_HYPERLINK_SELECTION); if (beginIndex == -1) return null; final int endIndex = linkString.indexOf(SHARE_FILE_HYPERLINK_END); if (endIndex == -1) return null; // should have syntax start-end final String selection = linkString.substring(beginIndex + SHARE_FILE_HYPERLINK_SELECTION.length(), endIndex); //$NON-NLS-1$ final int dashIndex = selection.indexOf("-"); if (dashIndex == -1) return null; try { final int start = Integer.parseInt(selection.substring(0, dashIndex)); final int end = Integer.parseInt(selection.substring(dashIndex + 1)); return new Selection(start, end); } catch (final NumberFormatException e) { return null; } } class Selection { int start; int end; public Selection(int start, int end) { this.start = start; this.end = end; } public int getStart() { return start; } public int getEnd() { return end; } } private String detectFileName(String substring) { //$NON-NLS-1$ final int startIndex = substring.indexOf("\""); if (startIndex == -1) return null; //$NON-NLS-1$ final int endIndex = substring.indexOf("\"", startIndex + 1); if (endIndex == -1) return null; return substring.substring(startIndex + 1, endIndex); } protected IRegion detectSubRegion(IRegion lineInfo, String fromLine) { final int startIndex = fromLine.indexOf(SHARE_FILE_HYPERLINK_START); if (startIndex == -1) return null; // got one...look for terminator after final int endIndex = fromLine.indexOf(SHARE_FILE_HYPERLINK_END, startIndex); if (endIndex == -1) return null; return new Region(lineInfo.getOffset() + startIndex, (endIndex - startIndex) + SHARE_FILE_HYPERLINK_END.length()); } public static String createDisplayStringForEditorOpen(String resourceName, SharedMarker marker) { final StringBuffer se = new StringBuffer(EclipseCollabHyperlinkDetector.SHARE_FILE_HYPERLINK_START); //$NON-NLS-1$ se.append(resourceName).append("\""); if (marker != null) { final int start = marker.getOffset().intValue(); final int length = marker.getLength().intValue(); if (length > 0) { se.append(EclipseCollabHyperlinkDetector.SHARE_FILE_HYPERLINK_SELECTION); //$NON-NLS-1$ se.append(start).append("-").append(//$NON-NLS-1$ start + length); } } se.append(EclipseCollabHyperlinkDetector.SHARE_FILE_HYPERLINK_END); return se.toString(); } }
39.577465
154
0.624911
157fbaf6e6ae5ae4eaf254d12af3705605820417
11,112
/* * This file is generated by jOOQ. */ package org.killbill.billing.plugin.mtnmomo.dao.gen.tables; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Index; import org.jooq.Name; import org.jooq.Record; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.TableOptions; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; import org.jooq.types.ULong; import org.killbill.billing.plugin.mtnmomo.dao.gen.Indexes; import org.killbill.billing.plugin.mtnmomo.dao.gen.Keys; import org.killbill.billing.plugin.mtnmomo.dao.gen.Killbill; import org.killbill.billing.plugin.mtnmomo.dao.gen.tables.records.MtnMomoPaymentMethodsRecord; import org.killbill.billing.plugin.mtnmomo.dao.gen.tables.records.MtnMomoResponsesRecord; /** * This class is generated by jOOQ. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class MtnMomoResponses extends TableImpl<MtnMomoResponsesRecord> { private static final long serialVersionUID = -393310045; /** * The reference instance of <code>killbill.MTNMOMO_RESPONSES</code> */ public static final MtnMomoResponses MTNMOMO_RESPONSES = new MtnMomoResponses(); /** * The class holding records for this type */ @Override public Class<MtnMomoResponsesRecord> getRecordType() { return MtnMomoResponsesRecord.class; } /** * The column <code>killbill.MTNMOMO_RESPONSES.record_id</code>. */ public final TableField<MtnMomoResponsesRecord, ULong> RECORD_ID = createField(DSL.name("record_id"), org.jooq.impl.SQLDataType.BIGINTUNSIGNED.nullable(false).identity(true), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.kb_account_id</code>. */ public final TableField<MtnMomoResponsesRecord, String> KB_ACCOUNT_ID = createField(DSL.name("kb_account_id"), org.jooq.impl.SQLDataType.CHAR(36).nullable(false), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.kb_payment_id</code>. */ public final TableField<MtnMomoResponsesRecord, String> KB_PAYMENT_ID = createField(DSL.name("kb_payment_id"), org.jooq.impl.SQLDataType.CHAR(36).nullable(false), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.kb_payment_transaction_id</code>. */ public final TableField<MtnMomoResponsesRecord, String> KB_PAYMENT_TRANSACTION_ID = createField(DSL.name("kb_payment_transaction_id"), org.jooq.impl.SQLDataType.CHAR(36).nullable(false), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.transaction_type</code>. */ public final TableField<MtnMomoResponsesRecord, String> TRANSACTION_TYPE = createField(DSL.name("transaction_type"), org.jooq.impl.SQLDataType.VARCHAR(32).nullable(false), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.amount</code>. */ public final TableField<MtnMomoResponsesRecord, BigDecimal> AMOUNT = createField(DSL.name("amount"), org.jooq.impl.SQLDataType.DECIMAL(15, 9), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.currency</code>. */ public final TableField<MtnMomoResponsesRecord, String> CURRENCY = createField(DSL.name("currency"), org.jooq.impl.SQLDataType.CHAR(3), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.psp_result</code>. */ // public final TableField<MtnMomoResponsesRecord, String> PSP_RESULT = createField(DSL.name("psp_result"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.psp_reference</code>. */ // public final TableField<MtnMomoResponsesRecord, String> PSP_REFERENCE = createField(DSL.name("psp_reference"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.auth_code</code>. */ public final TableField<MtnMomoResponsesRecord, String> STATUS = createField(DSL.name("status"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.result_code</code>. */ public final TableField<MtnMomoResponsesRecord, String> RESULT_CODE = createField(DSL.name("result_code"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.refusal_reason</code>. */ // public final TableField<MtnMomoResponsesRecord, String> REFUSAL_REASON = createField(DSL.name("refusal_reason"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.reference</code>. */ // public final TableField<MtnMomoResponsesRecord, String> REFERENCE = createField(DSL.name("reference"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.psp_error_codes</code>. */ // public final TableField<MtnMomoResponsesRecord, String> PSP_ERROR_CODES = createField(DSL.name("psp_error_codes"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.payment_internal_ref</code>. */ public final TableField<MtnMomoResponsesRecord, String> PAYMENT_INTERNAL_REF = createField(DSL.name("payment_internal_ref"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.form_url</code>. */ // public final TableField<MtnMomoResponsesRecord, String> FORM_URL = createField(DSL.name("form_url"), org.jooq.impl.SQLDataType.VARCHAR(1024), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.dcc_amount</code>. */ // public final TableField<MtnMomoResponsesRecord, BigDecimal> DCC_AMOUNT = createField(DSL.name("dcc_amount"), org.jooq.impl.SQLDataType.DECIMAL(15, 9), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.dcc_currency</code>. */ // public final TableField<MtnMomoResponsesRecord, String> DCC_CURRENCY = createField(DSL.name("dcc_currency"), org.jooq.impl.SQLDataType.CHAR(3), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.dcc_signature</code>. */ // public final TableField<MtnMomoResponsesRecord, String> DCC_SIGNATURE = createField(DSL.name("dcc_signature"), org.jooq.impl.SQLDataType.VARCHAR(64), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.issuer_url</code>. */ // public final TableField<MtnMomoResponsesRecord, String> ISSUER_URL = createField(DSL.name("issuer_url"), org.jooq.impl.SQLDataType.VARCHAR(1024), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.md</code>. */ // public final TableField<MtnMomoResponsesRecord, String> MD = createField(DSL.name("md"), org.jooq.impl.SQLDataType.CLOB, this, ""); public final TableField<MtnMomoResponsesRecord, String> PAYER_MESSAGE = createField(DSL.name("payer_message"), org.jooq.impl.SQLDataType.VARCHAR(255), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.pa_request</code>. */ // public final TableField<MtnMomoResponsesRecord, String> PA_REQUEST = createField(DSL.name("pa_request"), org.jooq.impl.SQLDataType.CLOB, this, ""); public final TableField<MtnMomoResponsesRecord, String> PAYEE_NOTE = createField(DSL.name("payee_note"), org.jooq.impl.SQLDataType.VARCHAR(255), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.pa_request</code>. */ // public final TableField<MtnMomoResponsesRecord, String> PA_REQUEST = createField(DSL.name("pa_request"), org.jooq.impl.SQLDataType.CLOB, this, ""); public final TableField<MtnMomoResponsesRecord, String> REASON = createField(DSL.name("reason"), org.jooq.impl.SQLDataType.VARCHAR(255), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.additional_data</code>. */ public final TableField<MtnMomoResponsesRecord, String> ADDITIONAL_DATA = createField(DSL.name("additional_data"), org.jooq.impl.SQLDataType.CLOB, this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.created_date</code>. */ public final TableField<MtnMomoResponsesRecord, LocalDateTime> CREATED_DATE = createField(DSL.name("created_date"), org.jooq.impl.SQLDataType.LOCALDATETIME.nullable(false), this, ""); /** * The column <code>killbill.MTNMOMO_RESPONSES.kb_tenant_id</code>. */ public final TableField<MtnMomoResponsesRecord, String> KB_TENANT_ID = createField(DSL.name("kb_tenant_id"), org.jooq.impl.SQLDataType.CHAR(36).nullable(false), this, ""); /** * Create a <code>killbill.MTNMOMO_RESPONSES</code> table reference */ public MtnMomoResponses() { this(DSL.name("mtnmomo_responses"), null); } /** * Create an aliased <code>killbill.MTNMOMO_RESPONSES</code> table reference */ public MtnMomoResponses(String alias) { this(DSL.name(alias), MTNMOMO_RESPONSES); } /** * Create an aliased <code>killbill.MTNMOMO_RESPONSES</code> table reference */ public MtnMomoResponses(Name alias) { this(alias, MTNMOMO_RESPONSES); } private MtnMomoResponses(Name alias, Table<MtnMomoResponsesRecord> aliased) { this(alias, aliased, null); } private MtnMomoResponses(Name alias, Table<MtnMomoResponsesRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table()); } public <O extends Record> MtnMomoResponses(Table<O> child, ForeignKey<O, MtnMomoResponsesRecord> key) { super(child, key, MTNMOMO_RESPONSES); } @Override public Schema getSchema() { return Killbill.KILLBILL; } @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.MTNMOMO_RESPONSES_MTNMOMO_RESPONSES_KB_PAYMENT_ID, Indexes.MTNMOMO_RESPONSES_MTNMOMO_RESPONSES_KB_PAYMENT_TRANSACTION_ID); } @Override public Identity<MtnMomoResponsesRecord, ULong> getIdentity() { return Keys.IDENTITY_MTNMOMO_RESPONSES; } @Override public UniqueKey<MtnMomoResponsesRecord> getPrimaryKey() { return Keys.KEY_MTNMOMO_RESPONSES_PRIMARY; } @Override public List<UniqueKey<MtnMomoResponsesRecord>> getKeys() { return Arrays.<UniqueKey<MtnMomoResponsesRecord>>asList(Keys.KEY_MTNMOMO_RESPONSES_PRIMARY, Keys.KEY_MTNMOMO_RESPONSES_RECORD_ID); } @Override public MtnMomoResponses as(String alias) { return new MtnMomoResponses(DSL.name(alias), this); } @Override public MtnMomoResponses as(Name alias) { return new MtnMomoResponses(alias, this); } /** * Rename this table */ @Override public MtnMomoResponses rename(String name) { return new MtnMomoResponses(DSL.name(name), null); } /** * Rename this table */ @Override public MtnMomoResponses rename(Name name) { return new MtnMomoResponses(name, null); } }
41.155556
201
0.714273
d23b1d1d94e27741ac329a2ffd2f9085bb958d7d
3,857
package com.ke.schedule.server.core.service.impl; import com.ke.schedule.server.core.model.db.LogCollect; import com.ke.schedule.server.core.model.db.LogOpt; import com.ke.schedule.server.core.model.db.TaskRecord; import com.ke.schedule.server.core.repository.LogCollectRepository; import com.ke.schedule.server.core.repository.LogOptRepository; import com.ke.schedule.server.core.repository.TaskRecordRepository; import com.ke.schedule.server.core.service.LoggerService; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.Resource; import javax.persistence.criteria.Predicate; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 日志service * * @Author: zhaoyuguang * @Date: 2018/8/24 下午9:15 */ @Service("loggerService") public class LoggerServiceImpl implements LoggerService { @Value("${kob-schedule.mysql-prefix}") private String mp; @Resource private LogCollectRepository logCollectRepository; @Resource private LogOptRepository logOptRepository; @Resource private TaskRecordRepository taskRecordRepository; @Override public long selectTaskRecordCountByParam(Map<String, Object> param) { Long triggerTimeStart = (Long) param.get("triggerTimeStart"); Long triggerTimeEnd = (Long) param.get("triggerTimeEnd"); Specification<TaskRecord> specification = (Specification<TaskRecord>) (root, criteriaQuery, criteriaBuilder) -> { List<Predicate> predicates = new ArrayList<>(); if (!StringUtils.isEmpty(param.get("projectCode"))) { Predicate predicate = criteriaBuilder.equal(root.get("projectCode").as(String.class), param.get("projectCode")); predicates.add(predicate); } if (!StringUtils.isEmpty(param.get("jobUuid"))) { Predicate predicate = criteriaBuilder.equal(root.get("jobUuid").as(String.class), param.get("jobUuid")); predicates.add(predicate); } if (triggerTimeStart != null) { Predicate predicate = criteriaBuilder.greaterThanOrEqualTo(root.get("triggerTime").as(Long.class), triggerTimeStart); predicates.add(predicate); } if (triggerTimeEnd != null) { Predicate predicate = criteriaBuilder.lessThanOrEqualTo(root.get("triggerTime").as(Long.class), triggerTimeEnd); predicates.add(predicate); } if (predicates.size() == 0) { return null; } return criteriaBuilder.or(predicates.toArray(new Predicate[]{})); }; return taskRecordRepository.count(specification); } @Override public Long selectLogCollectCountByProjectCodeAndTaskUuid(String projectCode, String taskUuid) { if (StringUtils.isEmpty(taskUuid)) { return logCollectRepository.countLogCollectByProjectCode(projectCode); } else { return logCollectRepository.countLogCollectByProjectCodeAndTaskUuid(projectCode, taskUuid); } } @Override public List<LogCollect> selectLogCollectPageByProjectAndTaskUuid(String projectCode, String taskUuid, Pageable pageable) { if (StringUtils.isEmpty(taskUuid)) { return logCollectRepository.findLogCollectByProjectCode(projectCode, pageable).getContent(); } else { return logCollectRepository.findLogCollectByProjectCodeAndTaskUuid(projectCode, taskUuid, pageable).getContent(); } } @Override public void saveLogOpt(LogOpt logOpt) { logOptRepository.save(logOpt); } }
37.813725
133
0.699767
6168de74cb4449a4a54b20c53944f740edac900f
1,255
package org.folio.rest.impl; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.junit.jupiter.api.Test; import java.net.MalformedURLException; import static org.junit.Assert.assertEquals; public class PoNumberTest extends TestBase { private final Logger logger = LogManager.getLogger(PoNumberTest.class); private static final String PO_NUMBER_ENDPOINT = "/orders-storage/po-number"; @Test public void testGetPoNumberOk() throws MalformedURLException { long poNumber1 = getPoNumberAsInt(); logger.info("--- mod-orders-storage Generated po_number1: " + poNumber1); long poNumber2 = getPoNumberAsInt(); logger.info("--- mod-orders-storage Generated po_number2: " + poNumber2); long poNumber3 = getPoNumberAsInt(); logger.info("--- mod-orders-storage Generated po_number3: " + poNumber3); //ensure that the numbers returned are in fact sequential assertEquals(1, poNumber3 - poNumber2); assertEquals(1, poNumber2 - poNumber1); } private int getPoNumberAsInt() throws MalformedURLException { return Integer.parseInt(getData(PO_NUMBER_ENDPOINT) .then() .statusCode(200) .extract() .response() .path("sequenceNumber")); } }
30.609756
79
0.732271
55e6084c554263b8d89ef7969e9532a58e5e0b55
2,365
package com.obsidiandynamics.indigo; import static com.obsidiandynamics.indigo.ActorSystemConfig.ExceptionHandlerChoice.*; import static junit.framework.TestCase.*; import org.junit.*; import com.obsidiandynamics.indigo.util.*; public final class FrameworkErrorTest implements TestSupport { private static final String SINK = "sink"; private static final class BadSignal implements Signal {} private ActorSystem system; @Before public void setup() { system = new TestActorSystemConfig() {{ exceptionHandler = DRAIN; }} .createActorSystem(); } @After public void teardown() { system.shutdownSilently(); } @Test public void testUnsupportedSolicitedSignal() throws InterruptedException { system.on(SINK).cue((a, m) -> { a.reply(m).tell(new BadSignal()); }) .ingress(a -> { a.to(ActorRef.of(SINK)).ask() .onFault(f -> { fail("Unexpected fault"); }) .await(60_000).onTimeout(() -> { /* may still time out when draining the schedulers during system termination */ }) .onResponse(r -> { fail("Unexpected response"); }); }); try { system.drain(0); fail("Failed to catch UnhandledMultiException"); } catch (UnhandledMultiException e) { assertEquals(1, e.getErrors().length); assertFrameworkError(e.getErrors()[0]); } assertFalse(system.isRunning()); } @Test public void testUnsupportedUnsolicitedSignal() throws InterruptedException { system.ingress(a -> { a.to(ActorRef.of(ActorRef.INGRESS)).ask(new BadSignal()) .onFault(f -> { fail("Unexpected fault"); }) .await(60_000).onTimeout(() -> { /* may still time out when draining the schedulers during system termination */ }) .onResponse(r -> { fail("Unexpected response"); }); }); try { system.drain(0); fail("Failed to catch UnhandledMultiException"); } catch (UnhandledMultiException e) { assertEquals(1, e.getErrors().length); assertFrameworkError(e.getErrors()[0]); } assertFalse(system.isRunning()); } private void assertFrameworkError(Throwable t) { assertEquals(FrameworkError.class, t.getClass()); assertEquals("Unsupported signal of type " + BadSignal.class.getName(), t.getMessage()); } }
27.5
121
0.64482
6c3a1e896305b12103dae7922a055008be21b21d
4,495
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3; import android.appwidget.AppWidgetHost; import android.appwidget.AppWidgetHostView; import android.appwidget.AppWidgetProviderInfo; import android.content.Context; import android.os.TransactionTooLargeException; import android.view.LayoutInflater; import android.view.View; import java.util.ArrayList; /** * Specific {@link AppWidgetHost} that creates our {@link LauncherAppWidgetHostView} * which correctly captures all long-press events. This ensures that users can * always pick up and move widgets. */ public class LauncherAppWidgetHost extends AppWidgetHost { private final ArrayList<Runnable> mProviderChangeListeners = new ArrayList<Runnable>(); private int mQsbWidgetId = -1; private Launcher mLauncher; public LauncherAppWidgetHost(Launcher launcher, int hostId) { super(launcher, hostId); mLauncher = launcher; } public void setQsbWidgetId(int widgetId) { mQsbWidgetId = widgetId; } @Override protected AppWidgetHostView onCreateView(Context context, int appWidgetId, AppWidgetProviderInfo appWidget) { if (appWidgetId == mQsbWidgetId) { return new LauncherAppWidgetHostView(context) { @Override protected View getErrorView() { // For the QSB, show an empty view instead of an error view. return new View(getContext()); } }; } return new LauncherAppWidgetHostView(context); } @Override public void startListening() { try { super.startListening(); } catch (Exception e) { if (e.getCause() instanceof TransactionTooLargeException) { // We're willing to let this slide. The exception is being caused by the list of // RemoteViews which is being passed back. The startListening relationship will // have been established by this point, and we will end up populating the // widgets upon bind anyway. See issue 14255011 for more context. } else { throw new RuntimeException(e); } } } @Override public void stopListening() { super.stopListening(); clearViews(); } public void addProviderChangeListener(Runnable callback) { mProviderChangeListeners.add(callback); } public void removeProviderChangeListener(Runnable callback) { mProviderChangeListeners.remove(callback); } protected void onProvidersChanged() { if (!mProviderChangeListeners.isEmpty()) { for (Runnable callback : new ArrayList<>(mProviderChangeListeners)) { callback.run(); } } } public AppWidgetHostView createView(Context context, int appWidgetId, LauncherAppWidgetProviderInfo appWidget) { if (appWidget.isCustomWidget) { LauncherAppWidgetHostView lahv = new LauncherAppWidgetHostView(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(appWidget.initialLayout, lahv); lahv.setAppWidget(0, appWidget); lahv.updateLastInflationOrientation(); return lahv; } else { return super.createView(context, appWidgetId, appWidget); } } /** * Called when the AppWidget provider for a AppWidget has been upgraded to a new apk. */ @Override protected void onProviderChanged(int appWidgetId, AppWidgetProviderInfo appWidget) { LauncherAppWidgetProviderInfo info = LauncherAppWidgetProviderInfo.fromProviderInfo( mLauncher, appWidget); super.onProviderChanged(appWidgetId, info); } }
34.576923
96
0.667186
e0f4e8de9dd606ee2b5a9ed802eddb017318ead0
1,632
package aiyagirl.nanchen.com.myapplication.presenter; import com.hyphenate.EMCallBack; import com.hyphenate.chat.EMClient; import aiyagirl.nanchen.com.myapplication.entity.User; import aiyagirl.nanchen.com.myapplication.ui.contract.LoginContract; import aiyagirl.nanchen.com.myapplication.utils.ThreadUtil; /** * Created by Administrator on 2017/9/28. */ public class LoginPresenter extends LoginContract.Presenter { @Override public void login(final String name, final String pwd) { getView().setDialogState(true); EMClient.getInstance().login(name, pwd, new EMCallBack() { @Override public void onSuccess() { EMClient.getInstance().groupManager().loadAllGroups(); EMClient.getInstance().chatManager().loadAllConversations(); loginSuccess(true,new User(name,pwd),null); } @Override public void onError(int i, String s) { loginSuccess(false,null,s); } @Override public void onProgress(int i, String s) { } }); } private void loginSuccess(final boolean isSuccess, final User user, final String msg) { ThreadUtil.runOnUiThread(new Runnable() { @Override public void run() { getView().setDialogState(false); if(isSuccess){ getView().loginSuccess(user); }else { getView().showMessage("登录失败:"+msg); } } }); } }
31.384615
92
0.574142
3e59fc8795290434a24f9d130da424be893a033b
1,672
package ru.job4j.homeworks; import java.util.Scanner; // в двумерный массив записали годовые оценки по десяти предметам // за 9-й класс каждого из 25 учеников класса (в первой строчке - оценки первого ученика, // во второй - второго и т.д.). В начале нового учебного года в класс пришел новый ученик. // Изменить массив так, чтобы в нем были оценки за 9-ый класс и нового ученика, учитывая, // что этот ученик в списке должен быть на n-ном месте. Оценки нового ученика вводятся с клавиатуры // и в дополнительный массив записываться не должны. public class Task12250 { // special methods for test int[] newPupil; public Task12250(int[] newPupil) { this.newPupil = newPupil; } public int[][] renovatePupils(int[][] array, int place) { //int[] newPupil = enterNewPupil(array[0].length); int[] newPupil = this.newPupil; int[][] result = new int[array.length + 1][array[0].length]; boolean isPassed = false; int correct = 0; for (int i = 0; i < array.length; i++) { if (i == place) { for (int j = 0; j < array[i].length; j++) { result[i + correct][j] = newPupil[j]; } correct++; } for (int j = 0; j < array[i].length; j++) { result[i + correct][j] = array[i][j]; } } return result; } private int[] enterNewPupil(int size) { int[] result = new int[size]; Scanner scanner = new Scanner(System.in); for (int i = 0; i < size; i++) { result[i] = scanner.nextInt(); } return result; } }
33.44
99
0.569976
72c665d15c6e63322ce535a790aceddca31b4a5c
12,409
package org.blender.dna; import java.io.IOException; import org.cakelab.blender.io.block.Block; import org.cakelab.blender.io.block.BlockTable; import org.cakelab.blender.nio.CArrayFacade; import org.cakelab.blender.nio.CFacade; import org.cakelab.blender.nio.CMetaData; import org.cakelab.blender.nio.CPointer; /** * Generated facet for DNA struct type 'NlaTrack'. * * <h3>Class Documentation</h3> * <h4>Blender Source Code:</h4> * <p> NLA Tracks ----------------------------------<mdash/> NLA Track (nlt)</p><p> A track groups a bunch of 'strips', which should form a continuous set of motion, on top of which other such groups can be layered. This should allow for animators to work in a non-destructive manner, layering tweaks, etc. over 'rough' blocks of their work. </p> */ @CMetaData(size32=88, size64=104) public class NlaTrack extends CFacade { /** * This is the sdna index of the struct NlaTrack. * <p> * It is required when allocating a new block to store data for NlaTrack. * </p> * @see {@link org.cakelab.blender.io.dna.internal.StructDNA} * @see {@link org.cakelab.blender.io.block.BlockTable#allocate} */ public static final int __DNA__SDNA_INDEX = 656; /** * Field descriptor (offset) for struct member 'next'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * NlaTrack nlatrack = ...; * CPointer&lt;Object&gt; p = nlatrack.__dna__addressof(NlaTrack.__DNA__FIELD__next); * CPointer&lt;CPointer&lt;NlaTrack&gt;&gt; p_next = p.cast(new Class[]{CPointer.class, NlaTrack.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'next'</li> * <li>Signature: 'NlaTrack*'</li> * <li>Actual Size (32bit/64bit): 4/8</li> * </ul> */ public static final long[] __DNA__FIELD__next = new long[]{0, 0}; /** * Field descriptor (offset) for struct member 'prev'. * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * NlaTrack nlatrack = ...; * CPointer&lt;Object&gt; p = nlatrack.__dna__addressof(NlaTrack.__DNA__FIELD__prev); * CPointer&lt;CPointer&lt;NlaTrack&gt;&gt; p_prev = p.cast(new Class[]{CPointer.class, NlaTrack.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'prev'</li> * <li>Signature: 'NlaTrack*'</li> * <li>Actual Size (32bit/64bit): 4/8</li> * </ul> */ public static final long[] __DNA__FIELD__prev = new long[]{4, 8}; /** * Field descriptor (offset) for struct member 'strips'. * <h3>Field Documentation</h3> * <h4>Blender Python API:</h4> * (read-only) NLA Strips on this NLA-track<h4>Blender Source Code:</h4> * <p> BActionStrips in this track. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * NlaTrack nlatrack = ...; * CPointer&lt;Object&gt; p = nlatrack.__dna__addressof(NlaTrack.__DNA__FIELD__strips); * CPointer&lt;ListBase&gt; p_strips = p.cast(new Class[]{ListBase.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'strips'</li> * <li>Signature: 'ListBase'</li> * <li>Actual Size (32bit/64bit): 8/16</li> * </ul> */ public static final long[] __DNA__FIELD__strips = new long[]{8, 16}; /** * Field descriptor (offset) for struct member 'flag'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Settings for this track. </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * NlaTrack nlatrack = ...; * CPointer&lt;Object&gt; p = nlatrack.__dna__addressof(NlaTrack.__DNA__FIELD__flag); * CPointer&lt;Integer&gt; p_flag = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'flag'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__flag = new long[]{16, 32}; /** * Field descriptor (offset) for struct member 'index'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Index of the track in the stack <h2>Note</h2><p> not really useful, but we need a '_pad' var anyways! </p> not really useful, but we need a '_pad' var anyways! * * </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * NlaTrack nlatrack = ...; * CPointer&lt;Object&gt; p = nlatrack.__dna__addressof(NlaTrack.__DNA__FIELD__index); * CPointer&lt;Integer&gt; p_index = p.cast(new Class[]{Integer.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'index'</li> * <li>Signature: 'int'</li> * <li>Actual Size (32bit/64bit): 4/4</li> * </ul> */ public static final long[] __DNA__FIELD__index = new long[]{20, 36}; /** * Field descriptor (offset) for struct member 'name'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p><code></code> . </p> * <h3>Pointer Arithmetics</h3> * <p> * This is how you get a reference on the corresponding field in the struct: * </p> * <pre> * NlaTrack nlatrack = ...; * CPointer&lt;Object&gt; p = nlatrack.__dna__addressof(NlaTrack.__DNA__FIELD__name); * CPointer&lt;CArrayFacade&lt;Byte&gt;&gt; p_name = p.cast(new Class[]{CArrayFacade.class, Byte.class}); * </pre> * <h3>Metadata</h3> * <ul> * <li>Field: 'name'</li> * <li>Signature: 'char[64]'</li> * <li>Actual Size (32bit/64bit): 64/64</li> * </ul> */ public static final long[] __DNA__FIELD__name = new long[]{24, 40}; public NlaTrack(long __address, Block __block, BlockTable __blockTable) { super(__address, __block, __blockTable); } protected NlaTrack(NlaTrack that) { super(that.__io__address, that.__io__block, that.__io__blockTable); } /** * Get method for struct member 'next'. * @see #__DNA__FIELD__next */ public CPointer<NlaTrack> getNext() throws IOException { long __dna__targetAddress; if ((__io__pointersize == 8)) { __dna__targetAddress = __io__block.readLong(__io__address + 0); } else { __dna__targetAddress = __io__block.readLong(__io__address + 0); } Class<?>[] __dna__targetTypes = new Class[]{NlaTrack.class}; return new CPointer<NlaTrack>(__dna__targetAddress, __dna__targetTypes, __io__blockTable.getBlock(__dna__targetAddress, NlaTrack.__DNA__SDNA_INDEX), __io__blockTable); } /** * Set method for struct member 'next'. * @see #__DNA__FIELD__next */ public void setNext(CPointer<NlaTrack> next) throws IOException { long __address = ((next == null) ? 0 : next.getAddress()); if ((__io__pointersize == 8)) { __io__block.writeLong(__io__address + 0, __address); } else { __io__block.writeLong(__io__address + 0, __address); } } /** * Get method for struct member 'prev'. * @see #__DNA__FIELD__prev */ public CPointer<NlaTrack> getPrev() throws IOException { long __dna__targetAddress; if ((__io__pointersize == 8)) { __dna__targetAddress = __io__block.readLong(__io__address + 8); } else { __dna__targetAddress = __io__block.readLong(__io__address + 4); } Class<?>[] __dna__targetTypes = new Class[]{NlaTrack.class}; return new CPointer<NlaTrack>(__dna__targetAddress, __dna__targetTypes, __io__blockTable.getBlock(__dna__targetAddress, NlaTrack.__DNA__SDNA_INDEX), __io__blockTable); } /** * Set method for struct member 'prev'. * @see #__DNA__FIELD__prev */ public void setPrev(CPointer<NlaTrack> prev) throws IOException { long __address = ((prev == null) ? 0 : prev.getAddress()); if ((__io__pointersize == 8)) { __io__block.writeLong(__io__address + 8, __address); } else { __io__block.writeLong(__io__address + 4, __address); } } /** * Get method for struct member 'strips'. * <h3>Field Documentation</h3> * <h4>Blender Python API:</h4> * (read-only) NLA Strips on this NLA-track<h4>Blender Source Code:</h4> * <p> BActionStrips in this track. </p> * @see #__DNA__FIELD__strips */ public ListBase getStrips() throws IOException { if ((__io__pointersize == 8)) { return new ListBase(__io__address + 16, __io__block, __io__blockTable); } else { return new ListBase(__io__address + 8, __io__block, __io__blockTable); } } /** * Set method for struct member 'strips'. * <h3>Field Documentation</h3> * <h4>Blender Python API:</h4> * (read-only) NLA Strips on this NLA-track<h4>Blender Source Code:</h4> * <p> BActionStrips in this track. </p> * @see #__DNA__FIELD__strips */ public void setStrips(ListBase strips) throws IOException { long __dna__offset; if ((__io__pointersize == 8)) { __dna__offset = 16; } else { __dna__offset = 8; } if (__io__equals(strips, __io__address + __dna__offset)) { return; } else if (__io__same__encoding(this, strips)) { __io__native__copy(__io__block, __io__address + __dna__offset, strips); } else { __io__generic__copy( getStrips(), strips); } } /** * Get method for struct member 'flag'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Settings for this track. </p> * @see #__DNA__FIELD__flag */ public int getFlag() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 32); } else { return __io__block.readInt(__io__address + 16); } } /** * Set method for struct member 'flag'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Settings for this track. </p> * @see #__DNA__FIELD__flag */ public void setFlag(int flag) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 32, flag); } else { __io__block.writeInt(__io__address + 16, flag); } } /** * Get method for struct member 'index'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Index of the track in the stack <h2>Note</h2><p> not really useful, but we need a '_pad' var anyways! </p> not really useful, but we need a '_pad' var anyways! * * </p> * @see #__DNA__FIELD__index */ public int getIndex() throws IOException { if ((__io__pointersize == 8)) { return __io__block.readInt(__io__address + 36); } else { return __io__block.readInt(__io__address + 20); } } /** * Set method for struct member 'index'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p> Index of the track in the stack <h2>Note</h2><p> not really useful, but we need a '_pad' var anyways! </p> not really useful, but we need a '_pad' var anyways! * * </p> * @see #__DNA__FIELD__index */ public void setIndex(int index) throws IOException { if ((__io__pointersize == 8)) { __io__block.writeInt(__io__address + 36, index); } else { __io__block.writeInt(__io__address + 20, index); } } /** * Get method for struct member 'name'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p><code></code> . </p> * @see #__DNA__FIELD__name */ public CArrayFacade<Byte> getName() throws IOException { Class<?>[] __dna__targetTypes = new Class[]{Byte.class}; int[] __dna__dimensions = new int[]{ 64 }; if ((__io__pointersize == 8)) { return new CArrayFacade<Byte>(__io__address + 40, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } else { return new CArrayFacade<Byte>(__io__address + 24, __dna__targetTypes, __dna__dimensions, __io__block, __io__blockTable); } } /** * Set method for struct member 'name'. * <h3>Field Documentation</h3> * <h4>Blender Source Code:</h4> * <p><code></code> . </p> * @see #__DNA__FIELD__name */ public void setName(CArrayFacade<Byte> name) throws IOException { long __dna__offset; if ((__io__pointersize == 8)) { __dna__offset = 40; } else { __dna__offset = 24; } if (__io__equals(name, __io__address + __dna__offset)) { return; } else if (__io__same__encoding(this, name)) { __io__native__copy(__io__block, __io__address + __dna__offset, name); } else { __io__generic__copy( getName(), name); } } /** * Instantiates a pointer on this instance. */ public CPointer<NlaTrack> __io__addressof() { return new CPointer<NlaTrack>(__io__address, new Class[]{NlaTrack.class}, __io__block, __io__blockTable); } }
30.265854
347
0.667338
7664b91f9219a2d876773f25d606f35023436511
12,483
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.rio.helpers; import static org.junit.Assert.*; import java.util.Collections; import java.util.HashSet; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.XMLSchema; import org.eclipse.rdf4j.rio.DatatypeHandler; import org.eclipse.rdf4j.rio.LanguageHandler; import org.eclipse.rdf4j.rio.ParseErrorListener; import org.eclipse.rdf4j.rio.ParserConfig; import org.eclipse.rdf4j.rio.RDFParseException; 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; /** * Tests for {@link RDFParserHelper} methods. * * @author Peter Ansell */ public class RDFParserHelperTest { private static final String TEST_MESSAGE_FOR_FAILURE = "Test message for failure."; @Rule public ExpectedException thrown = ExpectedException.none(); private static final String LABEL_TESTA = "test-a"; private static final String LANG_EN = "en"; private ParserConfig parserConfig; private ParseErrorCollector errListener; private ValueFactory valueFactory; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { parserConfig = new ParserConfig(); // By default we wipe out the SPI loaded datatype and language handlers parserConfig.set(BasicParserSettings.DATATYPE_HANDLERS, Collections.<DatatypeHandler>emptyList()); parserConfig.set(BasicParserSettings.LANGUAGE_HANDLERS, Collections.<LanguageHandler>emptyList()); // Ensure that the set of non-fatal errors is empty by default parserConfig.setNonFatalErrors(new HashSet<>()); errListener = new ParseErrorCollector(); valueFactory = SimpleValueFactory.getInstance(); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#createLiteral(java.lang.String, java.lang.String, org.eclipse.rdf4j.model.URI, org.eclipse.rdf4j.rio.ParserConfig, org.eclipse.rdf4j.rio.ParseErrorListener, org.eclipse.rdf4j.model.ValueFactory)} * . */ @Test public final void testCreateLiteralLabelNull() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage("Cannot create a literal using a null label"); RDFParserHelper.createLiteral(null, null, null, parserConfig, errListener, valueFactory); } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#createLiteral(java.lang.String, java.lang.String, org.eclipse.rdf4j.model.URI, org.eclipse.rdf4j.rio.ParserConfig, org.eclipse.rdf4j.rio.ParseErrorListener, org.eclipse.rdf4j.model.ValueFactory)} * . */ @Test public final void testCreateLiteralLabelOnly() throws Exception { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, null, null, parserConfig, errListener, valueFactory); assertEquals(LABEL_TESTA, literal.getLabel()); assertFalse(literal.getLanguage().isPresent()); assertEquals(XMLSchema.STRING, literal.getDatatype()); } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#createLiteral(java.lang.String, java.lang.String, org.eclipse.rdf4j.model.URI, org.eclipse.rdf4j.rio.ParserConfig, org.eclipse.rdf4j.rio.ParseErrorListener, org.eclipse.rdf4j.model.ValueFactory)} * . */ @Test public final void testCreateLiteralLabelAndLanguage() throws Exception { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, LANG_EN, null, parserConfig, errListener, valueFactory); assertEquals(LABEL_TESTA, literal.getLabel()); assertEquals(LANG_EN, literal.getLanguage().orElse(null)); assertEquals(RDF.LANGSTRING, literal.getDatatype()); } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#createLiteral(java.lang.String, java.lang.String, org.eclipse.rdf4j.model.URI, org.eclipse.rdf4j.rio.ParserConfig, org.eclipse.rdf4j.rio.ParseErrorListener, org.eclipse.rdf4j.model.ValueFactory)} * . */ @Test public final void testCreateLiteralLabelAndDatatype() throws Exception { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, null, XMLSchema.STRING, parserConfig, errListener, valueFactory); assertEquals(LABEL_TESTA, literal.getLabel()); assertFalse(literal.getLanguage().isPresent()); assertEquals(XMLSchema.STRING, literal.getDatatype()); } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#createLiteral(java.lang.String, java.lang.String, org.eclipse.rdf4j.model.URI, org.eclipse.rdf4j.rio.ParserConfig, org.eclipse.rdf4j.rio.ParseErrorListener, org.eclipse.rdf4j.model.ValueFactory)} * . * <p> * SES-1803 : Temporary decision to ensure RDF-1.0 backwards compatibility for Literals created by this method in * cases where {@link RDF#LANGSTRING} is given and there is a language. */ @Test public final void testCreateLiteralLabelAndLanguageWithRDFLangString() throws Exception { Literal literal = RDFParserHelper.createLiteral(LABEL_TESTA, LANG_EN, RDF.LANGSTRING, parserConfig, errListener, valueFactory); assertEquals(LABEL_TESTA, literal.getLabel()); assertEquals(LANG_EN, literal.getLanguage().orElse(null)); assertEquals(RDF.LANGSTRING, literal.getDatatype()); } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#createLiteral(java.lang.String, java.lang.String, org.eclipse.rdf4j.model.URI, org.eclipse.rdf4j.rio.ParserConfig, org.eclipse.rdf4j.rio.ParseErrorListener, org.eclipse.rdf4j.model.ValueFactory)} * . * <p> * SES-1803 : Temporary decision to ensure RDF-1.0 backwards compatibility for Literals created by this method in * cases where {@link RDF#LANGSTRING} is given and there is NO given language. * <p> * SES-2203 : This was inconsistent, so has been changed to verify failure. */ @Test public final void testCreateLiteralLabelNoLanguageWithRDFLangString() throws Exception { thrown.expect(RDFParseException.class); RDFParserHelper.createLiteral(LABEL_TESTA, null, RDF.LANGSTRING, parserConfig, errListener, valueFactory); } @Test public final void testReportErrorStringFatalActive() throws Exception { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); thrown.expect(RDFParseException.class); thrown.expectMessage(TEST_MESSAGE_FOR_FAILURE); try { RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, BasicParserSettings.VERIFY_DATATYPE_VALUES, parserConfig, errListener); } finally { assertErrorListener(0, 1, 0); } } @Test public final void testReportErrorStringNonFatalActive() throws Exception { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); parserConfig.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, BasicParserSettings.VERIFY_DATATYPE_VALUES, parserConfig, errListener); assertErrorListener(0, 1, 0); } @Test public final void testReportErrorStringFatalInactive() throws Exception { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, parserConfig, errListener); assertErrorListener(0, 0, 0); } @Test public final void testReportErrorStringNonFatalInactive() throws Exception { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); parserConfig.addNonFatalError(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, parserConfig, errListener); assertErrorListener(0, 0, 0); } @Test public final void testReportErrorStringIntIntFatalActive() throws Exception { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); thrown.expect(RDFParseException.class); thrown.expectMessage(TEST_MESSAGE_FOR_FAILURE); try { RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, 1, 1, BasicParserSettings.VERIFY_DATATYPE_VALUES, parserConfig, errListener); } finally { assertErrorListener(0, 1, 0); } } @Test public final void testReportErrorStringIntIntNonFatalActive() throws Exception { parserConfig.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, true); assertTrue(parserConfig.get(BasicParserSettings.VERIFY_DATATYPE_VALUES)); parserConfig.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, 1, 1, BasicParserSettings.VERIFY_DATATYPE_VALUES, parserConfig, errListener); assertErrorListener(0, 1, 0); } @Test public final void testReportErrorStringIntIntFatalInactive() throws Exception { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, 1, 1, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, parserConfig, errListener); assertErrorListener(0, 0, 0); } @Test public final void testReportErrorStringIntIntNonFatalInactive() throws Exception { assertFalse(parserConfig.get(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES)); parserConfig.addNonFatalError(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES); RDFParserHelper.reportError(TEST_MESSAGE_FOR_FAILURE, 1, 1, BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, parserConfig, errListener); assertErrorListener(0, 0, 0); } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#reportError(java.lang.Exception, int, int, org.eclipse.rdf4j.rio.RioSetting, org.eclipse.rdf4j.rio.ParserConfig, org.eclipse.rdf4j.rio.ParseErrorListener)} * . */ @Ignore @Test public final void testReportErrorExceptionIntInt() throws Exception { fail("Not yet implemented"); // TODO } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#reportFatalError(java.lang.String, org.eclipse.rdf4j.rio.ParseErrorListener)} * . */ @Ignore @Test public final void testReportFatalErrorString() throws Exception { fail("Not yet implemented"); // TODO } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#reportFatalError(java.lang.String, int, int, org.eclipse.rdf4j.rio.ParseErrorListener)} * . */ @Ignore @Test public final void testReportFatalErrorStringIntInt() throws Exception { fail("Not yet implemented"); // TODO } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#reportFatalError(java.lang.Exception, org.eclipse.rdf4j.rio.ParseErrorListener)} * . */ @Ignore @Test public final void testReportFatalErrorException() throws Exception { fail("Not yet implemented"); // TODO } /** * Test method for * {@link org.eclipse.rdf4j.rio.helpers.RDFParserHelper#reportFatalError(java.lang.Exception, int, int, org.eclipse.rdf4j.rio.ParseErrorListener)} * . */ @Ignore @Test public final void testReportFatalErrorExceptionIntInt() throws Exception { fail("Not yet implemented"); // TODO } /** * Private method for verifying the number of errors that were logged to the {@link ParseErrorListener}. * * @param fatalErrors Expected number of fatal errors logged by error listener. * @param errors Expected number of errors logged by error listener. * @param warnings Expected number of warnings logged by error listener. */ private void assertErrorListener(int fatalErrors, int errors, int warnings) { assertEquals(fatalErrors, errListener.getFatalErrors().size()); assertEquals(errors, errListener.getErrors().size()); assertEquals(warnings, errListener.getWarnings().size()); } }
39.378549
252
0.772811
9275bf45bb344cd63f7d93d6b6533cd2c054e43a
2,740
package net.humba01.inquiry.blocks.cromatic.glasses; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.block.Block; import net.minecraft.block.Material; import net.minecraft.sound.BlockSoundGroup; public class CromaticGlassPainels { //Primary Glass Painels public static final Block PRIMARY_RED_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block PRIMARY_BLUE_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block PRIMARY_YELLOW_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); //Secondary Glass Painels public static final Block SECONDARY_GREEN_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block SECONDARY_ORANGE_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block SECONDARY_VIOLET_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); //Tertiary Glass Painels public static final Block TERTIARY_ORANGE_RED_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block TERTIARY_PURPLISH_RED_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block TERTIARY_GREENISH_YELLOW_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block TERTIARY_ORANGE_YELLOW_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block TERTIARY_BLUE_GREEN_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block TERTIARY_BLUE_PURPLE_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); //Neutral Glass Painels public static final Block NEUTRAL_WHITE_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block NEUTRAL_BLACK_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static final Block NEUTRAL_GRAY_GLASS_PAINEL = new Block(FabricBlockSettings.of(Material.GLASS).sounds(BlockSoundGroup.GLASS)); public static void registryPrimaryGlassPainels() {} public static void registrySecondaryGlassPainels() {} public static void registryTertiaryGlassPainels() {} public static void registryNeutralGlassPainels() {} }
70.25641
148
0.833577
907d5f1e5123c767ac555e575cbd0edaea8f86a1
591
package org.kyojo.schemaOrg.m3n3.doma.core.container; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaOrg.m3n3.core.impl.REQUIRED_MAX_AGE; import org.kyojo.schemaOrg.m3n3.core.Container.RequiredMaxAge; @ExternalDomain public class RequiredMaxAgeConverter implements DomainConverter<RequiredMaxAge, Long> { @Override public Long fromDomainToValue(RequiredMaxAge domain) { return domain.getNativeValue(); } @Override public RequiredMaxAge fromValueToDomain(Long value) { return new REQUIRED_MAX_AGE(value); } }
25.695652
87
0.817259
32a903fb8a871304fa45d037e161de45dfa03015
203
package com.riven_chris.static_and_defalut_method; @FunctionalInterface public interface Model2<T> { T get(); default void function2() { System.out.println("Model2 function2"); } }
18.454545
50
0.699507
8e48892950ac31aab4ba5b1d94e85eddcd1bc597
2,498
package com.donkingliang.imageselector.adapter; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.donkingliang.imageselector.entry.MediaInfo; import com.donkingliang.imageselector.view.VideoViewAndPhotoView; import java.util.ArrayList; import java.util.List; public class ImagePagerAdapter extends PagerAdapter { private Context mContext; private List<VideoViewAndPhotoView> viewList = new ArrayList<>(4); List<MediaInfo> mImgList; private OnItemClickListener mListener; public ImagePagerAdapter(Context context, List<MediaInfo> imgList) { this.mContext = context; createImageViews(); mImgList = imgList; } private void createImageViews() { for (int i = 0; i < 4; i++) { VideoViewAndPhotoView videoViewAndPhotoView = new VideoViewAndPhotoView(mContext); viewList.add(videoViewAndPhotoView); } } @Override public int getCount() { return mImgList == null ? 0 : mImgList.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { if (object instanceof VideoViewAndPhotoView) { VideoViewAndPhotoView view = (VideoViewAndPhotoView) object; view.resetRes(); viewList.add(view); container.removeView(view); } } @Override public Object instantiateItem(ViewGroup container, final int position) { final VideoViewAndPhotoView currentView = viewList.remove(0); final MediaInfo image = mImgList.get(position); container.addView(currentView); if (!image.isVideo()) { currentView.showPicByPath(image.getPath()); } else { currentView.playVideoByPath(image.getPath()); } currentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onItemClick(position, image); } } }); return currentView; } public void setOnItemClickListener(OnItemClickListener l) { mListener = l; } public interface OnItemClickListener { void onItemClick(int position, MediaInfo image); } }
30.096386
94
0.652922
303678865b10f8b581f48e4f976990e4e957616c
4,167
package se.claremont.taf.core.gui.teststructure; import se.claremont.taf.core.gui.guistyle.TafButton; import se.claremont.taf.core.gui.guistyle.TafCloseButton; import se.claremont.taf.core.gui.guistyle.TafFrame; import se.claremont.taf.core.gui.guistyle.TafPanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; import java.util.List; public class TestStepListPanel extends TafPanel { TafPanel listingsPanel = new TafPanel("Listingspanel"); JScrollPane scrollPane = new JScrollPane(listingsPanel); TafPanel thisPanel; public TestStepListPanel(List<TestStep> selectedTestSteps, List<TestStep> additionalAvailableTestSteps){ super("TestStepListPanel"); scrollPane.setName("TestStepListingsScrollPane"); populateListingsPanel(selectedTestSteps, additionalAvailableTestSteps); add(scrollPane); } private void populateListingsPanel(List<TestStep> selectedTestSteps, List<TestStep> additionalAvaliableTestSteps){ listingsPanel.removeAll(); //listingsPanel.setLayout(new GridLayout(selectedTestSteps.size(), 3)); GridBagLayout gridBagLayout = new GridBagLayout(); listingsPanel.setLayout(gridBagLayout); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.HORIZONTAL; List<TestStep> listForRemoval = new LinkedList<>(selectedTestSteps); List<TestStep> listForAddition = new LinkedList<>(additionalAvaliableTestSteps); if(selectedTestSteps.size() == 0){ TafButton addTestStepButton = new TafButton("Select first test step"); addTestStepButton.setMnemonic('S'); addTestStepButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new SelectWindow(additionalAvaliableTestSteps); } }); listingsPanel.add(addTestStepButton, constraints); } int i = 0; for(TestStep testStep : selectedTestSteps){ constraints.anchor = GridBagConstraints.LINE_START; constraints.weightx = 0; constraints.gridx = 0; constraints.gridy = i; listingsPanel.add(testStep.guiComponent(), constraints); TafButton addButton = new TafButton("Add below"); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new SelectWindow(additionalAvaliableTestSteps); } }); if(additionalAvaliableTestSteps.size() == 0) addButton.setEnabled(false); constraints.weightx = 0.5; constraints.gridx = 1; listingsPanel.add(addButton, constraints); TafButton removeButton = new TafButton("Remove"); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { listForAddition.add(testStep); listForRemoval.remove(testStep); populateListingsPanel(listForRemoval, listForAddition); } }); constraints.gridx = 2; constraints.weightx = 1; listingsPanel.add(removeButton, constraints); i++; } } private class SelectWindow extends TafFrame{ public SelectWindow(List<TestStep> additionalAvaliableTestSteps) { this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); java.awt.List testStepListing = new java.awt.List(); for (TestStep step : additionalAvaliableTestSteps) { testStepListing.add(step.getTestStepTypeShortName() + " " + step.getName()); } this.getContentPane().add(testStepListing); this.getContentPane().add(new TafCloseButton(this)); this.pack(); this.setVisible(true); } } }
38.229358
118
0.649148
4de5d755ac0f1acabb79f0e351a902c2629e0d72
811
package pt.ulisboa.tecnico.socialsoftware.tutor.answer.dto; import pt.ulisboa.tecnico.socialsoftware.tutor.question.domain.OpenEndedQuestion; public class OpenEndedCorrectAnswerDto extends CorrectAnswerDetailsDto { private String defaultCorrectAnswer; public OpenEndedCorrectAnswerDto(OpenEndedQuestion question) { this.defaultCorrectAnswer = question.getCorrectAnswerRepresentation(); } public String getDefaultCorrectAnswer() { return defaultCorrectAnswer; } public void setDefaultCorrectAnswer(String correctAnswer) { this.defaultCorrectAnswer = correctAnswer; } @Override public String toString() { return "OpenEndedCorrectAnswerDto{" + "defaultCorrectAnswer='" + defaultCorrectAnswer + "'}"; } }
30.037037
81
0.726264
530f1797155b0dca1596b9529e034b8b05507691
2,988
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.ml.selection.paramgrid; import java.util.HashMap; import java.util.Map; /** * Keeps the grid of parameters. */ public class ParamGrid { /** Parameter values by parameter index. */ private Map<Integer, Double[]> paramValuesByParamIdx = new HashMap<>(); /** Parameter names by parameter index. */ private Map<Integer, String> paramNamesByParamIdx = new HashMap<>(); /** Parameter counter. */ private int paramCntr; /** */ public Map<Integer, Double[]> getParamValuesByParamIdx() { return paramValuesByParamIdx; } /** * Adds a grid for the specific hyper parameter. * @param paramName The parameter name. * @param params The array of the given hyper parameter values. * @return The updated ParamGrid. */ public ParamGrid addHyperParam(String paramName, Double[] params) { paramValuesByParamIdx.put(paramCntr, params); paramNamesByParamIdx.put(paramCntr, paramName); paramCntr++; return this; } /** */ public String getParamNameByIndex(int idx) { return paramNamesByParamIdx.get(idx); } }
39.315789
101
0.717871
709db6248ab8eacde7398b41822ce5b33aaf4d01
879
package com.github.afanas10101111.jtb.command; import com.github.afanas10101111.jtb.service.SendBotMessageService; import lombok.RequiredArgsConstructor; import org.telegram.telegrambots.meta.api.objects.Update; import static com.github.afanas10101111.jtb.bot.util.BotUpdateUtil.extractChatId; import static com.github.afanas10101111.jtb.command.CommandName.START; import static com.github.afanas10101111.jtb.command.Emoji.SUNGLASSES_SMILE; @RequiredArgsConstructor public class UserNotFoundExceptionCommand implements Command { public static final String MESSAGE = "Кажется, мы еще незнакомы " + SUNGLASSES_SMILE.getTextValue() + "\nВведи " + START.getName() + " чтоб представиться"; private final SendBotMessageService service; @Override public void execute(Update update) { service.sendMessage(extractChatId(update), MESSAGE); } }
38.217391
105
0.791809
9c87b9440baaec9ef2db42829458e7187bc66337
7,340
/* * The MIT License * * Copyright 2017 mhrimaz. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package knighttourfx; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; import java.util.function.Function; /** * * @author mhrimaz */ public class SearchAgent { private static Position getMin(ArrayState state, List<Position> allPosition) { int min = Integer.MAX_VALUE; Position minPosition = null; Iterator<Position> iterator = allPosition.iterator(); while (iterator.hasNext()) { Position next = iterator.next(); int allPossibleMoves = state.allPossibleMoves(next); if (min > allPossibleMoves) { min = allPossibleMoves; minPosition = next; } } return minPosition; } private Search dfs = (initState, status) -> { Stack<ArrayState> stack = new Stack<>(); stack.add(initState); while (!stack.isEmpty()) { ArrayState pop = stack.pop(); status.setVisitedNode(status.getVisitedNode() + 1); List<Position> allPossibleMoves = pop.getAllPossiblePositions(); for (Position nextMove : allPossibleMoves) { ArrayState newState = pop.moveTo(nextMove); if (newState.isPathExist()) { return newState; } status.setExpandedNode(status.getExpandedNode() + 1); stack.push(newState); } } return null; }; private Search bfs = (initState, status) -> { Queue<ArrayState> queue = new LinkedList<>(); queue.add(initState); while (!queue.isEmpty()) { ArrayState pop = queue.remove(); status.setVisitedNode(status.getVisitedNode() + 1); List<Position> allPossibleMoves = pop.getAllPossiblePositions(); for (Position nextMove : allPossibleMoves) { ArrayState newState = pop.moveTo(nextMove); if (newState.isPathExist()) { return newState; } status.setExpandedNode(status.getExpandedNode() + 1); queue.add(newState); } } return null; }; private Search ucs = (initState, status) -> { Queue<ArrayState> queue = new PriorityQueue<>((ArrayState o1, ArrayState o2) -> { return Integer.compare(o1.getMoveNumber(), o2.getMoveNumber()); }); queue.add(initState); while (!queue.isEmpty()) { ArrayState pop = queue.remove(); status.setVisitedNode(status.getVisitedNode() + 1); List<Position> allPossibleMoves = pop.getAllPossiblePositions(); for (Position nextMove : allPossibleMoves) { ArrayState newState = pop.moveTo(nextMove); if (newState.isPathExist()) { return newState; } status.setExpandedNode(status.getExpandedNode() + 1); queue.add(newState); } } return null; }; //higher return value is better private final Function<ArrayState, Double> heuristic = (state) -> { double distance = Math.hypot(state.getLastX() - state.getBoardSize() / 2D, state.getLastY() - state.getBoardSize() / 2D); return distance + (8 - state.allPossibleMoves()); }; private Search aStar = (initState, status) -> { Queue<ArrayState> queue = new PriorityQueue<>((ArrayState o1, ArrayState o2) -> { return -Double.compare(o1.getMoveNumber() + heuristic.apply(o1), o2.getMoveNumber() + heuristic.apply(o2)); }); queue.add(initState); while (!queue.isEmpty()) { ArrayState pop = queue.remove(); status.setVisitedNode(status.getVisitedNode() + 1); List<Position> allPossibleMoves = pop.getAllPossiblePositions(); for (Position nextMove : allPossibleMoves) { ArrayState newState = pop.moveTo(nextMove); if (newState.isPathExist()) { return newState; } //prune states with dead end if (!newState.hasDeadEnd()) { status.setExpandedNode(status.getExpandedNode() + 1); queue.add(newState); } } } return null; }; private final Search greedy = (initState, status) -> { ArrayState curr = initState; while (!curr.isPathExist()) { List<Position> allPossibleMoves = curr.getAllPossiblePositions(); if (allPossibleMoves.isEmpty()) { return null; } Position min = getMin(curr, allPossibleMoves); curr = curr.moveTo(min); status.setExpandedNode(status.getExpandedNode() + 1); status.setVisitedNode(status.getVisitedNode() + 1); if (curr.isPathExist()) { return curr; } } return null; }; private final HashMap<SearchStrategy, Search> map; public SearchAgent() { map = new HashMap<>(); map.put(SearchStrategy.BFS, bfs); map.put(SearchStrategy.DFS, dfs); map.put(SearchStrategy.A_STAR, aStar); map.put(SearchStrategy.GREEDY, greedy); map.put(SearchStrategy.UCS, ucs); // map.put(SearchStrategy.RBFS, rbfs); } public ArrayState performSearch(ArrayState initState, SearchStrategy strategy, Status status) { long start = System.currentTimeMillis(); ArrayState search = map.get(strategy).search(initState, status); long end = System.currentTimeMillis(); status.setTakenTime(end - start); if (search == null) { status.setStatus("FAILED"); } else { status.setStatus("SUCCESS"); } return search; } }
38.429319
120
0.581744
293ee348a7b20f9e251637f3f55e52e8de0d94af
106
package com.home4u.hotelmanagement.models; public enum FoodType { BREAKFAST, LUNCH, DINNER }
13.25
42
0.707547
ac5cd7f457479afdd5f06bd25f6d314db328eff6
4,081
/*- * << * sag * == * Copyright (C) 2019 sia * == * 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.creditease.gateway.spi.controller; import java.io.IOException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.tomcat.util.modeler.Registry; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.creditease.gateway.excpetion.GatewayException; import com.creditease.gateway.excpetion.GatewayException.ExceptionType; import com.creditease.gateway.helper.JsonHelper; import com.creditease.gateway.message.Message; /** * @Author: yongbiao * @Date: 2019-03-12 19:07 */ @RestController public class ZuulCoreController { private static Logger logger = LoggerFactory.getLogger(ZuulCoreController.class); @Value("${server.port:8080}") private String port; @Value("${zuul.version:1.0}") private String version; @Autowired private DiscoveryClient client; @RequestMapping(value = "/getversion", produces = "application/json;charset=UTF-8", method = RequestMethod.GET) @ResponseBody public String getVersion() { try { logger.info("The zuul version is :{}", version); Message msg = new Message(version, Message.ResponseCode.SUCCESS_CODE.getCode()); return new ObjectMapper().writeValueAsString(msg); } catch (IOException e) { new GatewayException(ExceptionType.CoreException, e); return null; } } @RequestMapping(value = "/updateServerList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET) @ResponseBody public String updateServerList() { try { logger.info("The zuul version is :{}", version); try { Method method = DiscoveryClient.class.getDeclaredMethod("refreshRegistry"); method.setAccessible(true); method.invoke(client, null); } catch (Exception e) { logger.error("Failed to refreshRegistry.", e); } return new ObjectMapper().writeValueAsString("success refresh"); } catch (IOException e) { new GatewayException(ExceptionType.CoreException, e); return null; } } @RequestMapping(value = "/keepAliveCount", produces = "application/json;charset=UTF-8", method = RequestMethod.GET) @ResponseBody public Object getKeepAliveCount() throws Exception { MBeanServer server = Registry.getRegistry(null, null).getMBeanServer(); ObjectName threadObjName = new ObjectName("Tomcat:type=ThreadPool,name=\"http-nio-" + port + "\""); Map<String, Object> result = new HashMap<>(2); result.put("keepAliveCount", server.getAttribute(threadObjName, "keepAliveCount")); result.put("maxConnections", server.getAttribute(threadObjName, "maxConnections")); return JsonHelper.toString(result); } }
32.91129
121
0.697868
b552a4be90807762e629d75de9df3334efe87cff
2,874
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python; import com.jetbrains.python.documentation.docstrings.SphinxDocString; import com.jetbrains.python.fixtures.PyTestCase; import com.jetbrains.python.toolbox.Substring; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; public class SphinxDocstringTest extends PyTestCase { private static SphinxDocString createSphinxDocstring(@Language("TEXT") @NotNull String unescapedContentWithoutQuotes) { return new SphinxDocString(new Substring(unescapedContentWithoutQuotes)); } public void testFieldAliases() { final SphinxDocString docstring = createSphinxDocstring(":param p1: p1 description\n" + ":parameter p2: p2 description\n" + ":arg p3: p3 description\n" + ":argument p4: p4 description\n" + "\n" + ":key key1: key1 description\n" + ":keyword key2: key2 description\n" + "\n" + ":raises Exc1: Exc1 description \n" + ":raise Exc2: Exc2 description \n" + ":except Exc3: Exc3 description \n" + ":exception Exc4: Exc4 description "); assertSameElements(docstring.getParameters(), "p1", "p2", "p3", "p4"); assertEquals("p1 description", docstring.getParamDescription("p1")); assertEquals("p2 description", docstring.getParamDescription("p2")); assertEquals("p3 description", docstring.getParamDescription("p3")); assertEquals("p4 description", docstring.getParamDescription("p4")); assertSameElements(docstring.getKeywordArguments(), "key1", "key2"); assertEquals("key1 description", docstring.getKeywordArgumentDescription("key1")); assertEquals("key2 description", docstring.getKeywordArgumentDescription("key2")); assertSameElements(docstring.getRaisedExceptions(), "Exc1", "Exc2", "Exc3", "Exc4"); assertEquals("Exc1 description", docstring.getRaisedExceptionDescription("Exc1")); assertEquals("Exc2 description", docstring.getRaisedExceptionDescription("Exc2")); assertEquals("Exc3 description", docstring.getRaisedExceptionDescription("Exc3")); assertEquals("Exc4 description", docstring.getRaisedExceptionDescription("Exc4")); } }
62.478261
140
0.587335
8be008d841039e317188f30026e779e859623cbc
1,516
/* * 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 com.app.sinconWeb.models; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; /** * * @author Marcelo Fernandes */ @Entity public class Morador implements Serializable { @Id @SequenceGenerator(name = "morador_seq", sequenceName = "morador_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "morador_seq") private int id; @ManyToOne private Lote lote; private String nome; private String cpf; public Morador() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public Lote getLote() { return lote; } public void setLote(Lote lote) { this.lote = lote; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } /** * @return the idMorador */ }
21.055556
83
0.614116
9592ba3b5882164c67effabc383043e70ae2f4df
6,466
package org.codepay.common.orm.mybatis; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codepay.common.orm.GenericDao; import org.codepay.common.orm.mybatis.paginator.domain.PageBounds; import org.codepay.common.orm.mybatis.paginator.domain.PageList; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; @SuppressWarnings("rawtypes") public class GenericMybatisDao<T> implements GenericDao<T> { private SqlSessionTemplate sqlSessionTemplate; @Autowired public void setsqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } public SqlSessionTemplate getSqlSessionTemplate() { return sqlSessionTemplate; } @Override public long generateSequence(String sqlNameWithNameSpace) { return (Long) sqlSessionTemplate.selectOne(sqlNameWithNameSpace); } /** * 插入数据,返回affectedCount,没有改变id * * @param sqlNameWithNameSpace * @param obj * @return */ @Override public int insertAndReturnAffectedCount(String sqlNameWithNameSpace, T obj) { return sqlSessionTemplate.insert(sqlNameWithNameSpace, obj); } /** * 插入数据,sql里将id设置进obj,返回affectedCount * * @param sqlNameWithNameSpace * @param obj * @return 因为返回值是int型,不是long型,所以不是id,而是affectedCount */ @Override public int insertAndSetupId(String sqlNameWithNameSpace, T obj) { return sqlSessionTemplate.insert(sqlNameWithNameSpace, obj); } @Override public int insertBatchAndReturnAffectedCount(String sqlNameWithNameSpace, Collection<T> objs) { return sqlSessionTemplate.insert(sqlNameWithNameSpace, objs); } @Override public int insert(String sqlNameWithNameSpace, Map<String, Object> paramMap) { return sqlSessionTemplate.insert(sqlNameWithNameSpace, paramMap); } @Override public int delete(String sqlNameWithNameSpace) { return sqlSessionTemplate.delete(sqlNameWithNameSpace); } @Override public int delete(String sqlNameWithNameSpace, Map<String, Object> param) { return sqlSessionTemplate.delete(sqlNameWithNameSpace, param); } @Override public int delete(String sqlNameWithNameSpace, Object param) { return sqlSessionTemplate.delete(sqlNameWithNameSpace, param); } @Override public int update(String sqlNameWithNameSpace, Map<String, Object> param) { return sqlSessionTemplate.update(sqlNameWithNameSpace, param); } @Override public int updateBatchAndReturnAffectedCount(String sqlNameWithNameSpace, Collection<T> objs) { return sqlSessionTemplate.update(sqlNameWithNameSpace, objs); } @Override public int updateByObj(String sqlNameWithNameSpace, Object param) { return sqlSessionTemplate.update(sqlNameWithNameSpace, param); } @SuppressWarnings("unchecked") @Override public T queryOne(String statement, long id) { return (T) sqlSessionTemplate.selectOne(statement, id); } @SuppressWarnings("unchecked") @Override public T queryOne(String statement, String idStr) { return (T) sqlSessionTemplate.selectOne(statement, idStr); } @SuppressWarnings("unchecked") @Override public T queryOne(String sqlNameWithNameSpace, Map map) { return (T) sqlSessionTemplate.selectOne(sqlNameWithNameSpace, map); } @SuppressWarnings("unchecked") @Override public T queryOneByObject(String sqlNameWithNameSpace, String mapKey, Object mapValue) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put(mapKey, mapValue); return (T) sqlSessionTemplate.selectOne(sqlNameWithNameSpace, paramMap); } /** * select count(*) where xxx * * @param sqlNameWithNameSpace * @param map * @return */ @Override public int queryCount(String sqlNameWithNameSpace, Map map) { return (Integer) sqlSessionTemplate.selectOne(sqlNameWithNameSpace, map); } /** * select * where 分页 * * @param sqlNameWithNameSpace * @param map * @param page * @return */ @SuppressWarnings("unchecked") @Override public PageList<T> queryList(String sqlNameWithNameSpace, Map<String, Object> paramMap, PageBounds pageBounds) { return (PageList<T>) sqlSessionTemplate.selectList(sqlNameWithNameSpace, paramMap, pageBounds); } /** * select * where * * @param sqlNameWithNameSpace * @param map * @return */ @Override public <E> List<E> queryList(String sqlNameWithNameSpace, Map<String, Object> map) { return sqlSessionTemplate.selectList(sqlNameWithNameSpace, map); } /** * 慎用。不能用没有where条件的sql * * @param sqlNameWithNameSpace * @return */ @SuppressWarnings("unchecked") @Override public List<T> queryList(String sqlNameWithNameSpace) { return (List<T>) sqlSessionTemplate.selectList(sqlNameWithNameSpace); } @SuppressWarnings("unchecked") @Override public List<T> queryIdIn(String sqlNameWithNameSpace, long[] idList) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("idList", idList); return (List<T>) sqlSessionTemplate.selectList(sqlNameWithNameSpace, paramMap); } /** * 需要预防idList拼接后sql超长超出数据库sql长度的情况 * * @param sqlNameWithNameSpace * @param idList * @return */ @SuppressWarnings("unchecked") @Override public List<T> queryIdIn(String sqlNameWithNameSpace, String[] idList) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("idList", idList); return (List<T>) sqlSessionTemplate.selectList(sqlNameWithNameSpace, paramMap); } @SuppressWarnings("unchecked") @Override public Map<String, Object> selectOneToMap(String sqlNameWithNameSpace, Map param) { return (Map<String, Object>) sqlSessionTemplate.selectOne(sqlNameWithNameSpace, param); } /** * count 查询 * * @param statement * @param parameter * @return */ public Object selectOne(String statement, Object parameter) { return (Object) sqlSessionTemplate.selectOne(statement, parameter); } }
30.074419
116
0.690999
80ed2b24180c97e5361d221a3cdd16a7d8377289
792
package com.sempra.sdgesi.services; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @ConfigurationProperties @Component public class ApplicationProperties { String app; String environment; String color; public ApplicationProperties() { super(); } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getEnvironment() { return environment; } public void setEnvironment(String environment) { this.environment = environment; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
18
75
0.656566
3f84bf5e11c51dedb551e469c551086275d743da
275
package com.study.spring.mapper; import com.study.spring.entity.Student; import org.springframework.stereotype.Repository; /** * Created on 2017-08-10 21:51 * * @author liuzhaoyuan */ @Repository public interface StudentDao { Student getStudentById(Integer id); }
17.1875
49
0.752727
e7dc1294ecd4bad93cfd2ef9fb57f1bd97b7d13f
7,838
/** * */ package com.org.commons.atomparser.parser; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; import com.org.commons.atomparser.exceptions.CheckedException; import com.org.commons.atomparser.helpers.MonitorObject; /** * @author Sharath * */ public class FileParser { /** * */ public static String TempFile = ".//AtomLogs//Temp"; /** * */ public static String LineSeparator = "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"; /** * */ public static String DatePrefix = "Date & Time"; /** * Used for custom fix code for Linux servers Disk utilization */ public static int LinuxDiskTokenCount = 1; private File file; private String pattern; private String rowId; private String columnId; private String hasHeader; private String monitoredElement; private File tempFile; /** * @param fileName * @param pattern * @param rowId * @param columnId * @param hasHeader * @param monitoredElement * @throws CheckedException */ public FileParser(String fileName,String pattern,String rowId, String columnId, String hasHeader, String monitoredElement) throws CheckedException{ this.tempFile = new File(TempFile); this.file = new File(fileName); this.pattern = pattern; this.rowId = rowId; this.columnId = columnId; this.hasHeader = hasHeader; this.monitoredElement = monitoredElement; parseFile(); } /** * @param file * @param pattern * @param rowId * @param columnId * @param hasHeader * @param monitoredElement * @throws CheckedException */ public FileParser(File file,String pattern,String rowId, String columnId, String hasHeader, String monitoredElement) throws CheckedException{ this.tempFile = new File(TempFile); this.file = file; this.pattern = pattern; this.rowId = rowId; this.columnId = columnId; this.hasHeader = hasHeader; this.monitoredElement = monitoredElement; parseFile(); } private void parseFile() throws CheckedException{ Scanner _fileScanner; String _parseLine; StringBuffer _tempBuffer; boolean _hasNextLine; boolean _temp; int _patternIndex; String _skipLineSeparator; String _nextLine; try{ _fileScanner = new Scanner(this.file); _hasNextLine = _fileScanner.hasNextLine(); _tempBuffer = new StringBuffer(); while(_hasNextLine){ _parseLine = _fileScanner.nextLine(); _temp = _parseLine.startsWith(DatePrefix); if(_temp){ _tempBuffer.append(_parseLine); _tempBuffer.append("\n"); } _patternIndex = _parseLine.indexOf(pattern); if(_patternIndex >= 0){ _skipLineSeparator = "true"; _hasNextLine = _fileScanner.hasNextLine(); while(_hasNextLine && (!(_nextLine = _fileScanner.nextLine()).equals(LineSeparator)||(_skipLineSeparator.equals("true")))){ if(_skipLineSeparator.equals("true")) _skipLineSeparator = "false"; _tempBuffer.append(_nextLine); _tempBuffer.append("\n"); } } _hasNextLine = _fileScanner.hasNextLine(); } storeToTempFile(_tempBuffer); }catch (FileNotFoundException e) { CheckedException ce = new CheckedException(e); ce.setCustomMessage("Unable to find the file to be parsed : "+this.file); throw ce; } } private void storeToTempFile(StringBuffer buffer) throws CheckedException{ FileWriter _fileWriter; try{ if(this.tempFile.exists()){ _fileWriter = new FileWriter(this.tempFile); } else{ this.tempFile.createNewFile(); _fileWriter = new FileWriter(this.tempFile); } _fileWriter.flush(); _fileWriter.write(buffer.toString()); _fileWriter.close(); }catch(IOException e){ CheckedException ce = new CheckedException(e); ce.setCustomMessage("Error while writing to the temp File : "+TempFile); throw ce; } } /** * @return * * this method will read the details from the tempFile to create the Monitor Object. * the created the MonitorObject will be returned back. * @throws CheckedException * */ public ArrayList<MonitorObject> getMonitorObjectDetails() throws CheckedException{ ArrayList<MonitorObject> _monitors; _monitors = getMonitorsListFromFile(this.tempFile); return _monitors; } private ArrayList<MonitorObject> getMonitorsListFromFile(File _file) throws CheckedException{ ArrayList<MonitorObject> _monitorsList; Scanner _fileScanner; String _tempLine; MonitorObject _monitorObject; StringTokenizer _tempTokens; String _rowString; String _columnString; String _token; int _countTokens; _monitorsList = new ArrayList<MonitorObject>(); boolean _isFirstLine = true;; /** * Start the code to populate the Array list with Monitor Objects */ try { _fileScanner = new Scanner(_file); _monitorObject = null; for(boolean _hasNextLine = _fileScanner.hasNextLine();_hasNextLine;_hasNextLine = _fileScanner.hasNextLine()){ _rowString = null; _columnString = null; _tempLine = _fileScanner.nextLine(); if(_tempLine.startsWith(DatePrefix)){ if(!_isFirstLine){ _monitorsList.add(_monitorObject); } _monitorObject = new MonitorObject(_tempLine,this.monitoredElement); _isFirstLine = false; continue; } if(_tempLine.startsWith(LineSeparator)){ if(this.hasHeader.equals("true")){ _fileScanner.nextLine(); } continue; } _tempTokens = new StringTokenizer(_tempLine); _countTokens = _tempTokens.countTokens(); /* * Custom Fix for the FAST Linux servers might create problems in future */ if(_countTokens == LinuxDiskTokenCount && this.monitoredElement.equals("DISK")){ setUtilizationValuesForLinuxServers(_fileScanner,_monitorObject); continue; } /* * End of Custom Fix for the FAST Linux servers might create problems in future */ for(int _index=0;_index<_countTokens;_index++){ _token = _tempTokens.nextToken(); if(_index == (Integer.parseInt(this.rowId))){ _rowString = _token; continue; } if(_index == (Integer.parseInt(this.columnId))){ _columnString = _token; continue; } } if( (_monitorObject != null) && (_rowString != null) && (_columnString != null) ){ _monitorObject.setUtilizationValues(_rowString,_columnString); } } } catch (FileNotFoundException e) { CheckedException ce = new CheckedException(e); ce.setCustomMessage("Error while creating the MonitorObjects "); throw ce; } /** * End of the code to populate the ArrayList */ return _monitorsList; } private void setUtilizationValuesForLinuxServers(Scanner fileScanner,MonitorObject monitorObject){ String _tempLine; StringTokenizer _tempTokens; int _countTokens; String _rowString; String _columnString; String _token; _rowString = null; _columnString = null; _tempLine = fileScanner.nextLine(); _tempTokens = new StringTokenizer(_tempLine); _countTokens = _tempTokens.countTokens(); for(int _index=0;_index<_countTokens;_index++){ _token = _tempTokens.nextToken(); if(_index == (Integer.parseInt(this.rowId)-1)){ _rowString = _token; continue; } if(_index == (Integer.parseInt(this.columnId)-1)){ _columnString = _token; continue; } } if( (monitorObject != null) && (_rowString != null) && (_columnString != null) ){ monitorObject.setUtilizationValues(_rowString,_columnString); } } }
29.355805
148
0.673896
e9b4e38d835f056f0539c7ef96ae42fb42bf26b5
1,115
public class EstatisticaDeOrdemR<T extends Comparable<T>> { public static void main(String[] args) { Integer[] array = new Integer[] {2,9,4,11,3}; Integer elem = new EstatisticaDeOrdemR<Integer>().getEstatisticaDeOrdem(array, 4); System.out.println(elem); } public T getEstatisticaDeOrdem(T[] array, int k) { int iMin = 0; int iMax = 0; for (int i = 0; i < array.length; i++) { if (array[i].compareTo(array[iMin]) < 0) { iMin = i; } if (array[i].compareTo(array[iMax]) > 0) { iMax = i; } } return auxGetEstatisticaDeOrdem(array, k, 1, iMin, iMax); } private T auxGetEstatisticaDeOrdem(T[] array, int k, int qntdMinimos, int iMin, int iMax) { if (k == qntdMinimos) { return array[iMin]; } if (k == array.length) { return null; } int iLastMin = iMax; for (int i = 0; i < array.length; i++) { if (array[i].compareTo(array[iLastMin]) < 0) { if (array[i].compareTo(array[iMin]) > 0) { iLastMin = i; } } } return auxGetEstatisticaDeOrdem(array, k, qntdMinimos + 1, iLastMin, iMax); } }
25.930233
93
0.595516
083b44a9b32aca9466193cc7a9f131ad4ea08021
706
package ViewHolder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import anucha.techlogn.promotionapp.R; /** * Created by anucha on 2/16/2018. */ public class ViewHolderSearchBranch extends RecyclerView.ViewHolder { public TextView textBranchName; public TextView textBranchID; public ImageView img_del; public ViewHolderSearchBranch(View convertView) { super(convertView); textBranchName = convertView.findViewById(R.id.textBranchName); textBranchID = convertView.findViewById(R.id.textBranchID); img_del = convertView.findViewById(R.id.img_delete); } }
27.153846
71
0.756374
868ce20342e102ee63f58c3c4d206bd8a6655a2a
1,753
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.core.api.domain.autodiscover; import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; import org.optaplanner.core.api.domain.solution.PlanningEntityProperty; import org.optaplanner.core.api.domain.solution.PlanningSolution; import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; import org.optaplanner.core.api.domain.solution.drools.ProblemFactProperty; /** * Determines if and how to automatically presume * {@link ProblemFactCollectionProperty}, {@link ProblemFactProperty}, * {@link PlanningEntityCollectionProperty} and {@link PlanningEntityProperty} annotations * on {@link PlanningSolution} members based from the member type. */ public enum AutoDiscoverMemberType { /** * Do not reflect. */ NONE, /** * Reflect over the fields and automatically behave as the appropriate annotation is there * based on the field type. */ FIELD, /** * Reflect over the getter methods and automatically behave as the appropriate annotation is there * based on the return type. */ GETTER; }
37.297872
102
0.750143
089c0b161a566b0bdfa2e306f896f0a2b640cb72
1,953
/** * Copyright 2010 - 2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.tree.btree; import jetbrains.exodus.tree.TreeCursor; import org.jetbrains.annotations.NotNull; /** * BTree iterator with duplicates support */ class BTreeCursorDup extends TreeCursor { @NotNull protected final BTreeTraverserDup traverser; // hack to avoid casts BTreeCursorDup(@NotNull BTreeTraverserDup traverser) { super(traverser); this.traverser = traverser; } @Override public boolean getNextDup() { // move to next dup if in -1 position or dupCursor has next element return hasNext() && traverser.inDupTree && getNext() && traverser.inDupTree; } @Override public boolean getNextNoDup() { if (traverser.inDupTree) { traverser.popUntilDupRight(); canGoDown = false; } return getNext(); } @Override public boolean getPrevDup() { // move to next dup if in -1 position or dupCursor has next element return hasPrev() && traverser.inDupTree && getPrev() && traverser.inDupTree; } @Override public boolean getPrevNoDup() { traverser.popUntilDupLeft(); // ignore duplicates return getPrev(); } @Override public int count() { return traverser.inDupTree ? (int) traverser.currentNode.getTree().size : super.count(); } }
29.149254
96
0.676395
b34187ed99af87ce914dbbf871f43707f00af2c1
23,016
package no.nav.foreldrepenger.abakus.iay.tjeneste.dto.iay; import static org.assertj.core.api.Assertions.assertThat; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import no.nav.abakus.iaygrunnlag.inntektsmelding.v1.InntektsmeldingerDto; import no.nav.abakus.iaygrunnlag.inntektsmelding.v1.RefusjonskravDatoerDto; import no.nav.abakus.iaygrunnlag.kodeverk.ArbeidsforholdHandlingType; import no.nav.abakus.iaygrunnlag.kodeverk.YtelseType; import no.nav.foreldrepenger.abakus.dbstoette.JpaExtension; import no.nav.foreldrepenger.abakus.domene.iay.Arbeidsgiver; import no.nav.foreldrepenger.abakus.domene.iay.InntektArbeidYtelseGrunnlagBuilder; import no.nav.foreldrepenger.abakus.domene.iay.InntektArbeidYtelseRepository; import no.nav.foreldrepenger.abakus.domene.iay.arbeidsforhold.ArbeidsforholdInformasjon; import no.nav.foreldrepenger.abakus.domene.iay.arbeidsforhold.ArbeidsforholdInformasjonBuilder; import no.nav.foreldrepenger.abakus.domene.iay.arbeidsforhold.ArbeidsforholdOverstyringBuilder; import no.nav.foreldrepenger.abakus.domene.iay.arbeidsforhold.ArbeidsforholdReferanse; import no.nav.foreldrepenger.abakus.domene.iay.inntektsmelding.Inntektsmelding; import no.nav.foreldrepenger.abakus.domene.iay.inntektsmelding.InntektsmeldingBuilder; import no.nav.foreldrepenger.abakus.iay.InntektArbeidYtelseTjeneste; import no.nav.foreldrepenger.abakus.kobling.Kobling; import no.nav.foreldrepenger.abakus.kobling.KoblingReferanse; import no.nav.foreldrepenger.abakus.kobling.KoblingTjeneste; import no.nav.foreldrepenger.abakus.kobling.repository.KoblingRepository; import no.nav.foreldrepenger.abakus.kobling.repository.LåsRepository; import no.nav.foreldrepenger.abakus.typer.AktørId; import no.nav.foreldrepenger.abakus.typer.EksternArbeidsforholdRef; import no.nav.foreldrepenger.abakus.typer.InternArbeidsforholdRef; import no.nav.foreldrepenger.abakus.typer.OrgNummer; import no.nav.foreldrepenger.abakus.typer.Saksnummer; public class MapInntektsmeldingerTest { public static final String SAKSNUMMER = "1234123412345"; private static final YtelseType ytelseType = YtelseType.FORELDREPENGER; @RegisterExtension public static JpaExtension jpaExtension = new JpaExtension(); private final KoblingRepository repository = new KoblingRepository(jpaExtension.getEntityManager()); private final KoblingTjeneste koblingTjeneste = new KoblingTjeneste(repository, new LåsRepository(jpaExtension.getEntityManager())); private final InntektArbeidYtelseRepository iayRepository = new InntektArbeidYtelseRepository(jpaExtension.getEntityManager()); private final InntektArbeidYtelseTjeneste iayTjeneste = new InntektArbeidYtelseTjeneste(iayRepository); @Test public void skal_hente_alle_inntektsmeldinger_for_fagsak_uten_duplikater() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); KoblingReferanse koblingReferanse2 = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); YtelseType foreldrepenger = YtelseType.FORELDREPENGER; Kobling kobling1 = new Kobling(foreldrepenger, saksnummer, koblingReferanse, aktørId); Kobling kobling2 = new Kobling(foreldrepenger, saksnummer, koblingReferanse2, aktørId); koblingTjeneste.lagre(kobling1); koblingTjeneste.lagre(kobling2); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(Arbeidsgiver.virksomhet(new OrgNummer("910909088"))) .medBeløp(BigDecimal.TEN) .medInnsendingstidspunkt(LocalDateTime.now()) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); ArbeidsforholdInformasjonBuilder arbeidsforholdInformasjon = ArbeidsforholdInformasjonBuilder.builder(Optional.empty()); iayRepository.lagre(koblingReferanse, arbeidsforholdInformasjon, List.of(im)); iayRepository.lagre(koblingReferanse2, arbeidsforholdInformasjon, List.of(im)); // Act Map<Inntektsmelding, ArbeidsforholdInformasjon> alleIm = iayTjeneste.hentArbeidsforholdinfoInntektsmeldingerMapFor(aktørId, saksnummer, foreldrepenger); InntektsmeldingerDto inntektsmeldingerDto = MapInntektsmeldinger.mapUnikeInntektsmeldingerFraGrunnlag(alleIm); // Assert assertThat(inntektsmeldingerDto.getInntektsmeldinger().size()).isEqualTo(1); } @Test public void skal_hente_alle_inntektsmeldinger_for_fagsak_uten_duplikater_med_flere_versjoner_av_arbeidsforholdInformasjon() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); YtelseType foreldrepenger = YtelseType.FORELDREPENGER; Kobling kobling1 = new Kobling(foreldrepenger, saksnummer, koblingReferanse, aktørId); koblingTjeneste.lagre(kobling1); UUID internArbeidsforholdRef = UUID.randomUUID(); Arbeidsgiver virksomhet = Arbeidsgiver.virksomhet(new OrgNummer("910909088")); InternArbeidsforholdRef ref = InternArbeidsforholdRef.ref(internArbeidsforholdRef); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medArbeidsforholdId(ref) .medBeløp(BigDecimal.TEN) .medInnsendingstidspunkt(LocalDateTime.now()) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); EksternArbeidsforholdRef eksternRef = EksternArbeidsforholdRef.ref("EksternRef"); ArbeidsforholdInformasjonBuilder arbeidsforholdInfo1 = ArbeidsforholdInformasjonBuilder.builder(Optional.empty()); arbeidsforholdInfo1.leggTilNyReferanse(new ArbeidsforholdReferanse(virksomhet, ref, eksternRef)); iayRepository.lagre(koblingReferanse, arbeidsforholdInfo1, List.of(im)); ArbeidsforholdInformasjonBuilder arbeidsforholdInfo2 = ArbeidsforholdInformasjonBuilder.builder(Optional.of(arbeidsforholdInfo1.build())) .leggTil(ArbeidsforholdOverstyringBuilder.oppdatere(Optional.empty()) .medArbeidsforholdRef(ref) .medArbeidsgiver(virksomhet) .medHandling(ArbeidsforholdHandlingType.BASERT_PÅ_INNTEKTSMELDING)); InntektArbeidYtelseGrunnlagBuilder grBuilder = InntektArbeidYtelseGrunnlagBuilder.oppdatere(iayRepository.hentInntektArbeidYtelseForBehandling(koblingReferanse)) .medInformasjon(arbeidsforholdInfo2.build()); iayRepository.lagre(koblingReferanse, grBuilder); // Act Map<Inntektsmelding, ArbeidsforholdInformasjon> alleIm = iayTjeneste.hentArbeidsforholdinfoInntektsmeldingerMapFor(aktørId, saksnummer, foreldrepenger); InntektsmeldingerDto inntektsmeldingerDto = MapInntektsmeldinger.mapUnikeInntektsmeldingerFraGrunnlag(alleIm); // Assert assertThat(inntektsmeldingerDto.getInntektsmeldinger().size()).isEqualTo(1); } @Test public void skal_mappe_en_inntektsmelding_til_første_refusjonsdato_og_første_innsendelsesdato() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); YtelseType foreldrepenger = YtelseType.FORELDREPENGER; Kobling kobling1 = new Kobling(foreldrepenger, saksnummer, koblingReferanse, aktørId); koblingTjeneste.lagre(kobling1); LocalDateTime innsendingstidspunkt = LocalDateTime.now(); LocalDate startPermisjon = LocalDate.now().minusDays(10); Arbeidsgiver virksomhet = Arbeidsgiver.virksomhet(new OrgNummer("910909088")); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medBeløp(BigDecimal.TEN) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); iayRepository.lagre(koblingReferanse, ArbeidsforholdInformasjonBuilder.builder(Optional.empty()), List.of(im)); // Act Set<Inntektsmelding> alleIm = iayTjeneste.hentAlleInntektsmeldingerFor(aktørId, saksnummer, foreldrepenger); Kobling nyesteKobling = koblingTjeneste.hentSisteFor(aktørId, saksnummer, foreldrepenger).orElseThrow(); RefusjonskravDatoerDto refusjonskravDatoerDto = MapInntektsmeldinger.mapRefusjonskravdatoer(alleIm, iayTjeneste.hentAggregat(nyesteKobling.getKoblingReferanse())); // Assert assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().size()).isEqualTo(1); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getArbeidsgiver().getIdent()).isEqualTo(virksomhet.getIdentifikator()); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteDagMedRefusjonskrav()).isEqualTo(startPermisjon); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteInnsendingAvRefusjonskrav()).isEqualTo(innsendingstidspunkt.toLocalDate()); } @Test public void skal_mappe_en_inntektsmelding_til_første_refusjonsdato_og_første_innsendelsesdato_når_startdato_permisjon_er_null() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); Kobling kobling1 = new Kobling(ytelseType, saksnummer, koblingReferanse, aktørId); koblingTjeneste.lagre(kobling1); LocalDateTime innsendingstidspunkt = LocalDateTime.now(); Arbeidsgiver virksomhet = Arbeidsgiver.virksomhet(new OrgNummer("910909088")); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medBeløp(BigDecimal.TEN) .medRefusjon(BigDecimal.TEN) .medInnsendingstidspunkt(innsendingstidspunkt) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); iayRepository.lagre(koblingReferanse, ArbeidsforholdInformasjonBuilder.builder(Optional.empty()), List.of(im)); // Act Set<Inntektsmelding> alleIm = iayTjeneste.hentAlleInntektsmeldingerFor(aktørId, saksnummer, ytelseType); Kobling nyesteKobling = koblingTjeneste.hentSisteFor(aktørId, saksnummer, ytelseType).orElseThrow(); RefusjonskravDatoerDto refusjonskravDatoerDto = MapInntektsmeldinger.mapRefusjonskravdatoer(alleIm, iayTjeneste.hentAggregat(nyesteKobling.getKoblingReferanse())); // Assert assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().size()).isEqualTo(1); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getArbeidsgiver().getIdent()).isEqualTo(virksomhet.getIdentifikator()); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteDagMedRefusjonskrav()).isNull(); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteInnsendingAvRefusjonskrav()).isEqualTo(innsendingstidspunkt.toLocalDate()); } @Test public void skal_mappe_ikkje_mappe_refusjonsdatoer_når_siste_inntektsmelding_ikkje_har_refusjonskrav() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); Kobling kobling1 = new Kobling(ytelseType, saksnummer, koblingReferanse, aktørId); koblingTjeneste.lagre(kobling1); LocalDateTime innsendingstidspunkt = LocalDateTime.now(); LocalDate startPermisjon = LocalDate.now().minusDays(10); Arbeidsgiver virksomhet = Arbeidsgiver.virksomhet(new OrgNummer("910909088")); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medBeløp(BigDecimal.TEN) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); Inntektsmelding im2 = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medBeløp(BigDecimal.ZERO) .medRefusjon(BigDecimal.ZERO) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt.plusDays(10)) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id2") .build(); iayRepository.lagre(koblingReferanse, ArbeidsforholdInformasjonBuilder.builder(Optional.empty()), List.of(im)); iayRepository.lagre(koblingReferanse, ArbeidsforholdInformasjonBuilder.builder(Optional.empty()), List.of(im2)); // Act Set<Inntektsmelding> alleIm = iayTjeneste.hentAlleInntektsmeldingerFor(aktørId, saksnummer, ytelseType); Kobling nyesteKobling = koblingTjeneste.hentSisteFor(aktørId, saksnummer, ytelseType).orElseThrow(); RefusjonskravDatoerDto refusjonskravDatoerDto = MapInntektsmeldinger.mapRefusjonskravdatoer(alleIm, iayTjeneste.hentAggregat(nyesteKobling.getKoblingReferanse())); // Assert assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().size()).isEqualTo(0); } @Test public void skal_mappe_til_refusjonskravdatoer_for_flere_inntektsmeldinger_med_refusjonskrav() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); Kobling kobling1 = new Kobling(ytelseType, saksnummer, koblingReferanse, aktørId); koblingTjeneste.lagre(kobling1); LocalDateTime innsendingstidspunkt = LocalDateTime.now(); LocalDate startPermisjon = LocalDate.now().minusDays(10); Arbeidsgiver virksomhet = Arbeidsgiver.virksomhet(new OrgNummer("910909088")); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medBeløp(BigDecimal.TEN) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); Inntektsmelding im2 = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medBeløp(BigDecimal.ZERO) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt.plusDays(10)) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id2") .build(); iayRepository.lagre(koblingReferanse, ArbeidsforholdInformasjonBuilder.builder(Optional.empty()), List.of(im)); iayRepository.lagre(koblingReferanse, ArbeidsforholdInformasjonBuilder.builder(Optional.empty()), List.of(im2)); // Act Set<Inntektsmelding> alleIm = iayTjeneste.hentAlleInntektsmeldingerFor(aktørId, saksnummer, ytelseType); Kobling nyesteKobling = koblingTjeneste.hentSisteFor(aktørId, saksnummer, ytelseType).orElseThrow(); RefusjonskravDatoerDto refusjonskravDatoerDto = MapInntektsmeldinger.mapRefusjonskravdatoer(alleIm, iayTjeneste.hentAggregat(nyesteKobling.getKoblingReferanse())); // Assert assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().size()).isEqualTo(1); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getArbeidsgiver().getIdent()).isEqualTo(virksomhet.getIdentifikator()); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteDagMedRefusjonskrav()).isEqualTo(startPermisjon); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteInnsendingAvRefusjonskrav()).isEqualTo(innsendingstidspunkt.toLocalDate()); } @Test public void skal_mappe_til_refusjonskravdatoer_for_flere_arbeidsgivere_med_refusjonskrav() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); Kobling kobling1 = new Kobling(ytelseType, saksnummer, koblingReferanse, aktørId); koblingTjeneste.lagre(kobling1); LocalDateTime innsendingstidspunkt = LocalDateTime.now(); LocalDate startPermisjon = LocalDate.now().minusDays(10); Arbeidsgiver virksomhet = Arbeidsgiver.virksomhet(new OrgNummer("910909088")); Arbeidsgiver virksomhet2 = Arbeidsgiver.virksomhet(new OrgNummer("995428563")); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medBeløp(BigDecimal.TEN) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); LocalDateTime innsendingstidspunkt2 = innsendingstidspunkt.plusDays(10); Inntektsmelding im2 = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet2) .medBeløp(BigDecimal.ZERO) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt2) .medMottattDato(innsendingstidspunkt2.toLocalDate()) .medJournalpostId("journalpost_id2") .build(); iayRepository.lagre(koblingReferanse, ArbeidsforholdInformasjonBuilder.builder(Optional.empty()), List.of(im, im2)); // Act Set<Inntektsmelding> alleIm = iayTjeneste.hentAlleInntektsmeldingerFor(aktørId, saksnummer, ytelseType); Kobling nyesteKobling = koblingTjeneste.hentSisteFor(aktørId, saksnummer, ytelseType).orElseThrow(); RefusjonskravDatoerDto refusjonskravDatoerDto = MapInntektsmeldinger.mapRefusjonskravdatoer(alleIm, iayTjeneste.hentAggregat(nyesteKobling.getKoblingReferanse())); // Assert assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().size()).isEqualTo(2); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getArbeidsgiver().getIdent()).isEqualTo(virksomhet2.getIdentifikator()); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteDagMedRefusjonskrav()).isEqualTo(startPermisjon); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteInnsendingAvRefusjonskrav()).isEqualTo(innsendingstidspunkt2.toLocalDate()); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(1).getArbeidsgiver().getIdent()).isEqualTo(virksomhet.getIdentifikator()); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(1).getFørsteDagMedRefusjonskrav()).isEqualTo(startPermisjon); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(1).getFørsteInnsendingAvRefusjonskrav()).isEqualTo(innsendingstidspunkt.toLocalDate()); } @Test public void skal_mappe_til_refusjonskravdatoer_for_flere_arbeidsforhold_med_refusjonskrav() { // Arrange Saksnummer saksnummer = new Saksnummer(SAKSNUMMER); KoblingReferanse koblingReferanse = new KoblingReferanse(UUID.randomUUID()); AktørId aktørId = new AktørId("1234123412341"); Kobling kobling1 = new Kobling(ytelseType, saksnummer, koblingReferanse, aktørId); koblingTjeneste.lagre(kobling1); LocalDateTime innsendingstidspunkt = LocalDateTime.now(); LocalDate startPermisjon = LocalDate.now().minusDays(10); Arbeidsgiver virksomhet = Arbeidsgiver.virksomhet(new OrgNummer("910909088")); ArbeidsforholdInformasjonBuilder builder = ArbeidsforholdInformasjonBuilder.builder(Optional.empty()); InternArbeidsforholdRef ref1 = builder.finnEllerOpprett(virksomhet, EksternArbeidsforholdRef.ref("rgjg98jj3j43")); Inntektsmelding im = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medArbeidsforholdId(ref1) .medBeløp(BigDecimal.TEN) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt) .medMottattDato(LocalDate.now()) .medJournalpostId("journalpost_id") .build(); LocalDateTime innsendingstidspunkt2 = innsendingstidspunkt.plusDays(10); InternArbeidsforholdRef ref2 = builder.finnEllerOpprett(virksomhet, EksternArbeidsforholdRef.ref("28r9283yr92")); Inntektsmelding im2 = InntektsmeldingBuilder.builder() .medArbeidsgiver(virksomhet) .medArbeidsforholdId(ref2) .medBeløp(BigDecimal.ZERO) .medRefusjon(BigDecimal.TEN) .medStartDatoPermisjon(startPermisjon) .medInnsendingstidspunkt(innsendingstidspunkt2) .medMottattDato(innsendingstidspunkt2.toLocalDate()) .medJournalpostId("journalpost_id2") .build(); iayRepository.lagre(koblingReferanse, builder, List.of(im, im2)); // Act Set<Inntektsmelding> alleIm = iayTjeneste.hentAlleInntektsmeldingerFor(aktørId, saksnummer, ytelseType); Kobling nyesteKobling = koblingTjeneste.hentSisteFor(aktørId, saksnummer, ytelseType).orElseThrow(); RefusjonskravDatoerDto refusjonskravDatoerDto = MapInntektsmeldinger.mapRefusjonskravdatoer(alleIm, iayTjeneste.hentAggregat(nyesteKobling.getKoblingReferanse())); // Assert assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().size()).isEqualTo(1); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getArbeidsgiver().getIdent()).isEqualTo(virksomhet.getIdentifikator()); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteDagMedRefusjonskrav()).isEqualTo(startPermisjon); assertThat(refusjonskravDatoerDto.getRefusjonskravDatoer().get(0).getFørsteInnsendingAvRefusjonskrav()).isEqualTo(innsendingstidspunkt.toLocalDate()); } }
59.9375
171
0.748566
b01668e97eb24dd591d7fb4ae57af62399f1e682
1,095
package tech.lancelot.controller.blog; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import tech.lancelot.annotations.Log; import tech.lancelot.annotations.restful.AnonymousGetMapping; import tech.lancelot.dto.blog.CategoryQueryCriteria; import tech.lancelot.dto.blog.TagQueryCriteria; import tech.lancelot.service.blog.CategoryService; import tech.lancelot.service.blog.TagService; import tech.lancelot.vo.Result; /** * @author lancelot */ @Api(tags = "博客:标签管理") @RestController @RequestMapping("/api/tags") @RequiredArgsConstructor public class TagController { private final TagService tagService; @Log("博客|查询标签") @ApiOperation("博客|查询标签") @GetMapping @AnonymousGetMapping public Result getAll() { return Result.success(tagService.getAll()); } }
29.594595
62
0.795434
d82ec73ff16c0ead848f52bbf7442b78f46bb286
1,319
/** * */ package com.sm.common.libs.codec; import com.sm.common.libs.exception.MessageException; /** * 解码异常 * * @author <a href="[email protected]">xc</a> * @version create on 2016年11月11日 下午2:58:16 */ public class DecodeException extends MessageException { /** * */ private static final long serialVersionUID = -4128289234956207576L; /** * 构造一个空的异常. */ public DecodeException() { super(); } /** * 构造一个异常, 指明异常的详细信息. * * @param message 详细信息 */ public DecodeException(String message) { super(message); } /** * 构造一个异常, 指明引起这个异常的起因. * * @param cause 异常的起因 */ public DecodeException(Throwable cause) { super(cause); } /** * 构造一个异常, 指明引起这个异常的起因. * * @param message 详细信息 * @param cause 异常的起因 */ public DecodeException(String message, Throwable cause) { super(message, cause); } /** * 构造一个异常, 参数化详细信息 * * @param message 详细信息 * @param params 参数表 */ public DecodeException(String message, Object... params) { super(message, params); } /** * 构造一个异常, 参数化详细信息,指明引起这个异常的起因 * * @param message 详细信息 * @param cause 异常的起因 * @param params 参数表 */ public DecodeException(String message, Throwable cause, Object... params) { super(message, cause, params); } }
16.910256
77
0.615618
ca743a397d4efcb998c474ccc883d96fef5a8532
949
package autodiff.nodes; import java.util.Arrays; /** * @author codistmonk (creation 2016-07-11) */ public final class Mapping extends AbstractNode<Mapping> { private String functionName; public Mapping() { super(Arrays.asList((Node<?>) null)); } public final Mapping setArgument(final Node<?> argument) { this.getArguments().set(0, argument); return this; } public final Node<?> getArgument() { return this.getArguments().get(0); } @Override public final <V> V accept(final NodeVisitor<V> visitor) { return visitor.visit(this); } public final String getFunctionName() { return this.functionName; } public final Mapping setFunctionName(final String functionName) { this.functionName = functionName; return this; } @Override public final Mapping autoShape() { return this.setShape(this.getArgument().getShape()); } private static final long serialVersionUID = -2566458738220643925L; }
19.367347
68
0.711275
37933be1dfe9319951ec152906ba6eb26a387ce1
2,594
package org.consumersunion.stories.server.security.authentication; import javax.inject.Inject; import org.apache.commons.validator.routines.EmailValidator; import org.consumersunion.stories.common.shared.model.CredentialedUser; import org.consumersunion.stories.server.persistence.CredentialedUserPersister; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; @Component public class CustomAuthenticationProvider implements AuthenticationProvider { private final EmailValidator emailValidator; private final CredentialedUserPersister credentialedUserPersister; @Inject public CustomAuthenticationProvider( EmailValidator emailValidator, CredentialedUserPersister credentialedUserPersister) { this.emailValidator = emailValidator; this.credentialedUserPersister = credentialedUserPersister; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); CredentialedUser user; if (emailValidator.isValid(username)) { user = credentialedUserPersister.getByEmail(username, false); } else { user = credentialedUserPersister.getByHandle(username, false); } if (user == null) { throw new UsernameNotFoundException("Invalid Username or Password. Please try again."); } authentication = new UsernamePasswordAuthenticationToken(user.getUser().getHandle(), password); if (!BCrypt.checkpw(password, user.getPasswordHash())) { throw new BadCredentialsException("Invalid Username or Password. Please try again."); } Authentication customAuthentication = new CustomUserAuthentication(authentication); customAuthentication.setAuthenticated(true); return customAuthentication; } @Override public boolean supports(Class<? extends Object> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } }
42.52459
103
0.771396
4c6997d579a197838a67583ad73a6987a3625b9d
149
package com.stxia.textlib; import android.util.Log; public class textutlis { public static void log(){ Log.d("测试成功","测试成功"); } }
14.9
31
0.624161
e50e5715176b40befbba4d0dd0e96e53274964a4
4,214
/** * PermissionsEx * Copyright (C) zml and PermissionsEx 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 ninja.leaping.permissionsex.data; import com.google.common.collect.ImmutableList; import ninja.leaping.permissionsex.PermissionsEx; import ninja.leaping.permissionsex.PermissionsExTest; import ninja.leaping.permissionsex.backend.DataStore; import ninja.leaping.permissionsex.backend.memory.MemoryDataStore; import ninja.leaping.permissionsex.config.PermissionsExConfiguration; import ninja.leaping.permissionsex.exception.PEBKACException; import ninja.leaping.permissionsex.subject.CalculatedSubject; import ninja.leaping.permissionsex.exception.PermissionsLoadingException; import ninja.leaping.permissionsex.subject.SubjectType; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; import static ninja.leaping.permissionsex.PermissionsEx.GLOBAL_CONTEXT; import static org.junit.Assert.assertEquals; public class SubjectDataBakerTest extends PermissionsExTest { /** * Arrangement: * parent * child * subject *ignored inheritance permission in parent does not have effect unless checked in parent or child * ignored inheritance permission in child has effect in both */ @Test public void testIgnoredInheritancePermissions() throws ExecutionException, PermissionsLoadingException, InterruptedException { SubjectType groupCache = getManager().getSubjects(PermissionsEx.SUBJECTS_GROUP); CalculatedSubject parentS = groupCache.get("parent").thenCompose(parent -> parent.data().update(old -> old.setPermission(GLOBAL_CONTEXT, "#test.permission.parent", 1)).thenApply(data -> parent)).get(); CalculatedSubject childS = groupCache.get("child").thenCompose(child -> child.data().update(old -> old.addParent(GLOBAL_CONTEXT, groupCache.getTypeInfo().getTypeName(), parentS.getIdentifier().getValue()) .setPermission(GLOBAL_CONTEXT, "#test.permission.child", 1) ).thenApply(data -> child)).get(); CalculatedSubject subjectS = groupCache.get("subject").thenCompose(subject -> subject.data().update(old -> old.addParent(GLOBAL_CONTEXT, childS.getIdentifier().getKey(), childS.getIdentifier().getValue())).thenApply(data -> subject)).get(); assertEquals(1, parentS.getPermissions(GLOBAL_CONTEXT).get("test.permission.parent")); assertEquals(1, childS.getPermissions(GLOBAL_CONTEXT).get("test.permission.parent")); assertEquals(1, childS.getPermissions(GLOBAL_CONTEXT).get("test.permission.child")); assertEquals(0, subjectS.getPermissions(GLOBAL_CONTEXT).get("test.permission.parent")); assertEquals(1, subjectS.getPermissions(GLOBAL_CONTEXT).get("test.permission.child")); } @Override protected PermissionsExConfiguration populate() { return new PermissionsExConfiguration() { @Override public DataStore getDataStore(String name) { return null; } @Override public DataStore getDefaultDataStore() { return new MemoryDataStore(); } @Override public boolean isDebugEnabled() { return false; } @Override public List<String> getServerTags() { return ImmutableList.of(); } @Override public void validate() throws PEBKACException { } @Override public PermissionsExConfiguration reload() throws IOException { return this; } }; } }
42.565657
248
0.709065
78380c3ed929df63d717aa31158716e1c7acb081
3,951
package de.uniulm.omi.cloudiator.lance.lca.containers.plain; import java.util.Map; import org.junit.Test; import de.uniulm.omi.cloudiator.domain.OperatingSystem; import de.uniulm.omi.cloudiator.domain.OperatingSystemArchitecture; import de.uniulm.omi.cloudiator.domain.OperatingSystemFamily; import de.uniulm.omi.cloudiator.domain.OperatingSystemImpl; import de.uniulm.omi.cloudiator.domain.OperatingSystemVersions; import de.uniulm.omi.cloudiator.lance.container.standard.ErrorAwareContainer; import de.uniulm.omi.cloudiator.lance.lca.GlobalRegistryAccessor; import de.uniulm.omi.cloudiator.lance.lca.container.ComponentInstanceId; import de.uniulm.omi.cloudiator.lance.lca.container.ContainerException; import de.uniulm.omi.cloudiator.lance.lca.container.port.NetworkHandler; import de.uniulm.omi.cloudiator.lance.lca.containers.dummy.DummyInterceptor; import de.uniulm.omi.cloudiator.lance.lca.registry.RegistrationException; import de.uniulm.omi.cloudiator.lance.lifecycle.ExecutionContext; import de.uniulm.omi.cloudiator.lance.lifecycle.LifecycleController; import de.uniulm.omi.cloudiator.lance.lifecycles.CoreElements; import de.uniulm.omi.cloudiator.lance.lifecycles.LifecycleStoreCreator; public class PlainContainerTest { public volatile DummyInterceptor interceptor; public volatile PlainContainerLogic containerLogic; private volatile CoreElements core; public volatile LifecycleStoreCreator creator; private volatile ExecutionContext ctx; private volatile ErrorAwareContainer<PlainContainerLogic> controller; private static final int DEFAULT_PROPERTIES = 5; private static final String INITIAL_LOCAL_ADDRESS = "<unknown>"; private volatile Map<ComponentInstanceId, Map<String, String>> dumb; private void init(boolean creatRegistry) { dumb = null; core = new CoreElements(creatRegistry); OperatingSystem os = new OperatingSystemImpl( OperatingSystemFamily.WINDOWS, OperatingSystemArchitecture.AMD64, OperatingSystemVersions.of(7,null)); ctx = new ExecutionContext(os, null); creator = new LifecycleStoreCreator(); creator.addDefaultStartDetector(); } /* copied from PlainContainerManager createNewContainer*/ private void createNewContainer() throws ContainerException { PlainShellFactory plainShellFactory = new TestPlainShellFactory(); GlobalRegistryAccessor accessor = new GlobalRegistryAccessor(core.ctx, core.comp, CoreElements.componentInstanceId); NetworkHandler networkHandler = core.networkHandler; PlainContainerLogic.Builder builder = new PlainContainerLogic.Builder(); //split for better readability builder = builder.cInstId(CoreElements.componentInstanceId).deplComp(core.comp).deplContext(core.ctx).operatingSys(ctx.getOperatingSystem()); containerLogic = builder.nwHandler(networkHandler).plShellFac(plainShellFactory).hostContext(CoreElements.context).build(); ExecutionContext executionContext = new ExecutionContext(ctx.getOperatingSystem(), plainShellFactory); LifecycleController lifecycleController = new LifecycleController(core.comp.getLifecycleStore(), containerLogic, accessor, executionContext, CoreElements.context); try { accessor.init(CoreElements.componentInstanceId); } catch (RegistrationException re) { throw new ContainerException("cannot start container, because registry not available", re); } controller = new ErrorAwareContainer<PlainContainerLogic>(CoreElements.componentInstanceId, containerLogic, networkHandler, lifecycleController, accessor, false); controller.create(); } @Test public void testInit() throws ContainerException{ init(true); createNewContainer(); } }
42.945652
153
0.756517
deba59e063affa689c7ff98e5469d2ce09db34d3
1,981
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.pds.client.models; import com.aliyun.tea.*; /** * 打包下载 */ public class CCPArchiveFilesRequest extends TeaModel { @NameInMap("httpheaders") public java.util.Map<String, String> httpheaders; // addition_data @NameInMap("addition_data") public java.util.Map<String, ?> additionData; // drive_id @NameInMap("drive_id") @Validation(pattern = "[0-9]+") public String driveId; @NameInMap("files") public java.util.List<FileInfo> files; // file_name @NameInMap("name") @Validation(maxLength = 1024, minLength = 1) public String name; public static CCPArchiveFilesRequest build(java.util.Map<String, ?> map) throws Exception { CCPArchiveFilesRequest self = new CCPArchiveFilesRequest(); return TeaModel.build(map, self); } public CCPArchiveFilesRequest setHttpheaders(java.util.Map<String, String> httpheaders) { this.httpheaders = httpheaders; return this; } public java.util.Map<String, String> getHttpheaders() { return this.httpheaders; } public CCPArchiveFilesRequest setAdditionData(java.util.Map<String, ?> additionData) { this.additionData = additionData; return this; } public java.util.Map<String, ?> getAdditionData() { return this.additionData; } public CCPArchiveFilesRequest setDriveId(String driveId) { this.driveId = driveId; return this; } public String getDriveId() { return this.driveId; } public CCPArchiveFilesRequest setFiles(java.util.List<FileInfo> files) { this.files = files; return this; } public java.util.List<FileInfo> getFiles() { return this.files; } public CCPArchiveFilesRequest setName(String name) { this.name = name; return this; } public String getName() { return this.name; } }
26.065789
95
0.655225
387b0628e1ebd424e073f05ec4818483f8a82925
686
package com.tom.java.test.leetcode; public class Problem409 { public static void main(String[] args) { String str = "abccccdd"; int len = longestPalindrome(str); System.out.println(len); } public static int longestPalindrome(String s) { if (s == null || s.length() == 0) { return 0; } int[] count = new int[128]; char[] charArr = s.toCharArray(); for (char c : charArr) { count[c]++; } int ans = 0; for (int v : count) { ans += v / 2 * 2; if (ans % 2 == 0 && v % 2 == 1) ans++; } return ans; } }
21.4375
51
0.453353
12c90e202a4661f5e53f86d0f9064d4a68808863
5,442
package org.lasencinas.cotxox.ServiceTest.Driver; import org.junit.Test; import org.junit.runner.RunWith; import org.lasencinas.cotxox.Model.Driver; import org.lasencinas.cotxox.Service.Driver.DriverService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @Sql(statements = { "delete from driver", "insert into driver values (1, 0, '8255 HVT', '500 Abarth', 'Érik Vila Diaz', 4.1, 1)", "insert into driver values (2, 1, '8221 LJS', 'Alfa Romeo Giulietta', 'Elena Perez Crespo', 4.35, 1);" }) public class DriverServiceImplTest { @Autowired public DriverService driverService; @Test public void releaseDriverShouldSetDriverBussyToFalse() { /*------------------- Given --------------------- */ Driver driver = driverService.findDriverById((long) 1); driver.setBussy(true); /*------------------- When --------------------- */ driverService.releaseDriver(driver); /*------------------- Then --------------------- */ assertFalse(driver.isBussy()); /*------------------- Given --------------------- */ Driver driverTest = driverService.findDriverById((long) 2); driver.setBussy(true); /*------------------- When --------------------- */ driverService.releaseDriver(driverTest); /*------------------- Then --------------------- */ assertFalse(driverTest.isBussy()); } @Test public void TakeDriverShouldSetDriverBussyToTrue() { /*------------------- Given --------------------- */ Driver driver = driverService.findDriverById((long) 1); driver.setBussy(false); /*------------------- When --------------------- */ driverService.takeDriver(driver); /*------------------- Then --------------------- */ assertTrue(driver.isBussy()); /*------------------- 2ndTest --------------------- */ /*------------------- Given --------------------- */ Driver driverTest = driverService.findDriverById((long) 2); driver.setBussy(false); /*------------------- When --------------------- */ driverService.takeDriver(driverTest); /*------------------- Then --------------------- */ assertTrue(driverTest.isBussy()); } @Test public void putDriverTest() { /*------------------- Given --------------------- */ Driver driver = driverService.findDriverById((long) 1); /*------------------- When --------------------- */ assertEquals(1, driver.getValuations()); assertEquals(4.1, driver.getRate(), 0); driverService.putDriver(driver, 4.9); /*------------------- Then --------------------- */ assertEquals(2, driver.getValuations()); assertEquals(4.5, driver.getRate(), 0); /*------------------- 2ndTest --------------------- */ /*------------------- Given --------------------- */ Driver driverTest = driverService.findDriverById((long) 2); /*------------------- When --------------------- */ assertEquals(1, driverTest.getValuations()); assertEquals(4.35, driverTest.getRate(), 0); driverService.putDriver(driverTest, 3.20); /*------------------- Then --------------------- */ assertEquals(2, driverTest.getValuations()); assertEquals(3.775, driverTest.getRate(), 0); } @Test public void findAllByBussyShouldReturnsDriversIsBussyEqualsFalse() { /*------------------- Given --------------------- */ Driver driver = driverService.findDriverById((long) 1); Driver driverTest = driverService.findDriverById((long) 2); /*------------------- When --------------------- */ driverService.takeDriver(driver); driverService.releaseDriver(driverTest); /*------------------- Then --------------------- */ assertEquals(1, driverService.findAllbyBussy().size()); assertTrue(driverService.findAllbyBussy().get(0).getId() == driverTest.getId()); assertFalse(driverService.findAllbyBussy().get(0).getId() == driver.getId()); /*------------------- 2ndTest --------------------- */ /*------------------- Given --------------------- */ //the same objects than in the first test but with other values /*------------------- When --------------------- */ driverService.takeDriver(driverTest); driverService.releaseDriver(driver); /*------------------- Then --------------------- */ assertEquals(1, driverService.findAllbyBussy().size()); assertTrue(driverService.findAllbyBussy().get(0).getId() == driver.getId()); assertFalse(driverService.findAllbyBussy().get(0).getId() == driverTest.getId()); } }
30.233333
111
0.482359
00e54b51315d3e3a795169ddf3045157d7e6fc6a
5,360
package de.leihwelt.android.gl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.microedition.khronos.opengles.GL10; import de.leihwelt.android.droidkobanpro.Droidkoban; import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLUtils; public class Texture { private static Texture lastTexture = null; public enum TextureFilter { Nearest, Linear, MipMap } public enum TextureWrap { ClampToEdge, Wrap } private int handle; private GL10 gl; // original image size private int height; private int width; private String file = null; private int resource = -1; private AssetManager am; private Resources r; // public static Texture load(GL10 gl, InputStream textureData) { // Bitmap bitmap = BitmapFactory.decodeStream(textureData); // Texture tex = new Texture(gl, bitmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.Wrap, TextureWrap.Wrap); // bitmap.recycle(); // return tex; // } public int getTextureId() { return this.handle; } public Texture(GL10 gl, AssetManager am, String file) throws IOException { this.file = file; this.am = am; recreate(gl); } public Texture(GL10 gl, Resources r, int resource) throws IOException { this.resource = resource; this.r = r; recreate(gl); } public void recreate(GL10 gl) throws IOException { Bitmap bitmap = null; if (r != null && resource > 0) { bitmap = BitmapFactory.decodeStream(r.openRawResource(resource)); } else if (am != null && file != null) { bitmap = BitmapFactory.decodeStream(am.open(file)); } if (bitmap != null) { create(gl, bitmap, TextureFilter.Linear, TextureFilter.Linear, TextureWrap.Wrap, TextureWrap.Wrap); bitmap.recycle(); } } private Texture(GL10 gl, Bitmap image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap sWrap, TextureWrap tWrap) { create(gl, image, minFilter, maxFilter, sWrap, tWrap); } private void create(GL10 gl, Bitmap image, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap sWrap, TextureWrap tWrap) { this.gl = gl; int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); handle = textures[0]; this.width = image.getWidth(); this.height = image.getHeight(); gl.glBindTexture(GL10.GL_TEXTURE_2D, handle); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, getTextureFilter(minFilter)); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, getTextureFilter(maxFilter)); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, getTextureWrap(sWrap)); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, getTextureWrap(tWrap)); gl.glMatrixMode(GL10.GL_TEXTURE); gl.glLoadIdentity(); buildMipmap(gl, image); image.recycle(); } public Texture(GL10 gl, int width, int height, TextureFilter minFilter, TextureFilter maxFilter, TextureWrap sWrap, TextureWrap tWrap) { Bitmap.Config config = Bitmap.Config.ARGB_8888; Bitmap image = Bitmap.createBitmap(width, height, config); create(gl, image, minFilter, maxFilter, sWrap, tWrap); } private int getTextureFilter(TextureFilter filter) { if (filter == TextureFilter.Linear) return GL10.GL_LINEAR; else if (filter == TextureFilter.Nearest) return GL10.GL_NEAREST; else return GL10.GL_LINEAR_MIPMAP_NEAREST; } private int getTextureWrap(TextureWrap wrap) { if (wrap == TextureWrap.ClampToEdge) return GL10.GL_CLAMP_TO_EDGE; else return GL10.GL_REPEAT; } private void buildMipmap(GL10 gl, Bitmap bitmap) { int level = 0; int height = bitmap.getHeight(); int width = bitmap.getWidth(); while (height >= 1 || width >= 1 && level < 4) { GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); if (height == 1 || width == 1) { break; } level++; if (height > 1) height /= 2; if (width > 1) width /= 2; Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true); bitmap.recycle(); bitmap = bitmap2; } } /** * Draws the given image to the texture * * @param gl * @param bitmap * @param x * @param y */ public void draw(Object bmp, int x, int y) { gl.glBindTexture(GL10.GL_TEXTURE_2D, handle); Bitmap bitmap = (Bitmap) bmp; int level = 0; int height = bitmap.getHeight(); int width = bitmap.getWidth(); while (height >= 1 || width >= 1 && level < 4) { GLUtils.texSubImage2D(GL10.GL_TEXTURE_2D, level, x, y, (Bitmap) bitmap); if (height == 1 || width == 1) { break; } level++; if (height > 1) height /= 2; if (width > 1) width /= 2; Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true); bitmap.recycle(); bitmap = bitmap2; } } /** * Binds the texture * * @param gl */ public void bind() { if (Texture.lastTexture != this) { gl.glBindTexture(GL10.GL_TEXTURE_2D, handle); Texture.lastTexture = this; } } /** * Disposes the texture and frees the associated resourcess * * @param gl */ public void dispose() { int[] textures = { handle }; gl.glDeleteTextures(1, textures, 0); handle = 0; } public int getHeight() { return height; } public int getWidth() { return width; } }
24.144144
137
0.7
201b1f5447ec449cf065d13786a710e8ccd89211
130
package cord.common; public enum NonBaseNodeLabels { SecurityGroup, Permission, canRead, canEdit, Active, Inactive }
11.818182
31
0.730769
898aeca044c2661acdd9c2b91baa72b7944b853f
7,311
/** * Copyright 2012, Board of Regents of the University of * Wisconsin System. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Board of Regents of the University of Wisconsin * System 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 edu.wisc.doit.tcrypt.cli; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.bouncycastle.crypto.InvalidCipherTextException; import edu.wisc.doit.tcrypt.BouncyCastleTokenDecrypter; import edu.wisc.doit.tcrypt.BouncyCastleTokenEncrypter; import edu.wisc.doit.tcrypt.TokenDecrypter; import edu.wisc.doit.tcrypt.TokenEncrypter; public class TokenCrypt { public static void main(String[] args) throws IOException { // create Options object final Options options = new Options(); // operation opt group final OptionGroup cryptTypeGroup = new OptionGroup(); cryptTypeGroup.addOption(new Option("e", "encrypt", false, "Encrypt a token")); cryptTypeGroup.addOption(new Option("d", "decrypt", false, "Decrypt a token")); cryptTypeGroup.addOption(new Option("c", "check", false, "Check if the string looks like an encrypted token")); cryptTypeGroup.setRequired(true); options.addOptionGroup(cryptTypeGroup); // token source opt group final OptionGroup tokenGroup = new OptionGroup(); final Option tokenOpt = new Option("t", "token", true, "The token(s) to operate on"); tokenOpt.setArgs(Option.UNLIMITED_VALUES); tokenGroup.addOption(tokenOpt); final Option tokenFileOpt = new Option("f", "file", true, "A file with one token per line to operate on, if - is specified stdin is used"); tokenGroup.addOption(tokenFileOpt); tokenGroup.setRequired(true); options.addOptionGroup(tokenGroup); final Option keyOpt = new Option("k", "keyFile", true, "Key file to use. Must be a private key for decryption and a public key for encryption"); keyOpt.setRequired(true); options.addOption(keyOpt); // create the parser final CommandLineParser parser = new GnuParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { // automatically generate the help statement System.err.println(exp.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + TokenCrypt.class.getName(), options, true); System.exit(1); } final Reader keyReader = createKeyReader(line); final TokenHandler tokenHandler = createTokenHandler(line, keyReader); if (line.hasOption("t")) { //tokens on cli final String[] tokens = line.getOptionValues("t"); for (final String token : tokens) { handleToken(tokenHandler, token); } } else { //tokens from a file final String tokenFile = line.getOptionValue("f"); final BufferedReader fileReader; if ("-".equals(tokenFile)) { fileReader = new BufferedReader(new InputStreamReader(System.in)); } else { fileReader = new BufferedReader(new FileReader(tokenFile)); } while (true) { final String token = fileReader.readLine(); if (token == null) { break; } handleToken(tokenHandler, token); } } } private static void handleToken(final TokenHandler tokenHandler, final String token) { try { final String convertedToken = tokenHandler.handleToken(token); System.out.println(token + "=" + convertedToken); } catch (InvalidCipherTextException e) { System.out.println("INVALID TOKEN " + token + " - " + e.getMessage()); } } private static TokenHandler createTokenHandler(CommandLine line, final Reader keyReader) throws IOException { final TokenHandler tokenHandler; if (line.hasOption("e")) { final TokenEncrypter tokenEncrypter = new BouncyCastleTokenEncrypter(keyReader); tokenHandler = new TokenHandler() { @Override public String handleToken(String token) throws InvalidCipherTextException { return tokenEncrypter.encrypt(token); } }; } else { final TokenDecrypter tokenDecrypter = new BouncyCastleTokenDecrypter(keyReader); if (line.hasOption("c")) { tokenHandler = new TokenHandler() { @Override public String handleToken(String token) throws InvalidCipherTextException { final boolean encryptedToken = tokenDecrypter.isEncryptedToken(token); return Boolean.toString(encryptedToken); } }; } else { tokenHandler = new TokenHandler() { @Override public String handleToken(String token) throws InvalidCipherTextException { return tokenDecrypter.decrypt(token); } }; } } return tokenHandler; } private static Reader createKeyReader(CommandLine line) throws IOException { final Reader keyReader; final String keyFile = line.getOptionValue("k"); try { final String keyData = FileUtils.readFileToString(new File(keyFile)); keyReader = new StringReader(keyData); } catch (IOException e) { throw new IOException("Failed to read keyFile: " + keyFile, e); } return keyReader; } private static interface TokenHandler { String handleToken(String token) throws InvalidCipherTextException; } }
39.518919
152
0.624949
e39e22581b3b18cd3eebee5e43ffd98384f72f76
23,193
/* The MIT License (MIT) Copyright (c) 2020 Pierre Lindenbaum Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.lindenb.jvarkit.tools.misc; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import com.beust.jcommander.Parameter; import com.github.lindenb.jvarkit.io.ArchiveFactory; import com.github.lindenb.jvarkit.io.IOUtils; import com.github.lindenb.jvarkit.io.NullOuputStream; import com.github.lindenb.jvarkit.lang.JvarkitException; import com.github.lindenb.jvarkit.lang.StringUtils; import com.github.lindenb.jvarkit.samtools.util.SimpleInterval; import com.github.lindenb.jvarkit.samtools.util.SimplePosition; import com.github.lindenb.jvarkit.util.bio.DistanceParser; import com.github.lindenb.jvarkit.util.bio.fasta.ContigNameConverter; import com.github.lindenb.jvarkit.util.bio.structure.Gene; import com.github.lindenb.jvarkit.util.bio.structure.GtfReader; import com.github.lindenb.jvarkit.util.bio.structure.Intron; import com.github.lindenb.jvarkit.util.bio.structure.Transcript; import com.github.lindenb.jvarkit.util.jcommander.Launcher; import com.github.lindenb.jvarkit.util.jcommander.NoSplitter; import com.github.lindenb.jvarkit.util.jcommander.Program; import com.github.lindenb.jvarkit.util.log.Logger; import com.github.lindenb.jvarkit.util.samtools.ContigDictComparator; import com.github.lindenb.jvarkit.variant.variantcontext.AttributeCleaner; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.util.CloseableIterator; import htsjdk.samtools.util.CloserUtil; import htsjdk.samtools.util.FileExtensions; import htsjdk.samtools.util.Locatable; import htsjdk.tribble.index.tabix.TabixFormat; import htsjdk.tribble.index.tabix.TabixIndexCreator; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.writer.Options; import htsjdk.variant.variantcontext.writer.VariantContextWriter; import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder; import htsjdk.variant.vcf.VCFFileReader; import htsjdk.variant.vcf.VCFHeader; import htsjdk.variant.vcf.VCFHeaderLine; /** BEGIN_DOC ### Example ``` $ java -jar dist/vcfgtfsplitter.jar -m jeter.manifest --gtf input.gtf.gz -o jeter.zip src/test/resources/test_vcf01.vcf $ unzip -l jeter.zip Archive: jeter.zip Length Date Time Name --------- ---------- ----- ---- 4741 2019-11-18 10:52 d2/a0884d9bf86378a2cd0bfacef19723/ENSG00000188157.vcf.gz 4332 2019-11-18 10:52 4d/11ff4f2413d4a369ee9a51192acad3/ENSG00000131591.vcf.gz --------- ------- 9073 2 files $ column -t jeter.manifest #chrom start end Gene-Id Gene-Name Gene-Biotype path Count_Variants 1 955502 991496 ENSG00000188157 AGRN protein_coding d2/a0884d9bf86378a2cd0bfacef19723/ENSG00000188157.vcf.gz 20 1 1017197 1051741 ENSG00000131591 C1orf159 protein_coding 4d/11ff4f2413d4a369ee9a51192acad3/ENSG00000131591.vcf.gz 6 $ java -jar dist/vcfgtfsplitter.jar -T --index --gtf jeter.gtf -m jeter.manifest -o jeter.zip src/test/resources/test_vcf01.vcf $ unzip -l jeter.zip Archive: jeter.zip Length Date Time Name --------- ---------- ----- ---- 4749 2019-11-18 10:56 93/00d3aa560bdbe3b3ff964e24303107/ENST00000379370.vcf.gz 4749 2019-11-18 10:56 93/00d3aa560bdbe3b3ff964e24303107/ENST00000379370.vcf.gz.tbi 3108 2019-11-18 10:56 6d/001c37d11b192bcd77ac089ec258f2/ENST00000477585.vcf.gz (...) 2969 2019-11-18 10:56 3a/8e697b04e03716942b362afbe7ee51/ENST00000472741.vcf.gz 2969 2019-11-18 10:56 3a/8e697b04e03716942b362afbe7ee51/ENST00000472741.vcf.gz.tbi 2969 2019-11-18 10:56 2c/4ced556d7722b978453c38d5525ee0/ENST00000480643.vcf.gz 2969 2019-11-18 10:56 2c/4ced556d7722b978453c38d5525ee0/ENST00000480643.vcf.gz.tbi --------- ------- 175030 46 files $ column -t jeter.manifest #chrom start end Gene-Id Gene-Name Gene-Biotype Transcript-Id path Count_Variants 1 955502 991496 ENSG00000188157 AGRN protein_coding ENST00000379370 93/00d3aa560bdbe3b3ff964e24303107/ENST00000379370.vcf.gz 20 1 969485 976105 ENSG00000188157 AGRN protein_coding ENST00000477585 6d/001c37d11b192bcd77ac089ec258f2/ENST00000477585.vcf.gz 3 1 970246 976777 ENSG00000188157 AGRN protein_coding ENST00000469403 a9/fe6f84e1a425797d5b58ceae3a8313/ENST00000469403.vcf.gz 2 1 983908 984774 ENSG00000188157 AGRN protein_coding ENST00000492947 55/b5a514c94417efe2632aba379d8247/ENST00000492947.vcf.gz 1 1 1017197 1051461 ENSG00000131591 C1orf159 protein_coding ENST00000379339 7b/26f9faff411f6e056fefc89cd15a24/ENST00000379339.vcf.gz 6 1 1017197 1051736 ENSG00000131591 C1orf159 protein_coding ENST00000448924 56/fad8194b90771b0c3e931bc4772be1/ENST00000448924.vcf.gz 6 1 1017197 1051736 ENSG00000131591 C1orf159 protein_coding ENST00000294576 df/3aa6bebac650a6c9f59409521ae17d/ENST00000294576.vcf.gz 6 (...) ``` # screenshot * https://twitter.com/yokofakun/status/1197149666237911040 ![https://twitter.com/yokofakun/status/1197149666237911040](https://pbs.twimg.com/media/EJ0hReMX0AcaBoq?format=png&name=small) * https://twitter.com/yokofakun/status/1199621057533140992 ![https://twitter.com/yokofakun/status/1199621057533140992](https://twitter.com/i/status/1199621057533140992) END_DOC */ @Program( name="vcfgtfsplitter", description="Split VCF+VEP by gene/transcript using a GTF file.", creationDate="20191118", modificationDate="20191128", keywords= {"genes","vcf","split","gtf"} ) public class VcfGtfSplitter extends Launcher { private static final Logger LOG = Logger.build(VcfGtfSplitter.class).make(); @Parameter(names={"-o","--output"},description= ArchiveFactory.OPT_DESC,required=true) private Path outputFile = null; @Parameter(names={"-m","--manifest"},description="Manifest Bed file output containing chrom/start/end of each gene") private Path manifestFile = null; @Parameter(names={"-T","--transcript"},description= "split by transcript. (default is to split per gene)") private boolean split_by_transcript = false; @Parameter(names={"-g","-G","--gtf"},description=GtfReader.OPT_DESC,required=true) private Path gtfPath = null; @Parameter(names={"--ignore-filtered"},description="Ignore FILTERED variant") private boolean ignoreFiltered = false; @Parameter(names={"-C","--contig","--chromosome"},description="Limit to those contigs.") private Set<String> limitToContigs = new HashSet<>(); @Parameter(names={"--bcf"},description="Use bcf format") private boolean use_bcf= false; @Parameter(names={"--index"},description="index files") private boolean index_vcf= false; @Parameter(names={"--features"},description="Features to keep. Comma separated values. A set of 'cds,exon,intron,transcript,utr,utr5,utr3,stop,start,upstream,downstream,splice'") private String featuresString = "cds,exon,intron,transcript,cds_utr,cds_utr5,cds_utr3,utr5,utr3,stop,start"; @Parameter(names={"--force"},description="Force writing a gene/transcript even if there is no variant.") private boolean enable_empty_vcf = false; @Parameter(names={"--coding"},description="Only use gene_biotype=\"protein_coding\".") private boolean protein_coding_only = false; @Parameter(names={"--upstream","--downstream"},description="length for upstream and downstream features. "+DistanceParser.OPT_DESCRIPTION,converter=DistanceParser.StringConverter.class,splitter=NoSplitter.class) private int xxxxstream_length = 1_000; @Parameter(names={"--splice"},description="distance to splice site for 'splice' feature. "+DistanceParser.OPT_DESCRIPTION,converter=DistanceParser.StringConverter.class,splitter=NoSplitter.class) private int split_length = 5; @Parameter(names={"--xannotate"},description="Remove annotations. "+AttributeCleaner.OPT_DESC) private String xannotatePattern= null; private boolean use_cds = false; private boolean use_intron = false; private boolean use_exon = false; private boolean use_stop = false; private boolean use_start = false; private boolean use_utr5 = false; private boolean use_utr3 = false; private boolean use_cds_utr5 = false; private boolean use_cds_utr3 = false; private boolean use_downstream = false; private boolean use_upstream = false; private boolean use_splice = false; private AttributeCleaner attCleaner = null; /** abstract splitter for Gene or Transcript */ private abstract class AbstractSplitter { void addMetadata(final VCFHeader h) { final Gene gene = this.getGene(); h.addMetaDataLine(new VCFHeaderLine("split.gene-id", gene.getId())); h.addMetaDataLine(new VCFHeaderLine("split.gene-name", gene.getGeneName())); h.addMetaDataLine(new VCFHeaderLine("split.gene-biotype", gene.getGeneBiotype())); } abstract Locatable getInterval(); abstract boolean accept(final VariantContext ctx); abstract String getId(); void printManifest(final PrintWriter pw) { final Gene gene = this.getGene(); pw.print(gene.getId()); pw.print("\t"); pw.print(gene.getGeneName()); pw.print("\t"); pw.print(gene.getGeneBiotype()); } abstract Gene getGene(); } /** splitter for transcript */ private class TranscriptSplitter extends AbstractSplitter { private final Transcript transcript; TranscriptSplitter(final Transcript transcript) { this.transcript = transcript; } @Override Locatable getInterval() { return this.transcript; } @Override Gene getGene() { return transcript.getGene(); } @Override void addMetadata(final VCFHeader h) { super.addMetadata(h); h.addMetaDataLine(new VCFHeaderLine("split.transcript-id", transcript.getId())); } @Override boolean accept(final VariantContext ctx) { return testTranscript(this.transcript,ctx); } @Override String getId() { return transcript.getId(); } @Override void printManifest(final PrintWriter pw) { super.printManifest(pw); pw.print("\t"); pw.print(transcript.getId()); } } /** splitter for gene */ private class GeneSplitter extends AbstractSplitter { private final Gene gene; GeneSplitter(final Gene gene) { this.gene = gene; } @Override Locatable getInterval() { return this.gene; } @Override Gene getGene() { return this.gene; } @Override boolean accept(final VariantContext ctx) { return gene.getTranscripts().stream().anyMatch(T->testTranscript(T, ctx)); } @Override String getId() { return gene.getId(); } @Override void printManifest(final PrintWriter pw) { super.printManifest(pw); pw.print("\t"); pw.print(this.gene.getTranscripts().stream().map(T->T.getId()).collect(Collectors.joining(";"))); } } public VcfGtfSplitter() { } private boolean testTranscript(final Transcript transcript,final VariantContext ctx) { if(!transcript.overlaps(ctx)) { if(this.use_upstream) { final SimplePosition pos = new SimplePosition( transcript.getContig(), transcript.isPositiveStrand()?transcript.getStart():transcript.getEnd()); if(ctx.withinDistanceOf(pos, this.xxxxstream_length)) return true; } if(this.use_downstream) { final SimplePosition pos = new SimplePosition( transcript.getContig(), transcript.isPositiveStrand()?transcript.getEnd():transcript.getStart()); if(ctx.withinDistanceOf(pos, this.xxxxstream_length)) return true; } return false; } if(this.use_exon && transcript.hasExon() && transcript.getExons().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; if(this.use_intron && transcript.hasIntron() && transcript.getIntrons().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; if(this.use_cds && transcript.hasCDS() && transcript.getAllCds().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; if(this.use_utr5) { if(transcript.isPositiveStrand() && transcript.getUTR5().isPresent() && transcript.getUTR5().get().overlaps(ctx)) return true; if(transcript.isNegativeStrand() && transcript.getUTR3().isPresent() && transcript.getUTR3().get().overlaps(ctx)) return true; } if(this.use_utr3) { if(transcript.isPositiveStrand() && transcript.getUTR3().isPresent() && transcript.getUTR3().get().overlaps(ctx)) return true; if(transcript.isNegativeStrand() && transcript.getUTR5().isPresent() && transcript.getUTR5().get().overlaps(ctx)) return true; } if(this.use_cds_utr5) { if(transcript.isPositiveStrand() && transcript.getUTR5().isPresent() && transcript.getUTR5().get().getIntervals().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; if(transcript.isNegativeStrand() && transcript.getUTR3().isPresent() && transcript.getUTR3().get().getIntervals().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; } if(this.use_cds_utr3) { if(transcript.isPositiveStrand() && transcript.getUTR3().isPresent() && transcript.getUTR3().get().getIntervals().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; if(transcript.isNegativeStrand() && transcript.getUTR5().isPresent() && transcript.getUTR5().get().getIntervals().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; } if(this.use_stop && transcript.hasCodonStopDefined() && transcript.getCodonStop().get().getBlocks().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; if(this.use_start && transcript.hasCodonStartDefined() && transcript.getCodonStart().get().getBlocks().stream().anyMatch(FEAT->FEAT.overlaps(ctx))) return true; if(this.use_splice && transcript.hasIntron()) { for(final Intron intron:transcript.getIntrons()) { final SimpleInterval splice1 = new SimpleInterval(intron.getContig(),intron.getStart()-1,intron.getStart()); if(ctx.withinDistanceOf(splice1, this.split_length)) return true; final SimpleInterval splice2 = new SimpleInterval(intron.getContig(),intron.getEnd(),intron.getEnd()+1); if(ctx.withinDistanceOf(splice2, this.split_length)) return true; } } return false; } private void split( final AbstractSplitter splitter, final VCFFileReader vcfFileReader, final VCFHeader header, final SAMSequenceDictionary dict, final ArchiveFactory archiveFactory, final Path tmpVcf, final PrintWriter manifest ) throws IOException { final Locatable interval = splitter.getInterval(); final CloseableIterator<VariantContext> iter; if((this.use_downstream || this.use_upstream) && this.xxxxstream_length>0) { iter = vcfFileReader.query(new SimpleInterval(interval).extend(this.xxxxstream_length)); } else { iter = vcfFileReader.query(interval); } if(!this.enable_empty_vcf && !iter.hasNext()) { iter.close(); return; } final VariantContextWriterBuilder vcwb=new VariantContextWriterBuilder(); vcwb.setCreateMD5(false); vcwb.setReferenceDictionary(null); final TabixIndexCreator tabixIndexCreator; final Path tbiPath; if(this.index_vcf) { if(dict==null) { tabixIndexCreator = new TabixIndexCreator(TabixFormat.VCF); } else { tabixIndexCreator = new TabixIndexCreator(dict, TabixFormat.VCF); } vcwb.setIndexCreator(tabixIndexCreator); vcwb.setOption(Options.INDEX_ON_THE_FLY); tbiPath =tmpVcf.getParent().resolve(tmpVcf.getFileName().toString()+FileExtensions.TABIX_INDEX); } else { tabixIndexCreator = null; tbiPath = null; } vcwb.setOutputPath(tmpVcf); final VariantContextWriter out = vcwb.build(); final VCFHeader header2=new VCFHeader(this.attCleaner.cleanHeader(header)); super.addMetaData(header2); splitter.addMetadata(header2); out.writeHeader(header2); int count_ctx = 0; while(iter.hasNext()) { final VariantContext ctx = iter.next(); if(this.ignoreFiltered && ctx.isFiltered()) continue; if(!splitter.accept(ctx)) continue; count_ctx++; out.add(this.attCleaner.apply(ctx)); } iter.close(); out.close(); if(!this.enable_empty_vcf && count_ctx==0) { Files.delete(tmpVcf); if(tbiPath!=null) Files.delete(tbiPath); return ; } final String md5 = StringUtils.md5(interval.getContig()+":"+splitter.getId()); final String filename = md5.substring(0,2) + File.separatorChar + md5.substring(2) + File.separator+splitter.getId().replaceAll("[/\\:]", "_") + (this.use_bcf?FileExtensions.BCF:FileExtensions.COMPRESSED_VCF); OutputStream os = archiveFactory.openOuputStream(filename); IOUtils.copyTo(tmpVcf, os); os.flush(); os.close(); if(tbiPath!=null) { os = archiveFactory.openOuputStream(filename+FileExtensions.TABIX_INDEX); IOUtils.copyTo(tmpVcf, os); os.flush(); os.close(); Files.delete(tbiPath); } Files.delete(tmpVcf); manifest.print(interval.getContig()); manifest.print('\t'); manifest.print(interval.getStart()-1); manifest.print('\t'); manifest.print(interval.getEnd()); manifest.print('\t'); splitter.printManifest(manifest); manifest.print('\t'); manifest.print((archiveFactory.isZip()?"":this.outputFile.toString()+File.separator)+filename); manifest.print('\t'); manifest.println(count_ctx); } @Override public int doWork(final List<String> args) { ArchiveFactory archiveFactory = null; PrintWriter manifest = null; VCFFileReader vcfFileReader = null; try { this.attCleaner = AttributeCleaner.compile(this.xannotatePattern); for(final String s: featuresString.split("[;, ]")) { if(StringUtils.isBlank(s)) continue; if(s.equals("cds")) { use_cds = true; } else if(s.equals("intron")) { use_cds = true; } else if(s.equals("exon")) { use_exon = true; } else if(s.equals("stop")) { use_stop = true; } else if(s.equals("start")) { use_start = true; } else if(s.equals("transcript")) { use_exon = true; use_intron = true; } else if(s.equals("utr5")) { use_utr5= true;} else if(s.equals("utr3")) { use_utr3= true;} else if(s.equals("utr")) { use_utr3= true;use_utr5= true;} else if(s.equals("upstream")) {use_upstream=true;} else if(s.equals("downstream")) {use_downstream=true;} else if(s.equals("splice")) {use_splice=true;} else if(s.equals("cds_utr5")) {use_cds_utr5=true;} else if(s.equals("cds_utr3")) {use_cds_utr3=true;} else if(s.equals("cds_utr")) {use_cds_utr3=true;use_cds_utr5=true;} else { LOG.error("unknown code "+s+" in "+this.featuresString); return -1; } } final Path tmpVcf = Files.createTempFile("tmp.",(use_bcf?FileExtensions.BCF:FileExtensions.COMPRESSED_VCF)); String input = oneAndOnlyOneFile(args); vcfFileReader = new VCFFileReader(Paths.get(input),true); final VCFHeader header1 = vcfFileReader.getFileHeader(); final SAMSequenceDictionary dict = header1.getSequenceDictionary(); if(dict==null && this.use_bcf) { throw new JvarkitException.VcfDictionaryMissing(input); } if(dict!=null && !limitToContigs.isEmpty()) { final ContigNameConverter ctgNameConverter = ContigNameConverter.fromOneDictionary(dict); final Set<String> set2 = new HashSet<>(this.limitToContigs.size()); for(final String ctg:this.limitToContigs) { final String ctg2 = ctgNameConverter.apply(ctg); if(StringUtils.isBlank(ctg2)) { LOG.error(JvarkitException.ContigNotFoundInDictionary.getMessage(ctg, dict)); return -1; } set2.add(ctg2); } this.limitToContigs = set2; } final List<Gene> all_genes; try(GtfReader gtfReader=new GtfReader(this.gtfPath)) { final Comparator<Gene> cmp; if(dict!=null) { gtfReader.setContigNameConverter(ContigNameConverter.fromOneDictionary(dict)); cmp = new ContigDictComparator(dict).createLocatableComparator(); } else { cmp = (A,B)->{ final int i= A.getContig().compareTo(B.getContig()); if(i!=0) return i; return Integer.compare(A.getStart(), B.getStart()); }; } all_genes = gtfReader. getAllGenes(). stream(). filter(G->{ if(this.protein_coding_only && !"protein_coding".equals(G.getGeneBiotype())) return false; if(this.limitToContigs.isEmpty()) return true; return this.limitToContigs.contains(G.getContig()); }). sorted(cmp). collect(Collectors.toList()); } archiveFactory = ArchiveFactory.open(this.outputFile); archiveFactory.setCompressionLevel(0); manifest = new PrintWriter(this.manifestFile==null?new NullOuputStream():IOUtils.openPathForWriting(manifestFile)); manifest.println("#chrom\tstart\tend\tGene-Id\tGene-Name\tGene-Biotype\tTranscript-Id\tpath\tCount_Variants"); if(this.split_by_transcript) { final Iterator<Transcript> triter = all_genes. stream(). flatMap(G->G.getTranscripts().stream()).iterator(); while(triter.hasNext()) { final Transcript tr=triter.next(); final AbstractSplitter splitter = new TranscriptSplitter(tr); this.split(splitter,vcfFileReader,header1,dict,archiveFactory,tmpVcf,manifest); } } else { for(Gene gene: all_genes) { final AbstractSplitter splitter = new GeneSplitter(gene); this.split(splitter,vcfFileReader,header1,dict,archiveFactory,tmpVcf,manifest); } } vcfFileReader.close(); vcfFileReader = null; manifest.flush(); manifest.close(); manifest = null; archiveFactory.close(); Files.deleteIfExists(tmpVcf); return RETURN_OK; } catch(final Exception err) { LOG.error(err); return -1; } finally { CloserUtil.close(vcfFileReader); CloserUtil.close(archiveFactory); CloserUtil.close(manifest); } } public static void main(final String[] args) { new VcfGtfSplitter().instanceMainWithExit(args); } }
39.37691
212
0.7244
0aad175c87a03ee6641b4454b488002a903edb99
1,510
package org.jboss.resteasy.test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.jboss.resteasy.plugins.server.netty.NettyUtil; import org.junit.Assert; @Path("async-io") public class AsyncIOResource { @GET @Path("blocking-writer-on-io-thread") public BlockingWriterData blockingWriterOnIoThread() { Assert.assertTrue(NettyUtil.isIoThread()); return new BlockingWriterData(); } @GET @Path("async-writer-on-io-thread") public AsyncWriterData asyncWriterOnIoThread() { return new AsyncWriterData(true, false); } @GET @Path("slow-async-writer-on-io-thread") public AsyncWriterData slowAsyncWriterOnIoThread() { return new AsyncWriterData(true, true); } @GET @Path("blocking-writer-on-worker-thread") public CompletionStage<BlockingWriterData> blockingWriterOnWorkerThread() { return CompletableFuture.supplyAsync(() -> new BlockingWriterData()); } @GET @Path("async-writer-on-worker-thread") public CompletionStage<AsyncWriterData> asyncWriterOnWorkerThread() { return CompletableFuture.supplyAsync(() -> new AsyncWriterData(false, true)); } @GET @Path("slow-async-writer-on-worker-thread") public CompletionStage<AsyncWriterData> slowAsyncWriterOnWorkerThread() { return CompletableFuture.supplyAsync(() -> new AsyncWriterData(false, true)); } }
29.038462
85
0.713245
45e4b1bfa2dca4762b301fec8f3b0b62e53d2f0b
21,855
/** * */ package com.zuoxiaolong.deerlet.redis.client; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.zuoxiaolong.deerlet.redis.client.command.BitopOperations; import com.zuoxiaolong.deerlet.redis.client.command.BooleanResultCommand; import com.zuoxiaolong.deerlet.redis.client.command.Commands; import com.zuoxiaolong.deerlet.redis.client.command.Cursor; import com.zuoxiaolong.deerlet.redis.client.command.CursorResultCommand; import com.zuoxiaolong.deerlet.redis.client.command.DefaultCursor; import com.zuoxiaolong.deerlet.redis.client.command.IntResultCommand; import com.zuoxiaolong.deerlet.redis.client.command.LInsertOptions; import com.zuoxiaolong.deerlet.redis.client.command.ListResultCommand; import com.zuoxiaolong.deerlet.redis.client.connection.ConnectionPool; import com.zuoxiaolong.deerlet.redis.client.strategy.LoadBalanceStrategy; /** * @author zuoxiaolong * */ public class SimpleNodeDeerletRedisClient extends AbstractDeerletRedisClient { public SimpleNodeDeerletRedisClient(LoadBalanceStrategy<ConnectionPool> strategy) { super(strategy); } @Override public int del(String... keys) { return executeCommand(null, IntResultCommand.class, Commands.del, Arrays.asList(keys).toArray()); } @Override public List<String> keys(String pattern) { return executeCommand(null, ListResultCommand.class, Commands.keys, pattern); } @Override public boolean rename(String key, String newKey) { return executeCommand(null, BooleanResultCommand.class, Commands.rename, key, newKey); } @Override public boolean renamenx(String key, String newKey) { return executeCommand(null, BooleanResultCommand.class, Commands.renamenx, key, newKey); } @Override public Cursor scan(Cursor cursor, String pattern, Integer count) { List<Object> arguments = new ArrayList<Object>(); if (cursor == null || cursor == DefaultCursor.EMPTY_CURSOR || cursor.getCursorList() == null || cursor.getCursorList().size() == 0) { arguments.add(0); } else { arguments.add(cursor.getCursorList().get(0)); } if (pattern != null) { arguments.add("match"); arguments.add(pattern); } if (count != null) { arguments.add("count"); arguments.add(count); } return executeCommand(null, CursorResultCommand.class, Commands.scan, arguments.toArray()); } @Override public int bitop(BitopOperations operation, String destKey, String... keys) { return executeCommand(destKey, IntResultCommand.class, Commands.bitop, operation, destKey, keys); } @Override public List<String> mget(String... keys) { return executeCommand(null, ListResultCommand.class, Commands.mget, Arrays.asList(keys).toArray()); } @Override public boolean mset(String[] keys, Object... values) { if (keys.length != values.length) { throw new IllegalArgumentException("keys.length != values.length!"); } Object[] arguments = new Object[keys.length + values.length]; for (int i = 0 ,index = 0; i < keys.length; i++) { arguments[index++] = keys[i]; arguments[index++] = values[i]; } return executeCommand(null, BooleanResultCommand.class, Commands.mset, arguments); } @Override public boolean msetnx(String[] keys, Object... values) { if (keys.length != values.length) { throw new IllegalArgumentException("keys.length != values.length!"); } Object[] arguments = new Object[keys.length + values.length]; for (int i = 0 ,index = 0; i < keys.length; i++) { arguments[index++] = keys[i]; arguments[index++] = values[i]; } return executeCommand(null, BooleanResultCommand.class, Commands.msetnx, arguments); } @Override public void hdel() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hexists() */ @Override public void hexists() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hget() */ @Override public void hget() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hgetall() */ @Override public void hgetall() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hincrby() */ @Override public void hincrby() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hincrbyfloat() */ @Override public void hincrbyfloat() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hkeys() */ @Override public void hkeys() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hlen() */ @Override public void hlen() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hmget() */ @Override public void hmget() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hmset() */ @Override public void hmset() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hset() */ @Override public void hset() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hsetnx() */ @Override public void hsetnx() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hvals() */ @Override public void hvals() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#hscan() */ @Override public void hscan() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#blpop() */ @Override public void blpop() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#brpop() */ @Override public void brpop() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#brpoplpush() */ @Override public void brpoplpush() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see * DeerletRedisClient#lset(java.lang.String, * int, java.lang.Object) */ @Override public boolean lset(String listKey, int index, Object value) { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see * DeerletRedisClient#lpush(java.lang.String, * java.lang.Object[]) */ @Override public int lpush(String listKey, Object... values) { // TODO Auto-generated method stub return 0; } /* * (non-Javadoc) * * @see * DeerletRedisClient#lrange(java.lang.String, * int, int) */ @Override public List<String> lrange(String listKey, int start, int stop) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see * DeerletRedisClient#llen(java.lang.String) */ @Override public int llen(String listKey) { // TODO Auto-generated method stub return 0; } /* * (non-Javadoc) * * @see * DeerletRedisClient#lpushx(java.lang.String, * java.lang.Object) */ @Override public int lpushx(String listKey, Object value) { // TODO Auto-generated method stub return 0; } /* * (non-Javadoc) * * @see * DeerletRedisClient#lpop(java.lang.String) */ @Override public String lpop(String listKey) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see * DeerletRedisClient#lrem(java.lang.String, * int, java.lang.Object) */ @Override public int lrem(String listKey, int count, Object value) { // TODO Auto-generated method stub return 0; } /* * (non-Javadoc) * * @see * DeerletRedisClient#lindex(java.lang.String, * int) */ @Override public String lindex(String listKey, int index) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see * DeerletRedisClient#linsert(java.lang.String, * LInsertOptions, java.lang.Object, * java.lang.Object) */ @Override public int linsert(String listKey, LInsertOptions option, Object pivot, Object value) { // TODO Auto-generated method stub return 0; } /* * (non-Javadoc) * * @see * DeerletRedisClient#ltrim(java.lang.String, * int, int) */ @Override public boolean ltrim(String listKey, int start, int stop) { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see DeerletRedisClient#rpop() */ @Override public void rpop() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#rpoplpush() */ @Override public void rpoplpush() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#rpush() */ @Override public void rpush() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#rpushx() */ @Override public void rpushx() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sadd() */ @Override public void sadd() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#scard() */ @Override public void scard() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sdiff() */ @Override public void sdiff() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sdiffstore() */ @Override public void sdiffstore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sinter() */ @Override public void sinter() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sinterstore() */ @Override public void sinterstore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sismember() */ @Override public void sismember() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#smembers() */ @Override public void smembers() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#smove() */ @Override public void smove() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#spop() */ @Override public void spop() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#srandmember() */ @Override public void srandmember() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#srem() */ @Override public void srem() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sunion() */ @Override public void sunion() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sunionstore() */ @Override public void sunionstore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sscan() */ @Override public void sscan() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zadd() */ @Override public void zadd() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zcard() */ @Override public void zcard() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zcount() */ @Override public void zcount() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zincrby() */ @Override public void zincrby() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrange() */ @Override public void zrange() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrangebyscore() */ @Override public void zrangebyscore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrank() */ @Override public void zrank() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrem() */ @Override public void zrem() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zremrangebyrank() */ @Override public void zremrangebyrank() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zremrangebyscore() */ @Override public void zremrangebyscore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrevrange() */ @Override public void zrevrange() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrevrangebyscore() */ @Override public void zrevrangebyscore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrevrank() */ @Override public void zrevrank() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zscore() */ @Override public void zscore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zunionstore() */ @Override public void zunionstore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zinterstore() */ @Override public void zinterstore() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zscan() */ @Override public void zscan() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zrangebylex() */ @Override public void zrangebylex() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zlexcount() */ @Override public void zlexcount() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#zremrangebylex() */ @Override public void zremrangebylex() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#pfadd() */ @Override public void pfadd() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#pfcount() */ @Override public void pfcount() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#pfmerge() */ @Override public void pfmerge() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#psubscribe() */ @Override public void psubscribe() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#publish() */ @Override public void publish() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#pubsub() */ @Override public void pubsub() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#punsubscribe() */ @Override public void punsubscribe() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#subscribe() */ @Override public void subscribe() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#unsubscribe() */ @Override public void unsubscribe() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#discard() */ @Override public void discard() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#exec() */ @Override public void exec() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#multi() */ @Override public void multi() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#unwatch() */ @Override public void unwatch() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#watch() */ @Override public void watch() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#eval() */ @Override public void eval() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#evalsha() */ @Override public void evalsha() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#scriptexists() */ @Override public void scriptexists() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#scriptflush() */ @Override public void scriptflush() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#scriptkill() */ @Override public void scriptkill() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#scriptload() */ @Override public void scriptload() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#auth() */ @Override public void auth() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#echo() */ @Override public void echo() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#ping() */ @Override public void ping() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#quit() */ @Override public void quit() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#select(int) */ @Override public boolean select(int index) { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see DeerletRedisClient#bgrewriteaof() */ @Override public boolean bgrewriteaof() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see DeerletRedisClient#bgsave() */ @Override public boolean bgsave() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see DeerletRedisClient#clientgetname() */ @Override public void clientgetname() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#clientkill() */ @Override public void clientkill() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#clientlist() */ @Override public void clientlist() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#clientsetname() */ @Override public void clientsetname() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#configget() */ @Override public void configget() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#config() */ @Override public void config() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#resetstat() */ @Override public void resetstat() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#configrewrite() */ @Override public void configrewrite() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#configset() */ @Override public void configset() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#dbsize() */ @Override public int dbsize() { // TODO Auto-generated method stub return 0; } /* * (non-Javadoc) * * @see DeerletRedisClient#debugobject() */ @Override public void debugobject() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#debugsegfault() */ @Override public void debugsegfault() { // TODO Auto-generated method stub } @Override public boolean flushall() { return executeCommand(null, BooleanResultCommand.class, Commands.flushall); } /* * (non-Javadoc) * * @see DeerletRedisClient#flushdb() */ @Override public boolean flushdb() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see DeerletRedisClient#info() */ @Override public void info() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#lastsave() */ @Override public void lastsave() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#monitor() */ @Override public void monitor() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#psync() */ @Override public void psync() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#save() */ @Override public void save() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#shutdown() */ @Override public void shutdown() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#slaveof() */ @Override public void slaveof() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#showlog() */ @Override public void showlog() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#sync() */ @Override public void sync() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see DeerletRedisClient#time() */ @Override public void time() { // TODO Auto-generated method stub } }
15.577334
135
0.638527
de8425f65394ca61afb5645ff9654a7703824450
770
package com.ysyx.commons.wx.requests.wxmsg; import com.ysyx.commons.wx.TextHttpRequest; import com.ysyx.commons.wx.WXCommonResult; import com.ysyx.commons.wx.annotations.Post; import com.ysyx.commons.wx.annotations.QueryString; import org.codehaus.jackson.annotate.JsonProperty; /** * get send status request. * * @author duanbn * */ @Post("/cgi-bin/message/mass/get") public class GetSendStatusRequest extends TextHttpRequest<WXCommonResult> { @QueryString("access_token") private final String accessToken; @JsonProperty("msg_id") private final String msgId; /** * * @param accessToken * @param msgId */ public GetSendStatusRequest(final String accessToken, final String msgId) { this.accessToken = accessToken; this.msgId = msgId; } }
22
76
0.753247
b2a7d819104a7a1baaea2b95b99c3ba2d9a152ad
1,935
package org.firstinspires.ftc.teamcode.code201920; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.firstinspires.ftc.teamcode.LcVuforiaOpMode; import org.firstinspires.ftc.teamcode.hardware.HardwareLilPanini; import org.firstinspires.ftc.teamcode.hardware.Robot; @Disabled @Autonomous(name = "SomethingRandom", group = "autonomous") public class SomethingRandom extends LcVuforiaOpMode { @Override public void runTasks() { robot.init(hardwareMap); waitForStart(); start(); robot.drive(.93, 10, 3); robot.turn(5, 2, 9); //Code if robot starts in the middle robot.drive(0.7, 44, 50); robot.turn(.6, -90, 50); robot.drive(0.4, 11, 50); robot.strafe(HardwareLilPanini.HorizontalDirection.LEFT, .5, 6, 50); robot.turn(.5, -90, 50); robot.drive(1, 14, 50); robot.turn(1, -15, 50); //ONE robot.drive(1, 14, 50); robot.turn(1, -15, 50); //TWO robot.drive(1, 14, 50); robot.turn(1, -15, 50); //THREE robot.drive(1, 14, 50); robot.turn(1, -15, 50); //FOUR robot.drive(1, 14, 50); robot.turn(1, -15, 50); //FIVE robot.drive(1, 10, 50); robot.turn(1, -15, 50); //SIX robot.drive(1, 44, 50); for (int i = 0; i < 5; i++) { if (isVisible(stoneTarget)) { robot.stop(); robot.grab(1); break; } else { robot.strafe(HardwareLilPanini.HorizontalDirection.LEFT, .5, 6, 50); } } robot.drive(.7,-25 , 50); robot.turn(.7, 90, 50); robot.drive(.7, 75, 50); robot.stop(); robot.release(1); } }
24.807692
84
0.555556
c96e934ae2d54412de2150dad8673c8ded9298ac
1,023
/* * Copyright 2018 Patrik Karlström. * * 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.nbgames.core.dice.data.sound; import java.applet.Applet; import java.applet.AudioClip; import se.trixon.almond.util.SystemHelper; /** * * @author Patrik Karlström */ public class DiceSound { public static AudioClip getAudioClip(String soundPath) { return Applet.newAudioClip(DiceSound.class.getClassLoader().getResource(SystemHelper.getPackageAsPath(DiceSound.class) + soundPath)); } }
31.96875
141
0.746823
4900349251bd64abc40c5c9dbe9a8f787b0d58a7
7,343
package com.eaybars.webstart.service.artifact.control; import com.eaybars.webstart.service.artifact.entity.Artifact; import com.eaybars.webstart.service.artifact.entity.ArtifactEvent; import org.infinispan.manager.CacheContainer; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Event; import javax.inject.Inject; import java.net.URI; import java.util.Comparator; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; @ApplicationScoped public class Artifacts { private static final Logger LOGGER = Logger.getLogger(Artifacts.class.getName()); @Resource(lookup = "java:jboss/infinispan/container/artifacts") CacheContainer cacheContainer; Map<URI, Artifact> cache; @Inject Event<Artifact> artifactEvent; @PostConstruct private void init() { cacheContainer.getCache().addListener(new CacheListener()); cache = cacheContainer.getCache(); } private Map<URI, Artifact> getCache() { return cache; } /** * Returns the artifact for the identifier * @param identifier * @return */ public Artifact get(URI identifier) { return getCache().get(identifier); } /** * Streams all active artifacts * @return stream of active artifacts */ public Stream<Artifact> stream() { return getCache().values().stream(); } /** * Adds the given artifact to the active artifacts and removes and returns the old artifact associated with the same * identifier if there exist one * @param artifact new artifact to store * @return old artifact associate with the same identifier with the given artifact or null if no such artifact exists */ public Artifact put(Artifact artifact) { return getCache().put(artifact.getIdentifier(), artifact); } /** * Adds the given artifact to the active artifacts if there is no artifact already associated with the same identifier * @param artifact artifact to add * @return existing artifact associated with the same identifier or null if no such artifact exists */ public Artifact putIfAbsent(Artifact artifact) { return getCache().putIfAbsent(artifact.getIdentifier(), artifact); } /** * Removes the given artifact from the active artifacts * @param artifact to remove * @return true if the given artifact is among the active artifacts, false otherwise */ public boolean remove(Artifact artifact) { return getCache().remove(artifact.getIdentifier()) != null; } /** * Removes the artifact associated with the given identifier from the active artifacts and returns it. If no such * artifact exists, null is returned * @param identifier identifier of the artifact to be removed * @return removed artifact associated with the given identifier or null if no such artifact exists */ public Artifact remove(URI identifier) { return getCache().remove(identifier); } /** * Clears active artifacts */ public void removeAll() { getCache().clear(); } public Hierarchy hierarchy() { return new Hierarchy(stream()); } public Hierarchy hierarchy(Predicate<? super Artifact> filter) { return new Hierarchy(stream().filter(filter)); } // public Collection<Artifact> children(Backends.BackendURI target) { // SearchManager searchManager = Search.getSearchManager((Cache<?, ?>) getCache(target.getBackend().getName())); // QueryBuilder queryBuilder = searchManager.buildQueryBuilderForClass(AbstractArtifact.class).get(); // Query query = queryBuilder.phrase() // .onField("identifier") // .sentence(target.getUri().toString()) // .createQuery(); // CacheQuery cacheQuery = searchManager.getQuery(query); // return (List) cacheQuery.list(); // } public static class Hierarchy { private Stream<Artifact> artifacts; private Hierarchy(Stream<Artifact> artifacts) { this.artifacts = artifacts; } public Stream<Artifact> top() { AtomicReference<Artifact> currentTop = new AtomicReference<>(); return artifacts.sequential() .sorted(Comparator.naturalOrder()) .map(c -> currentTop.accumulateAndGet(c, (oldC, newC) -> oldC == null ? newC : (newC.getIdentifier().toString().startsWith(oldC.getIdentifier().toString()) ? oldC : newC))) .distinct(); } public Optional<Artifact> parent(URI identifier) { return parents(identifier) .filter(c -> !identifier.equals(c.getIdentifier())) .findFirst(); } public Stream<Artifact> parents(URI identifier) { return artifacts .filter(c -> identifier.toString().startsWith(c.getIdentifier().toString())) .sorted(Comparator.reverseOrder()); } public Stream<Artifact> children(URI identifier) { return new Hierarchy(artifacts .filter(a -> a.getIdentifier().toString().startsWith(identifier.toString())) .filter(a -> !identifier.equals(a.getIdentifier())) ).top(); } public Stream<Artifact> descendants(URI identifier) { return artifacts.filter(a -> a.getIdentifier().toString().startsWith(identifier.toString())); } } @Listener(observation = Listener.Observation.POST) public class CacheListener { @CacheEntryCreated public void added(CacheEntryCreatedEvent<URI, Artifact> event) { artifactEvent.select(ArtifactEvent.Literal.LOADED) .fire(event.getValue()); LOGGER.log(Level.INFO, "Loaded artifact " + event.getValue()); } @CacheEntryModified public void modified(CacheEntryModifiedEvent<URI, Artifact> event) { artifactEvent.select(ArtifactEvent.Literal.UPDATED) .fire(event.getValue()); LOGGER.log(Level.INFO, "Updated artifact " + event.getValue()); } @CacheEntryRemoved public void removed(CacheEntryRemovedEvent<URI, Artifact> event) { artifactEvent.select(ArtifactEvent.Literal.UNLOADED) .fire(event.getOldValue()); LOGGER.log(Level.INFO, "Unloaded artifact " + event.getOldValue()); } } }
37.274112
122
0.667302
f1cab56bf8bfcd440c53acb301c18dfeb610515a
982
//,temp,sample_3958.java,2,11,temp,sample_827.java,2,17 //,3 public class xxx { public void dummy_method(){ String pvcName = exchange.getIn().getHeader( KubernetesConstants.KUBERNETES_PERSISTENT_VOLUME_CLAIM_NAME, String.class); String namespaceName = exchange.getIn().getHeader( KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class); PersistentVolumeClaimSpec pvcSpec = exchange.getIn().getHeader( KubernetesConstants.KUBERNETES_PERSISTENT_VOLUME_CLAIM_SPEC, PersistentVolumeClaimSpec.class); if (ObjectHelper.isEmpty(pvcName)) { throw new IllegalArgumentException( "Create a specific Persistent Volume Claim require specify a Persistent Volume Claim name"); } if (ObjectHelper.isEmpty(namespaceName)) { throw new IllegalArgumentException( "Create a specific Persistent Volume Claim require specify a namespace name"); } if (ObjectHelper.isEmpty(pvcSpec)) { log.info("create a specific persistent volume claim require specify a persistent volume claim spec bean"); } } };
46.761905
158
0.817719
be9454e119396fdfe811fa4c8839fddecc15deaf
84
package io.flaterlab.jjson; public interface Callback<T> { void call(T data); }
16.8
30
0.714286
202d2632f43e56138e4f43e3c75829f036a6d828
1,110
package org.fluentlenium.configuration; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.LinkedHashMap; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.Capabilities; public class CapabilitiesJsonParsingTest { private static final String CAPABILITIES = "{\"chromeOptions\": {\"args\": [\"headless\",\"disable-gpu\"]}}"; private static AnnotationConfiguration configuration; @FluentConfiguration(webDriver = "chrome", capabilities = CAPABILITIES) private static class ConfiguredClass { } @BeforeClass public static void beforeClass() { configuration = new AnnotationConfiguration(ConfiguredClass.class); } @Test public void capabilities() { Capabilities capabilities = configuration.getCapabilities(); LinkedHashMap<String, ArrayList<String>> chromeOptions = (LinkedHashMap<String, ArrayList<String>>) capabilities.getCapability("chromeOptions"); assertThat(chromeOptions.get("args")).contains("headless", "disable-gpu"); } }
32.647059
113
0.730631
8e2fbd79ac7f62bd7f0282199c52666fdfc6d795
2,524
package com.good.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.SimpleHttpConnectionManager; import org.apache.commons.httpclient.methods.PostMethod; import com.alibaba.druid.support.json.JSONUtils; /** * 邮件发送公共类. * @author zmyu * */ public class EmailUtils { private static String hexString ="0123456789ABCDEF"; /** * 发送邮件公共类,传入发送邮件URL和邮件内容map * @param url * @param map * emailAddresses 收件人列表,多个用半角逗号分割 * templateId 邮件模板ID * ss 模板中的参数 * attachments 附件列表,多个用半角逗号分割 * bccAddresses 隐藏抄送人列表,多个用半角逗号分割 * ccAddresses 抄送人列表,多个用半角逗号分割 * @return */ public static String sendEmail(String url, Map<String, Object> map){ HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); String jsonMap = JSONUtils.toJSONString(map); String s = encode(jsonMap); post.addParameter(new NameValuePair("parameters", s)); String responseContent = null; InputStream is = null; try { int statusCode = client.executeMethod(post); if (statusCode == HttpStatus.SC_OK){ is = post.getResponseBodyAsStream(); responseContent = post.getResponseBodyAsString(); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { ((SimpleHttpConnectionManager)client.getHttpConnectionManager()).shutdown(); } return responseContent; } private static String encode(String str){ byte[] bytes = str.getBytes(); StringBuilder sb = new StringBuilder(bytes.length*2); for(int i = 0; i < bytes.length; i++){ sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4)); sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0)); } return sb.toString(); } private static String decode(String bytes){ ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length()/2); for(int i = 0; i < bytes.length();i += 2){ baos.write((hexString.indexOf(bytes.charAt(i))<<4|hexString.indexOf(bytes.charAt(i+1)))); } return new String(baos.toByteArray()); } }
30.780488
94
0.660063
decf4d0a9caef8413c08620a84389d734c626f7b
685
/** * */ package str.govern.data; public enum Users { batman(1,"5/1/1939","b4tg1rl","the Caped Crusader", "batman",Status.active), robin(2, "4/1/1940", "b4tg1rl","the Boy Wonder", "robin", Status.active), joker(3, "4/25/1940", "h@rl3y","the Villian", "jerome", Status.locked); public int id; public String dob; public String password; public String lastname; public String username; public Status status; Users(int id, String dob, String password, String lastname, String username, Status status) { this.id = id; this.dob = dob; this.password = password; this.lastname = lastname; this.username = username; this.status = status; } }
27.4
95
0.662774
0532398e65c1ef04fe426314944f0bdc75d51904
5,945
/* * Copyright 2019-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vividus.excel; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentMatchers; import org.mockito.MockedStatic; import org.mockito.MockedStatic.Verification; import org.mockito.Mockito; import org.vividus.util.ResourceUtils; class ExcelSheetsExtractorTests { private static final String TEMPLATE_PATH = "/TestTemplate.xlsx"; private static final int EXPECTED_SHEETS_COUNT = 3; @Test void testGetSheetsFromFile() throws WorkbookParsingException { IExcelSheetsExtractor excelSheetsExtractor = new ExcelSheetsExtractor(TEMPLATE_PATH); assertThat(excelSheetsExtractor.getSheets().size(), Matchers.equalTo(EXPECTED_SHEETS_COUNT)); } @Test void testGetSheetsFromBytes() throws WorkbookParsingException, IOException { File excelFile = ResourceUtils.loadFile(this.getClass(), TEMPLATE_PATH); IExcelSheetsExtractor excelSheetsExtractor = new ExcelSheetsExtractor(Files.readAllBytes(excelFile.toPath())); assertThat(excelSheetsExtractor.getSheets().size(), Matchers.equalTo(EXPECTED_SHEETS_COUNT)); } @Test void testGetSheetAtNumberSuccess() throws WorkbookParsingException { IExcelSheetsExtractor excelSheetsExtractor = new ExcelSheetsExtractor(TEMPLATE_PATH); Optional<Sheet> sheetOpt = excelSheetsExtractor.getSheet(0); assertTrue(sheetOpt.isPresent()); assertThat("Mapping", Matchers.equalTo(sheetOpt.get().getSheetName())); } @ParameterizedTest @ValueSource(ints = {0, 1}) void testGetSheetAtNumberOutOfRange(int number) throws WorkbookParsingException { IExcelSheetsExtractor excelSheetsExtractor = new ExcelSheetsExtractor(TEMPLATE_PATH); Optional<Sheet> sheetOpt = excelSheetsExtractor.getSheet(EXPECTED_SHEETS_COUNT + number); assertFalse(sheetOpt.isPresent()); } @Test void testGetSheetByNameSuccess() throws WorkbookParsingException { IExcelSheetsExtractor excelSheetsExtractor = new ExcelSheetsExtractor(TEMPLATE_PATH); Optional<Sheet> sheetOpt = excelSheetsExtractor.getSheet("AsString"); assertTrue(sheetOpt.isPresent()); } @Test void testGetSheetByNameNotExisted() throws WorkbookParsingException { IExcelSheetsExtractor excelSheetsExtractor = new ExcelSheetsExtractor(TEMPLATE_PATH); Optional<Sheet> sheetOpt = excelSheetsExtractor.getSheet("Taxonomies"); assertFalse(sheetOpt.isPresent()); } @Test void testGetSheetsWithNames() throws WorkbookParsingException { IExcelSheetsExtractor excelSheetsExtractor = new ExcelSheetsExtractor(TEMPLATE_PATH); Map<String, Sheet> actualMap = excelSheetsExtractor.getSheetsWithNames(); actualMap.forEach((key, value) -> assertThat(key, Matchers.equalTo(value.getSheetName()))); } static Stream<Class<? extends Throwable>> exceptionDataProvider() { return Stream.of(EncryptedDocumentException.class, IOException.class); } @ParameterizedTest @MethodSource("exceptionDataProvider") void testCreateFromFileException(Class<? extends Throwable> exceptionClazz) { assertWorkbookParsingException(() -> WorkbookFactory.create(ArgumentMatchers.any(File.class)), exceptionClazz, () -> new ExcelSheetsExtractor(TEMPLATE_PATH)); } @ParameterizedTest @MethodSource("exceptionDataProvider") void testCreateFromBytesException(Class<? extends Throwable> exceptionClazz) { assertWorkbookParsingException(() -> WorkbookFactory.create(ArgumentMatchers.any(ByteArrayInputStream.class)), exceptionClazz, () -> new ExcelSheetsExtractor(new byte[0])); } private void assertWorkbookParsingException(Verification staticMethodMock, Class<? extends Throwable> exceptionClazz, Executable executable) { try (MockedStatic<WorkbookFactory> workbookFactory = Mockito.mockStatic(WorkbookFactory.class)) { workbookFactory.when(staticMethodMock).thenThrow(exceptionClazz); WorkbookParsingException workbookParsingException = assertThrows(WorkbookParsingException.class, executable); assertEquals("Unable to parse workbook", workbookParsingException.getMessage()); assertThat(workbookParsingException.getCause(), instanceOf(exceptionClazz)); } } }
40.719178
118
0.754247
bbb524f51c1a28952ce9574bc22de28606699ff8
1,710
/* * Copyright 2009 Denys Pavlov, Igor Azarnyi * * 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.yes.cart.service.order.impl.listener; import org.yes.cart.service.order.OrderEvent; import org.yes.cart.service.order.OrderStateAfterTransitionListener; import org.yes.cart.shoppingcart.DeliveryTimeEstimationVisitor; /** * User: denispavlov * Date: 07/02/2017 * Time: 17:13 */ public class OfflinePaymentDeliveryTimeEstimationListenerImpl implements OrderStateAfterTransitionListener { private final DeliveryTimeEstimationVisitor deliveryTimeEstimationVisitor; public OfflinePaymentDeliveryTimeEstimationListenerImpl(final DeliveryTimeEstimationVisitor deliveryTimeEstimationVisitor) { this.deliveryTimeEstimationVisitor = deliveryTimeEstimationVisitor; } /** {@inheritDoc} */ @Override public boolean onEvent(final OrderEvent orderEvent) { final Boolean handled = (Boolean) orderEvent.getRuntimeParams().get("handled"); if (handled != null && handled) { deliveryTimeEstimationVisitor.visit(orderEvent.getCustomerOrder()); return true; } return false; } }
34.2
128
0.736842
11fb7d4c2fabe7e126b08f8ea43cc07696bcde02
21,887
package com.tama.chat.ui.activities.main; import android.Manifest; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.LocalBroadcastManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import butterknife.Bind; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessaging; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; import com.quickblox.chat.model.QBChatDialog; import com.quickblox.chat.model.QBDialogType; import com.quickblox.messages.QBPushNotifications; import com.quickblox.messages.model.QBEnvironment; import com.quickblox.messages.model.QBNotificationChannel; import com.quickblox.messages.model.QBSubscription; import com.quickblox.q_municate_user_service.QMUserService; import com.quickblox.q_municate_user_service.model.QMUser; import com.tama.chat.R; import com.tama.chat.app.Config; import com.tama.chat.gcm.GSMHelper; import com.tama.chat.ui.activities.base.BaseLoggableActivity; import com.tama.chat.ui.fragments.chats.ContactsListFragment; import com.tama.chat.ui.fragments.chats.DialogsListFragment; import com.tama.chat.ui.fragments.map.MapBlinkFragment; import com.tama.chat.ui.fragments.settings.SettingsFragment; import com.tama.chat.ui.fragments.tamaaccount.MyTamaAccountFragment; import com.tama.chat.utils.MediaUtils; import com.tama.chat.utils.NotificationUtils; import com.tama.chat.utils.helpers.FacebookHelper; import com.tama.chat.utils.helpers.ImportFriendsHelper; import com.tama.chat.utils.image.ImageLoaderUtils; import com.tama.chat.utils.image.ImageUtils; import com.tama.q_municate_core.core.command.Command; import com.tama.q_municate_core.models.AppSession; import com.tama.q_municate_core.models.UserCustomData; import com.tama.q_municate_core.service.QBServiceConsts; import com.tama.q_municate_core.utils.Utils; import com.tama.q_municate_core.utils.helpers.CoreSharedHelper; import com.tama.q_municate_db.managers.DataManager; public class MainActivity extends BaseLoggableActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final String TTT = "myLogs"; private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 00001; private static final int PERMISSION_READ_STATE = 102; private static final int PERMISSION_READ_CONTACTS = 101; private FacebookHelper facebookHelper; // private GSMHelper gsmHelper; private BroadcastReceiver mRegistrationBroadcastReceiver; private ImportFriendsSuccessAction importFriendsSuccessAction; private ImportFriendsFailAction importFriendsFailAction; private GSMHelper gsmHelper; private int currentNavigationItemId = R.id.navigation_chats; private boolean showUserIcon = true; @Bind(R.id.navigation) BottomNavigationView navigation; @Bind(R.id.toolbar_view) LinearLayout toolbarView; @Bind(R.id.toolbar_tama_view) LinearLayout toolbarTamaView; @Bind(R.id.tama_toolbar_logo) ImageView tamaToolbarLogo; @Bind(R.id.tama_toolbar_user_icon) ImageView tamaToolbarUserIcon; @Bind(R.id.tama_toolbar_title) TextView tamaToolbarTitle; @Bind(R.id.tama_toolbar_subtitle) TextView tamaToolbarSubtitle; public static void start(Context context) { Intent intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(intent); } @Override protected int getContentResId() { return R.layout.activity_main; } // @Override // public void onBackPressed() { // if (getSupportFragmentManager().getBackStackEntryCount() == 1) { // finish(); // } else { // super.onBackPressed(); // } // } // @TargetApi(Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); initFields(); setUpActionBarWithUpButton(); addDialogsAction(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE); } else { String refreshedToken = FirebaseInstanceId.getInstance().getToken(); subscribeToPushNotifications(refreshedToken); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_READ_CONTACTS); } else { if (!isChatInitializedAndUserLoggedIn()) { Log.d("MainActivity", "onCreate. !isChatInitializedAndUserLoggedIn()"); loginChat(); } } } if(getIntent().getIntExtra(PAGE, 0)==0){ launchDialogsListFragment(); } else { // setCurrentSettingsFragment(R.id.navigation_settings); navigation.setSelectedItemId(R.id.navigation_settings); } //chka Hayk RegistrationBroadcast(); openPushDialogIfPossible(); } private void openPushDialogIfPossible() { CoreSharedHelper sharedHelper = CoreSharedHelper.getInstance(); if (sharedHelper.needToOpenDialog()) { QBChatDialog chatDialog = DataManager.getInstance().getQBChatDialogDataManager() .getByDialogId(sharedHelper.getPushDialogId()); QMUser user = QMUserService.getInstance().getUserCache() .get((long) sharedHelper.getPushUserId()); if (chatDialog != null) { startDialogActivity(chatDialog, user); } } } private void startDialogActivity(QBChatDialog chatDialog, QMUser user) { if (QBDialogType.PRIVATE.equals(chatDialog.getType())) { startPrivateChatActivity(user, chatDialog); } else { startGroupChatActivity(chatDialog); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PERMISSION_READ_STATE) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { String refreshedToken = FirebaseInstanceId.getInstance().getToken(); subscribeToPushNotifications(refreshedToken); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_READ_CONTACTS); } else { if (!isChatInitializedAndUserLoggedIn()) { Log.d("MainActivity", "onCreate. !isChatInitializedAndUserLoggedIn()"); loginChat(); } } } } else if (requestCode == PERMISSION_READ_CONTACTS) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (!isChatInitializedAndUserLoggedIn()) { Log.d("MainActivity", "onCreate. !isChatInitializedAndUserLoggedIn()"); loginChat(); } } } } //chka private void RegistrationBroadcast() { mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TTT, "mtnuma = " + intent.getAction().equals(Config.REGISTRATION_COMPLETE)); Log.d(TTT, "mtnuma 2 = " + intent.getAction().equals("pushNotification")); // checking for type intent filter if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) { // gcm successfully registered // now subscribe to `global` topic to receive app wide notifications FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL); displayFirebaseRegId(); } else if (intent.getAction().equals("pushNotification")) { // new push notification is received String message = intent.getStringExtra("message"); Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show(); } } }; } private void displayFirebaseRegId() { SharedPreferences pref = getApplicationContext() .getSharedPreferences(Config.SHARED_PREF, 0); String regId = pref.getString("regId", null); } private void initFields() { Log.d(TAG, "initFields()"); title = " " + AppSession.getSession().getUser().getFullName(); navigation.setOnNavigationItemSelectedListener(getNavigationItemSelectedListener()); gsmHelper = new GSMHelper(this); importFriendsSuccessAction = new ImportFriendsSuccessAction(); importFriendsFailAction = new ImportFriendsFailAction(); facebookHelper = new FacebookHelper(MainActivity.this); } private BottomNavigationView.OnNavigationItemSelectedListener getNavigationItemSelectedListener() { return new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { if (currentNavigationItemId == item.getItemId()) { return true; } switch (item.getItemId()) { case R.id.navigation_chats: setCurrentChatsFragment(R.id.navigation_chats); return true; case R.id.navigation_contacts: setCurrentContactsListFragment(R.id.navigation_contacts); return true; // case R.id.navigation_map: // setCurrentMapBlinkFragment(R.id.navigation_map); // return true; case R.id.navigation_account: setCurrentMyTamaAccountFragment(R.id.navigation_account); return true; case R.id.navigation_settings: setCurrentSettingsFragment(R.id.navigation_settings); return true; } return false; } }; } private void setTamaToolbar() { // checkVisibilityTamaUserIcon(tamaToolbarUserIcon); tamaToolbarTitle.setText(getString(R.string.tama_family)); tamaToolbarSubtitle.setText(getString(R.string.my_account)); } private void setCurrentChatsFragment(int itemId) { toolbarView.setVisibility(View.VISIBLE); toolbarTamaView.setVisibility(View.GONE); checkVisibilityUserIcon(); showUserIcon = true; title = " " + AppSession.getSession().getUser().getFullName(); setActionBarTitle(title); setCurrentFragment(DialogsListFragment.newInstance()); currentNavigationItemId = itemId; } private void setCurrentContactsListFragment(int itemId) { toolbarView.setVisibility(View.VISIBLE); toolbarTamaView.setVisibility(View.GONE); setCurrentFragment(ContactsListFragment.newInstance()); currentNavigationItemId = itemId; showUserIcon = false; } private void setCurrentMapBlinkFragment(int itemId) { toolbarView.setVisibility(View.VISIBLE); toolbarTamaView.setVisibility(View.GONE); setCurrentFragment(MapBlinkFragment.newInstance()); currentNavigationItemId = itemId; showUserIcon = false; } private void setCurrentSettingsFragment(int itemId) { toolbarView.setVisibility(View.VISIBLE); toolbarTamaView.setVisibility(View.GONE); setCurrentFragment(SettingsFragment.newInstance()); currentNavigationItemId = itemId; showUserIcon = false; } private void setCurrentMyTamaAccountFragment(int itemId) { toolbarView.setVisibility(View.GONE); toolbarTamaView.setVisibility(View.VISIBLE); setTamaToolbar(); setCurrentFragment(MyTamaAccountFragment.newInstance()); currentNavigationItemId = itemId; showUserIcon = false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); facebookHelper.onActivityResult(requestCode, resultCode, data); if (SettingsFragment.REQUEST_CODE_LOGOUT == requestCode && RESULT_OK == resultCode) { startLandingScreen(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { return false; } @Override protected void onStart() { super.onStart(); // navigation.setSelectedItemId(R.id.navigation_chats); Log.d(TTT, "MainActivity onStart()"); } @Override protected void onRestart() { super.onRestart(); Log.d("MainActivity", "onRestart()"); } @Override protected void onResume() { Log.d(TTT, "Activity onResume"); actualizeCurrentTitle(); super.onResume(); addActions(); //chka Hayk LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.REGISTRATION_COMPLETE)); // register new push message receiver // by doing this, the activity will be notified each time a new message arrives LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(Config.PUSH_NOTIFICATION)); // clear the notification area when the app is opened NotificationUtils.clearNotifications(getApplicationContext()); checkGCMRegistration();//<- } private void actualizeCurrentTitle() { if (AppSession.getSession().getUser().getFullName() != null) { title = " " + AppSession.getSession().getUser().getFullName(); } } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); super.onPause(); removeActions(); } // @Override // protected void onStop() { // super.onStop(); // } @Override protected void onDestroy() { super.onDestroy(); removeDialogsAction(); } @Override protected void checkShowingConnectionError() { if (!isNetworkAvailable()) { setActionBarTitle(getString(R.string.dlg_internet_connection_is_missing)); setActionBarIcon(null); } else { setActionBarTitle(title); if (showUserIcon) { checkVisibilityUserIcon(); } } } @Override protected void performLoginChatSuccessAction(Bundle bundle) { super.performLoginChatSuccessAction(bundle); actualizeCurrentTitle(); } private void addDialogsAction() { addAction(QBServiceConsts.LOAD_CHATS_DIALOGS_SUCCESS_ACTION, new LoadChatsSuccessAction()); } private void removeDialogsAction() { removeAction(QBServiceConsts.LOAD_CHATS_DIALOGS_SUCCESS_ACTION); } private void addActions() { addAction(QBServiceConsts.IMPORT_FRIENDS_SUCCESS_ACTION, importFriendsSuccessAction); addAction(QBServiceConsts.IMPORT_FRIENDS_FAIL_ACTION, importFriendsFailAction); updateBroadcastActionList(); } private void removeActions() { removeAction(QBServiceConsts.IMPORT_FRIENDS_SUCCESS_ACTION); removeAction(QBServiceConsts.IMPORT_FRIENDS_FAIL_ACTION); updateBroadcastActionList(); } private void checkVisibilityUserIcon() { UserCustomData userCustomData = Utils .customDataToObject(AppSession.getSession().getUser().getCustomData()); if (!TextUtils.isEmpty(userCustomData.getAvatarUrl())) { loadLogoActionBar(userCustomData.getAvatarUrl()); } else { setActionBarIcon(MediaUtils.getRoundIconDrawable(this, BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_user))); } } private void loadLogoActionBar(String logoUrl) { ImageLoader.getInstance() .loadImage(logoUrl, ImageLoaderUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedBitmap) { setActionBarIcon( MediaUtils.getRoundIconDrawable(MainActivity.this, loadedBitmap)); } }); } private void checkVisibilityTamaUserIcon(ImageView v) { UserCustomData userCustomData = Utils .customDataToObject(AppSession.getSession().getUser().getCustomData()); if (!TextUtils.isEmpty(userCustomData.getAvatarUrl())) { loadLogoTamaActionBar(userCustomData.getAvatarUrl(), v); } // else { // setTamaCustomActionBarIcon(ImageUtils.getRectIconDrawable( // BitmapFactory.decodeResource(getResources(), R.drawable.placeholder_rect_user),dpToPixel(48), dpToPixel(4)),v); // } } private void loadLogoTamaActionBar(String logoUrl, final ImageView v) { ImageLoader.getInstance().loadImage(logoUrl, ImageLoaderUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedBitmap) { setTamaCustomActionBarIcon( ImageUtils.getRectIconDrawable(loadedBitmap, dpToPixel(48), dpToPixel(4)), v); } }); } private void performImportFriendsSuccessAction() { appSharedHelper.saveUsersImportInitialized(true); hideProgress(); } private void checkGCMRegistration() { if (gsmHelper.checkPlayServices()) { if (!gsmHelper.isDeviceRegisteredWithUser()) { gsmHelper.registerInBackground(); } } else { Log.i(TAG, "No valid Google Play Services APK found."); } } //chka Hayk @SuppressLint("MissingPermission") public void subscribeToPushNotifications(String registrationID) { QBSubscription subscription = new QBSubscription(QBNotificationChannel.GCM); subscription.setEnvironment(QBEnvironment.DEVELOPMENT); // String deviceId; final TelephonyManager mTelephony = (TelephonyManager) this.getSystemService( Context.TELEPHONY_SERVICE); if (mTelephony.getDeviceId() != null) { deviceId = mTelephony.getDeviceId(); //*** use for mobiles } else { deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); //*** use for tablets } subscription.setDeviceUdid(deviceId); // subscription.setRegistrationID(registrationID); // QBPushNotifications.createSubscription(subscription); } private void performImportFriendsFailAction(Bundle bundle) { performImportFriendsSuccessAction(); } private void launchDialogsListFragment() { Log.d(TAG, "launchDialogsListFragment()"); // setCurrentFragment(DialogsListFragment.newInstance(), true); setCurrentChatsFragment(R.id.navigation_chats); } private void startImportFriends() { ImportFriendsHelper importFriendsHelper = new ImportFriendsHelper(MainActivity.this); if (facebookHelper.isSessionOpened()) { importFriendsHelper.startGetFriendsListTask(true); } else { importFriendsHelper.startGetFriendsListTask(false); } hideProgress(); } private class ImportFriendsSuccessAction implements Command { @Override public void execute(Bundle bundle) { performImportFriendsSuccessAction(); } } private class ImportFriendsFailAction implements Command { @Override public void execute(Bundle bundle) { performImportFriendsFailAction(bundle); } } }
37.09661
133
0.66423
020400b24964e0333b3d0dd124931a4e69ab83ec
6,967
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qlangtech.tis.plugin.ds.clickhouse; import com.qlangtech.tis.annotation.Public; import com.qlangtech.tis.extension.TISExtension; import com.qlangtech.tis.plugin.ds.BasicDataSourceFactory; import com.qlangtech.tis.plugin.ds.DBConfig; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.List; /** * @author: 百岁([email protected]) * @create: 2021-06-09 14:38 **/ @Public public class ClickHouseDataSourceFactory extends BasicDataSourceFactory { private static final String JDBC_DRIVER = "ru.yandex.clickhouse.ClickHouseDriver"; private static final Logger logger = LoggerFactory.getLogger(ClickHouseDataSourceFactory.class); public static final String DS_TYPE_CLICK_HOUSE = "ClickHouse"; // @FormField(identity = true, ordinal = 0, type = FormFieldType.INPUTTEXT, validate = {Validator.require, Validator.identity}) // public String name; // // @FormField(ordinal = 1, type = FormFieldType.INPUTTEXT, validate = {Validator.require}) // public String jdbcUrl; // // 必须要有用户名密码,不然datax执行的时候校验会失败 // @FormField(ordinal = 2, type = FormFieldType.INPUTTEXT, validate = {Validator.require}) // public String username; // @FormField(ordinal = 3, type = FormFieldType.PASSWORD, validate = {Validator.require}) // public String password; @Override public String identityValue() { return this.name; } public void refectTableInDB(List<String> tabs, Connection conn) throws SQLException { DatabaseMetaData metaData = conn.getMetaData(); ResultSet tablesResult = metaData.getTables(null, this.dbName, null, new String[]{"TABLE"}); while (tablesResult.next()) { // System.out.println(tablesResult.getString(2) + "," + tablesResult.getString(3)); if (!StringUtils.equals(this.dbName, tablesResult.getString(2))) { continue; } tabs.add(tablesResult.getString(3)); } } public final String getJdbcUrl() { for (String jdbcUrl : this.getJdbcUrls()) { return jdbcUrl; } throw new IllegalStateException("can not find jdbcURL"); } // @Override // public List<String> getTablesInDB() { // // List<String> tables = Lists.newArrayList(); // validateConnection(this.jdbcUrl, (conn) -> { // // DatabaseMetaData metaData = conn.getMetaData(); // // ResultSet tablesResult = metaData.getTables(conn.getCatalog(), null, null, new String[]{"TABLE"}); // // while (tablesResult.next()) { // //System.out.println(tablesResult.getString(2) + "," + tablesResult.getString(3)); // if (!"default".equalsIgnoreCase(tablesResult.getString(2))) { // continue; // } // tables.add(tablesResult.getString(3)); // } // // }); // return tables; // } @Override public Connection getConnection(String jdbcUrl) throws SQLException { try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { throw new SQLException(e); } // return super.getConnection(jdbcUrl, username, password); return DriverManager.getConnection(jdbcUrl, StringUtils.trimToNull(this.userName), StringUtils.trimToNull(password)); } @Override public String buidJdbcUrl(DBConfig db, String ip, String dbName) { //"jdbc:clickhouse://192.168.28.200:8123/tis", String jdbcUrl = "jdbc:clickhouse://" + ip + ":" + this.port + "/" + dbName; // if (StringUtils.isNotEmpty(this.encode)) { // jdbcUrl = jdbcUrl + "&characterEncoding=" + this.encode; // } // if (StringUtils.isNotEmpty(this.extraParams)) { // jdbcUrl = jdbcUrl + "&" + this.extraParams; // } return jdbcUrl; } // @Override // public List<ColumnMetaData> getTableMetadata(String table) { // return parseTableColMeta(table, this.jdbcUrl); // } @TISExtension public static class DefaultDescriptor extends BasicRdbmsDataSourceFactoryDescriptor { @Override protected String getDataSourceName() { return DS_TYPE_CLICK_HOUSE; } @Override public boolean supportFacade() { return false; } // private static Pattern PatternClickHouse = Pattern.compile("jdbc:clickhouse://(.+):\\d+/.*"); // public boolean validateJdbcUrl(IFieldErrorHandler msgHandler, Context context, String fieldName, String value) { // Matcher matcher = PatternClickHouse.matcher(value); // if (!matcher.matches()) { // msgHandler.addFieldError(context, fieldName, "不符合格式规范:" + PatternClickHouse); // return false; // } //// File rootDir = new File(value); //// if (!rootDir.exists()) { //// msgHandler.addFieldError(context, fieldName, "path:" + rootDir.getAbsolutePath() + " is not exist"); //// return false; //// } // return true; // } // @Override // protected boolean validateDSFactory(IControlMsgHandler msgHandler, Context context, DataSourceFactory dsFactory) { // return super.validateDSFactory(msgHandler, context, dsFactory); // } // // @Override // protected boolean validate(IControlMsgHandler msgHandler, Context context, PostFormVals postFormVals) { // // ParseDescribable<DataSourceFactory> ds = this.newInstance((IPluginContext) msgHandler, postFormVals.rawFormData, Optional.empty()); // // try { // List<String> tables = ds.instance.getTablesInDB(); // // msgHandler.addActionMessage(context, "find " + tables.size() + " table in db"); // } catch (Exception e) { // logger.warn(e.getMessage(), e); // msgHandler.addErrorMessage(context, e.getMessage()); // return false; // } // // return true; // } } }
37.659459
145
0.636716
47a11c0cec21c4c400c3cc978d2b24dc8ed610f3
531
package apple.imagecapturecore.enums; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.NInt; @Generated public final class ICReturnPTPDeviceErrorCode { @Generated private ICReturnPTPDeviceErrorCode() { } /** * PTP Command failed to send */ @Generated @NInt public static final long FailedToSendCommand = 0xFFFFFFFFFFFFACFEL; /** * PTP Command not authorized */ @Generated @NInt public static final long NotAuthorizedToSendCommand = 0xFFFFFFFFFFFFACFFL; }
26.55
95
0.728814
f666bc0ed5d8df92f346f8166c73b42aab9f244d
1,244
package api; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class UserDao { static { String DATABASE_URL = System.getProperty("DATABASE_URL"); } public User getUserBy(int id) { Connection connection; PreparedStatement preparedStatement; ResultSet resultSet; try { String sql = "SELECT id, name FROM USER WHERE id=?"; Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection("jdbc:mysql://my_database/sample?" + "user=user01&password=password"); preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, id); resultSet = preparedStatement.executeQuery(); if(resultSet.next()) { User user = new User(); user.setId(resultSet.getString("id")); user.setName(resultSet.getString("name")); return user; } } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException("Data not found"); } }
30.341463
84
0.582797
15dcbb12a62be3498b3b636ceadb88c54c8a4301
1,090
package com.itboyst.facedemo.dto; public class FaceSearchResDto { private String faceId; private String name; private Integer similarValue; private Integer age; private String gender; private String image; public String getFaceId() { return faceId; } public void setFaceId(String faceId) { this.faceId = faceId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSimilarValue() { return similarValue; } public void setSimilarValue(Integer similarValue) { this.similarValue = similarValue; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
18.166667
55
0.600917
b5e21b15ac7a0cadd11f0eab280bbd7c3fb69f4a
11,713
package Etudiants; import java.awt.EventQueue; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.plaf.nimbus.NimbusLookAndFeel; import net.proteanit.sql.DbUtils; import javax.swing.DefaultComboBoxModel; public class GestionMatieres extends JFrame { /** * */ private static final long serialVersionUID = 7272968866479767561L; private JPanel contentPane; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; private JTable table; private JTextField MatiereField; private JTextField coefField; private JComboBox<String> ProfBox; private JLabel lblCoef; private JComboBox<String> niveauBox; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(new NimbusLookAndFeel()); GestionMatieres gestionMatieres = new GestionMatieres(); gestionMatieres.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public GestionMatieres() { setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 1000, 500); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); connection = ConnexionMySql.ConnectionDB(); JLabel lblNewLabel_2 = new JLabel("Gestion Des Etudiants"); lblNewLabel_2.setBounds(394, 6, 211, 16); lblNewLabel_2.setFont(new Font("Roboto", Font.PLAIN, 20)); contentPane.add(lblNewLabel_2); JLabel lblcoleNationaleDes = new JLabel("École Nationale Des Sciences Appliquées - Al Hoceïma"); lblcoleNationaleDes.setBounds(323, 60, 354, 16); contentPane.add(lblcoleNationaleDes); JLabel lblLogo = new JLabel(""); lblLogo.setBounds(16, 0, 140, 100); lblLogo.setIcon(new ImageIcon("/Users/macbookpro/Desktop/S3/TPJAVA/GestionEtudiants/Images/Webp.net-resizeimage.png")); contentPane.add(lblLogo); JLabel label = new JLabel(""); label.setBounds(882, 0, 94, 100); label.setIcon(new ImageIcon("/Users/macbookpro/Desktop/ProjectJava/uae.png")); contentPane.add(label); JLabel lblNewLabel_1 = new JLabel("New label"); lblNewLabel_1.setBounds(0, 0, 1000, 100); lblNewLabel_1.setIcon(new ImageIcon("/Users/macbookpro/Desktop/S3/TPJAVA/GestionEtudiants/Images/head1.png")); contentPane.add(lblNewLabel_1); MatiereField = new JTextField(); MatiereField.setBounds(203, 171, 130, 26); contentPane.add(MatiereField); MatiereField.setColumns(10); JLabel lblNom = new JLabel("Nom de Matière : "); lblNom.setBounds(89, 176, 116, 16); contentPane.add(lblNom); JLabel lblNiveau = new JLabel("Niveau : "); lblNiveau.setBounds(89, 288, 110, 16); contentPane.add(lblNiveau); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(517, 175, 441, 284); contentPane.add(scrollPane); table = new JTable(); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int ligne = table.getSelectedRow(); String id = table.getModel().getValueAt(ligne, 0).toString(); String sql = "SELECT * FROM Matieres where id_matiere = '"+id+"'"; try { preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { MatiereField.setText(resultSet.getString("NomMatiere")); coefField.setText(resultSet.getString("Coef")); ProfBox.setSelectedItem(resultSet.getString("NomProf")); niveauBox.setSelectedItem(resultSet.getString("Niveau")); } } catch (SQLException e1) { e1.printStackTrace(); } } }); scrollPane.setViewportView(table); JLabel label_1 = new JLabel(""); label_1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { updateTable(); } }); label_1.setIcon(new ImageIcon("/Users/macbookpro/Desktop/S3/TPJAVA/GestionEtudiants/Images/Releoad.png")); label_1.setBounds(892, 110, 50, 50); contentPane.add(label_1); JLabel lblNewLabel_3 = new JLabel("Table des Matieres : "); lblNewLabel_3.setBounds(517, 134, 148, 16); contentPane.add(lblNewLabel_3); JLabel label_2 = new JLabel(""); label_2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { MenuAdministrateur menuAdministrateur = new MenuAdministrateur(); menuAdministrateur.setVisible(true); menuAdministrateur.setLocationRelativeTo(null); fermer(); } }); label_2.setIcon(new ImageIcon("/Users/macbookpro/Desktop/ProjectJava/GoBack_res.png")); label_2.setBounds(10, 113, 50, 50); contentPane.add(label_2); JButton btnNewButton = new JButton(""); btnNewButton.addActionListener(new ActionListener() { @SuppressWarnings("unlikely-arg-type") public void actionPerformed(ActionEvent e) { String nomMatiere = MatiereField.getText().toString(); String Coef = coefField.getText().toString(); String NomProf = ProfBox.getSelectedItem().toString(); String Niveau = niveauBox.getSelectedItem().toString(); String sql = "INSERT INTO Matieres (NomMatiere, Coef, NomProf, Niveau) VALUES (?, ?, ?, ?)"; try { if (!MatiereField.equals("") && !niveauBox.getSelectedItem().toString().equals("Selectionnez") && !ProfBox.getSelectedItem().equals("Selectionnez") && !coefField.equals("")) { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, nomMatiere); preparedStatement.setString(2, Coef); preparedStatement.setString(3, NomProf); preparedStatement.setString(4, Niveau); preparedStatement.execute(); updateTable(); MatiereField.setText(""); niveauBox.setSelectedItem("Selectionnez"); JOptionPane.showMessageDialog(null, "Matiere Ajoutee avec succes!"); }else { JOptionPane.showMessageDialog(null, "Erreur!"); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); btnNewButton.setIcon(new ImageIcon("/Users/macbookpro/Desktop/S3/TPJAVA/GestionEtudiants/Images/add-branche-res.png")); btnNewButton.setBounds(21, 370, 80, 80); contentPane.add(btnNewButton); JButton button = new JButton(""); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int ligne = table.getSelectedRow(); if (ligne == -1) { JOptionPane.showMessageDialog(null, "Selectionez un Niveau!"); }else { String id = table.getModel().getValueAt(ligne, 0).toString(); String sql = "UPDATE Matieres SET NomMatiere = ?, coef = ?, NomProf = ?, Niveau = ? WHERE id_matiere = '"+id+"'"; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, MatiereField.getText().toString()); preparedStatement.setString(2, coefField.getText().toString()); preparedStatement.setString(3, ProfBox.getSelectedItem().toString()); preparedStatement.setString(4, niveauBox.getSelectedItem().toString()); preparedStatement.execute(); updateTable(); MatiereField.setText(""); niveauBox.setSelectedItem("Selectionnez"); JOptionPane.showMessageDialog(null, "Matiere Modifiee avec succes!!"); updateTable(); } catch (SQLException e1) { e1.printStackTrace(); } } } }); button.setIcon(new ImageIcon("/Users/macbookpro/Desktop/S3/TPJAVA/GestionEtudiants/Images/Exchange-branche.png")); button.setBounds(150, 370, 80, 80); contentPane.add(button); JButton button_1 = new JButton(""); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int ligne = table.getSelectedRow(); String id = table.getModel().getValueAt(ligne, 0).toString(); if (ligne == -1) { JOptionPane.showMessageDialog(null, "Selectionnez un Niveau!!"); }else { String sql = "DELETE FROM Matieres WHERE id_matiere = '"+id+"'"; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.execute(); MatiereField.setText(""); niveauBox.setSelectedItem("Selectionnez"); updateTable(); JOptionPane.showMessageDialog(null, "Matiere supprimee avec succes!!"); updateTable(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); button_1.setIcon(new ImageIcon("/Users/macbookpro/Desktop/S3/TPJAVA/GestionEtudiants/Images/delete-branche-res.png")); button_1.setBounds(299, 370, 80, 80); contentPane.add(button_1); JLabel lblProfesseur = new JLabel("Professeur : "); lblProfesseur.setBounds(89, 249, 110, 16); contentPane.add(lblProfesseur); ProfBox = new JComboBox<String>(); ProfBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Selectionnez"})); ProfBox.setBounds(203, 245, 134, 27); contentPane.add(ProfBox); FillProfBox(); lblCoef = new JLabel("coef : "); lblCoef.setBounds(89, 209, 110, 16); contentPane.add(lblCoef); coefField = new JTextField(); coefField.setColumns(10); coefField.setBounds(203, 204, 130, 26); contentPane.add(coefField); niveauBox = new JComboBox<String>(); niveauBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Selectionnez"})); niveauBox.setBounds(203, 284, 134, 27); contentPane.add(niveauBox); FillNiveauBox(); JLabel lblNewLabel = new JLabel("New label"); lblNewLabel.setBounds(0, 0, 1000, 478); lblNewLabel.setIcon(new ImageIcon("/Users/macbookpro/Desktop/S3/TPJAVA/GestionEtudiants/Images/Sans titre-1.png")); contentPane.add(lblNewLabel); } public void fermer() { dispose(); } public void updateTable() { String sql = "SELECT * FROM Matieres"; try { preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); table.setModel(DbUtils.resultSetToTableModel(resultSet)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void FillProfBox() { String sql = "Select * from Professeurs"; try { preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String nom = resultSet.getString("Nom_prof").toString(); ProfBox.addItem(nom); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void FillNiveauBox() { String sql = "Select * from Niveaux"; try { preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String nom = resultSet.getString("Niveau").toString(); niveauBox.addItem(nom); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
32.090411
180
0.700931
5e688fdc672735d50bd73387d50246ace410d117
5,137
/* * Copyright 2020 momosecurity. * * 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.immomo.momosec.lang.java.rule.momosecurity; import com.immomo.momosec.lang.java.MomoJavaCodeInsightFixtureTestCase; public class XxeInspectorTest extends MomoJavaCodeInsightFixtureTestCase { String dirPrefix = "rule/momosecurity/XxeInspector/"; public void testIfFindsAllVulns() { myFixture.copyFileToProject(dirPrefix + "stub/DocumentBuilderFactory.java"); myFixture.copyFileToProject(dirPrefix + "stub/SAXParserFactory.java"); myFixture.copyFileToProject(dirPrefix + "stub/SAXTransformerFactory.java"); myFixture.copyFileToProject(dirPrefix + "stub/XMLConstants.java"); doTest(new XxeInspector(), dirPrefix + "Vuln.java"); } public void testDocumentBuilderFactoryLocalVuln() { testQuickFixEntityInLocalVariable( "DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();", "dbf.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true)", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.DOCUMENT_BUILDER, XxeInspector.VulnElemType.LOCAL_VARIABLE) ); } public void testDocumentBuilderFactoryClassVuln() { testQuickFixEntityInMethodAssignment( "DocumentBuilderFactory dbf;\n" + "public foo () {\n" + " dbf = DocumentBuilderFactory.newInstance();" + "}", "dbf.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true)", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.DOCUMENT_BUILDER, XxeInspector.VulnElemType.ASSIGNMENT_EXPRESSION) ); } public void testSAXParserFactoryLocalVuln() { testQuickFixEntityInLocalVariable( "SAXParserFactory spf = SAXParserFactory.newInstance();", "spf.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true)", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.SAX_PARSER_FACTORY, XxeInspector.VulnElemType.LOCAL_VARIABLE) ); } public void testSAXParserFactoryClassVuln() { testQuickFixEntityInMethodAssignment( "SAXParserFactory spf;\n" + "public foo() {\n" + " spf = SAXParserFactory.newInstance();\n" + "}", "spf.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true)", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.SAX_PARSER_FACTORY, XxeInspector.VulnElemType.ASSIGNMENT_EXPRESSION) ); } public void testSAXTransformerFactoryLocalVuln() { testQuickFixEntityInLocalVariable( "SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();", "sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, \"\")", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.SAX_TRANSFORMER_FACTORY, XxeInspector.VulnElemType.LOCAL_VARIABLE) ); } public void testSAXTransformerFactoryClassVuln() { testQuickFixEntityInMethodAssignment( "SAXTransformerFactory sf;\n" + "public foo() {\n" + " sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();\n" + "}", "sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, \"\")", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.SAX_TRANSFORMER_FACTORY, XxeInspector.VulnElemType.ASSIGNMENT_EXPRESSION) ); } public void testDocumentBuilderFactoryClassFieldInitVuln() { testQuickFixInClassInitializer( "private final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();", "dbf.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true)", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.DOCUMENT_BUILDER, XxeInspector.VulnElemType.CLASS_FIELD) ); } public void testDocumentBuilderFactoryStaticClassFieldInitVuln() { testQuickFixInClassInitializer( "private static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();", "dbf.setFeature(\"http://apache.org/xml/features/disallow-doctype-decl\", true)", new XxeInspector.XxeInspectionQuickFix(XxeInspector.XmlFactory.DOCUMENT_BUILDER, XxeInspector.VulnElemType.CLASS_FIELD) ); } }
48.462264
152
0.687755
891fd553297f9dec5f3c35e6d1c4773a3e3e9ae8
6,799
package cn.wildfire.chat.kit.contact.pick; import android.graphics.Rect; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import butterknife.BindView; import butterknife.OnFocusChange; import butterknife.OnTextChanged; import cn.wildfire.chat.kit.contact.BaseUserListFragment; import cn.wildfire.chat.kit.contact.UserListAdapter; import cn.wildfire.chat.kit.contact.model.UIUserInfo; import cn.wildfire.chat.kit.third.utils.UIUtils; import cn.wildfire.chat.kit.widget.QuickIndexBar; import cn.wildfirechat.chat.R; public abstract class PickUserFragment extends BaseUserListFragment implements QuickIndexBar.OnLetterUpdateListener { private SearchAndPickUserFragment searchAndPickUserFragment; protected PickUserViewModel pickUserViewModel; @BindView(R.id.pickedUserRecyclerView) protected RecyclerView pickedUserRecyclerView; @BindView(R.id.searchEditText) EditText searchEditText; @BindView(R.id.searchFrameLayout) FrameLayout searchUserFrameLayout; @BindView(R.id.hint_view) protected View hintView; private boolean isSearchFragmentShowing = false; private PickedUserAdapter pickedUserAdapter; private Observer<UIUserInfo> contactCheckStatusUpdateLiveDataObserver = userInfo -> { ((CheckableUserListAdapter) userListAdapter).updateUserStatus(userInfo); hideSearchContactFragment(); updatePickedUserView(userInfo); }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); pickUserViewModel = ViewModelProviders.of(getActivity()).get(PickUserViewModel.class); pickUserViewModel.userCheckStatusUpdateLiveData().observeForever(contactCheckStatusUpdateLiveDataObserver); } @Override protected void afterViews(View view) { super.afterViews(view); initView(); setupPickFromUsers(); } @Override public void onDestroyView() { super.onDestroyView(); pickUserViewModel.userCheckStatusUpdateLiveData().removeObserver(contactCheckStatusUpdateLiveDataObserver); } private void initView() { configPickedUserRecyclerView(); pickedUserAdapter = getPickedUserAdapter(); pickedUserRecyclerView.setAdapter(pickedUserAdapter); } protected void configPickedUserRecyclerView() { RecyclerView.LayoutManager pickedContactRecyclerViewLayoutManager = new LinearLayoutManager(getActivity(), GridLayoutManager.HORIZONTAL, false); pickedUserRecyclerView.setLayoutManager(pickedContactRecyclerViewLayoutManager); pickedUserRecyclerView.addItemDecoration(new Decoration()); } protected PickedUserAdapter getPickedUserAdapter() { return new PickedUserAdapter(); } @OnFocusChange(R.id.searchEditText) void onSearchEditTextFocusChange(View view, boolean focus) { if (getActivity() == null || getActivity().isFinishing()) { return; } if (focus) { showSearchContactFragment(); } else { hideSearchContactFragment(); } handleHintView(focus); } protected void handleHintView(boolean focus) { if (pickedUserAdapter.getItemCount() == 0 && !focus) { hintView.setVisibility(View.VISIBLE); } else { hintView.setVisibility(View.GONE); } } @OnTextChanged(value = R.id.searchEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED) void search(Editable editable) { // restore view state if (searchAndPickUserFragment == null) { return; } String key = editable.toString(); if (!TextUtils.isEmpty(key)) { searchAndPickUserFragment.search(key); } else { searchAndPickUserFragment.rest(); } } @Override public int getContentLayoutResId() { return R.layout.contact_pick_fragment; } @Override public UserListAdapter onCreateUserListAdapter() { return new CheckableUserListAdapter(this); } abstract protected void setupPickFromUsers(); private void showSearchContactFragment() { if (searchAndPickUserFragment == null) { searchAndPickUserFragment = new SearchAndPickUserFragment(); searchAndPickUserFragment.setPickUserFragment(this); } searchUserFrameLayout.setVisibility(View.VISIBLE); getChildFragmentManager().beginTransaction() .replace(R.id.searchFrameLayout, searchAndPickUserFragment) .commit(); isSearchFragmentShowing = true; } public void hideSearchContactFragment() { if (!isSearchFragmentShowing) { return; } searchEditText.setText(""); searchEditText.clearFocus(); searchUserFrameLayout.setVisibility(View.GONE); getChildFragmentManager().beginTransaction().remove(searchAndPickUserFragment).commit(); isSearchFragmentShowing = false; } @Override public void onUserClick(UIUserInfo userInfo) { if (userInfo.isCheckable()) { if (!pickUserViewModel.checkUser(userInfo, !userInfo.isChecked())) { Toast.makeText(getActivity(), "选人超限", Toast.LENGTH_SHORT).show(); } } } protected void handleEditText() { if (pickedUserAdapter.getItemCount() == 0) { searchEditText.setHint(""); } else { searchEditText.setHint("搜索"); } } private void updatePickedUserView(UIUserInfo userInfo) { if (userInfo.isChecked()) { pickedUserAdapter.addUser(userInfo); } else { pickedUserAdapter.removeUser(userInfo); } handleHintView(false); handleEditText(); } private static class Decoration extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { int position = parent.getChildAdapterPosition(view); if (position < parent.getAdapter().getItemCount() - 1) { outRect.right = UIUtils.dip2Px(4); } else { outRect.right = 0; } } } }
34.338384
152
0.693484
e9b25288466a480ba0dca8665d026c6bd4e82d1f
1,372
package personenkartei; import javax.swing.*; import java.util.Objects; public final class JFormTextField { private final PersonField personFieldTitle; private final JPanel panel; public JFormTextField(PersonField personFieldTitle, JPanel panel) { this.personFieldTitle = personFieldTitle; this.panel = panel; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; var that = (JFormTextField) obj; return Objects.equals(this.personFieldTitle, that.personFieldTitle) && Objects.equals(this.panel, that.panel); } @Override public int hashCode() { return Objects.hash(personFieldTitle, panel); } @Override public String toString() { return "JFormTextField[" + "personFieldTitle=" + personFieldTitle + ", " + "panel=" + panel + ']'; } public JPlaceholderTextFiled build() { Main.debug("Textfield added: " + personFieldTitle.toString()); JPlaceholderTextFiled jTextField = new JPlaceholderTextFiled(); jTextField.setPlaceholder(personFieldTitle.toString()); panel.add(new JLabel(personFieldTitle.toString())); panel.add(jTextField); return jTextField; } }
28.583333
78
0.641399
0ab007e666d765f5be7f065440d3c8ecbf3d84c4
9,973
// ============================================================================ // // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.metadata.managment.ui.wizard.documentation; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.eclipse.core.runtime.IPath; import org.talend.core.model.properties.DocumentationItem; import org.talend.core.model.properties.Item; import org.talend.core.model.properties.LinkDocumentationItem; import org.talend.core.model.properties.LinkType; import org.talend.core.repository.constants.FileConstants; /** * ggu class global comment. Detailled comment */ public final class LinkUtils { public static final String DOT = "."; //$NON-NLS-1$ public static final String NETWORK_PAGE_PATTERN = "(html|htm|php|asp|jsp|shtml)"; //$NON-NLS-1$ public static final String COMPRESSION_FILE_PATTERN = "(rar|zip|jar|arj|arc|cab)|(tar|Z|tgz|gz|bz2|bz|deb|rpm|lha)"; //$NON-NLS-1$ public static final String EXEC_FILE_PATTERN = "(exe|com)"; //$NON-NLS-1$ /* * match "/file.html" or "/file" */ public static final String NET_FILE_PATTERN = "(/\\w+(\\.(" + NETWORK_PAGE_PATTERN + "|" + COMPRESSION_FILE_PATTERN + "|" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + EXEC_FILE_PATTERN + "))?)$"; //$NON-NLS-1$ /* * such as: "http://www.talend.com/..." or "http://193.189.143.143/..." */ public static final String HTTP_PATTERN = "^(http://([\\w-]+\\.)+[\\w-]+)(/\\S*)?"; //$NON-NLS-1$ /** * */ public enum LinkInfo { FILE_NOT_FOUND, URL_ERROR, NET_ERROR, LINK_OK, } /** * * ggu Comment method "existedLink". * * the link is valid or not. */ public static boolean validateLink(LinkType link) { if (link == null) { return false; } String uri = link.getURI(); if (isRemoteFile(uri)) { if (testRemoteFile(uri) == LinkInfo.LINK_OK) { return true; } } else if (existedFile(uri)) { return true; } return false; } /** * * ggu Comment method "isFile". * * check the file */ public static boolean isFile(final String file) { if (file == null) { return false; } if (isFile(new File(file.trim()))) { return true; } return false; } public static boolean isFile(final File file) { if (file == null) { return false; } if (file.isFile()) { return true; } return false; } public static boolean isFile(final IPath path) { if (path == null) { return false; } if (isFile(path.toFile())) { return true; } return false; } /** * * ggu Comment method "existedFile". * * the file is existed or not. */ public static boolean existedFile(final File file) { if (!isFile(file)) { return false; } if (file.exists()) { return true; } return false; } public static boolean existedFile(final String file) { if (file == null) { return false; } if (existedFile(new File(file.trim()))) { return true; } return false; } public static boolean existedFile(final IPath path) { if (path == null) { return false; } if (existedFile(path.toFile())) { return true; } return false; } /** * * ggu Comment method "isPropertyFile". * * check the file is property file or not. */ public static boolean isPropertyFile(IPath path) { if (!isFile(path)) { return false; } return FileConstants.PROPERTIES_EXTENSION.equals(path.getFileExtension()); } public static boolean isPropertyFile(File file) { if (!isFile(file)) { return false; } return file.getAbsolutePath().endsWith(FileConstants.PROPERTIES_EXTENSION); } /** * * ggu Comment method "isItemFile". * * check the file is item file or not. */ public static boolean isItemFile(IPath path) { if (!isFile(path)) { return false; } return FileConstants.ITEM_EXTENSION.equals(path.getFileExtension()); } public static boolean isItemFile(File file) { if (!isFile(file)) { return false; } return file.getAbsolutePath().endsWith(FileConstants.ITEM_EXTENSION); } /** * * ggu Comment method "isLinkDocumentationItem". * */ public static boolean isLinkDocumentationItem(Item item) { if (item == null) { return false; } if (item instanceof LinkDocumentationItem) { return true; } return false; } public static boolean isDocumentationItem(Item item) { if (item == null) { return false; } if (item instanceof DocumentationItem) { return true; } return false; } /** * * ggu Comment method "getItemPath". * * get the related Item file. */ public static IPath getItemPath(IPath path) { if (!isFile(path)) { return null; } return path.removeFileExtension().addFileExtension(FileConstants.ITEM_EXTENSION); } /** * * ggu Comment method "getPropertiesPath". * * get the related property file. */ public static IPath getPropertyPath(IPath path) { if (!isFile(path)) { return null; } return path.removeFileExtension().addFileExtension(FileConstants.PROPERTIES_EXTENSION); } public static boolean isRemoteFile(final String remoteFile) { if (remoteFile == null) { return false; } Perl5Matcher matcher = new Perl5Matcher(); Perl5Compiler compiler = new Perl5Compiler(); Pattern pattern; try { pattern = compiler.compile(HTTP_PATTERN); if (matcher.contains(remoteFile, pattern)) { return true; } } catch (MalformedPatternException e) { return false; } return false; } public static LinkInfo testRemoteFile(String uri) { if (uri == null) { return LinkInfo.URL_ERROR; } uri = uri.trim(); if (!isRemoteFile(uri)) { return LinkInfo.URL_ERROR; } try { URL url = new URL(uri); return testRemoteFile(url); } catch (MalformedURLException e) { return LinkInfo.URL_ERROR; } } public static LinkInfo testRemoteFile(final URL url) { if (url == null) { return LinkInfo.URL_ERROR; } HttpURLConnection httpConn = null; try { httpConn = (HttpURLConnection) url.openConnection(); httpConn.connect(); httpConn.getContent(); // if (!httpConn.getURL().equals(url)) { // return LinkInfo.FILE_NOT_FOUND; // } } catch (FileNotFoundException e) { return LinkInfo.FILE_NOT_FOUND; } catch (IOException e) { return LinkInfo.NET_ERROR; } finally { if (httpConn != null) { httpConn.disconnect(); } } return LinkInfo.LINK_OK; } /** * * ggu Comment method "checkLinkFile". * * @param uri * @return */ public static boolean checkLinkFile(final String uri) { if (uri == null) { return false; } if (!isRemoteFile(uri)) { return false; } try { URL url = new URL(uri); final String file = url.getFile(); if (file != null) { if (file.equals(url.getPath())) { // match "http://xx.xx.xx" if ("".equals(file)) { //$NON-NLS-1$ return true; } // match "http://xx.xx.xx/" or "http://xx.xx.xx/yy/" if (file.endsWith("/")) { //$NON-NLS-1$ return true; } Perl5Matcher matcher = new Perl5Matcher(); Perl5Compiler compiler = new Perl5Compiler(); Pattern pattern; pattern = compiler.compile(NET_FILE_PATTERN); // match "http://xx.xx.xx/yy/zz" or "http://xx.xx.xx/yy/zz/abc.htm" if (matcher.contains(file, pattern)) { return true; } } else { // match the "http://xxxx.xx/a.php?a=b" return true; } } } catch (MalformedPatternException e) { // } catch (MalformedURLException e) { // } return false; } }
27.626039
167
0.527324
4b1d2f2d065fe3482f73ad02664b9c72fb19c8c9
2,670
package xyz.kvantum.bukkit.objects; import lombok.NonNull; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.entity.Player; import xyz.kvantum.bukkit.util.PlayerUtil; import xyz.kvantum.server.api.util.SearchResultProvider; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; public class PlayerManager implements SearchResultProvider<KvantumPlayer, KvantumPlayer> { @Override public Collection<? extends KvantumPlayer> getResults(@NonNull final KvantumPlayer kvantumPlayer) { final Collection<KvantumPlayer> kvantumPlayers = new ArrayList<>(); if ( !kvantumPlayer.getUsername().isEmpty() ) { final Player bukkitPlayer = Bukkit.getPlayer( kvantumPlayer.getUsername() ); if ( bukkitPlayer != null ) { kvantumPlayers.add( new KvantumPlayer( bukkitPlayer ) ); } else { final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer( kvantumPlayer.getUsername() ); if ( offlinePlayer != null && offlinePlayer.hasPlayedBefore() ) { kvantumPlayers.add( new KvantumPlayer( offlinePlayer ) ); } } } else if ( !kvantumPlayer.getUuid().isEmpty() ) { UUID uuid = null; try { uuid = UUID.fromString( kvantumPlayer.getUuid() ); } catch ( final Exception ignore ) {} if ( uuid != null ) { final Player bukkitPlayer = Bukkit.getPlayer( uuid ); if ( bukkitPlayer != null ) { kvantumPlayers.add( new KvantumPlayer( bukkitPlayer ) ); } else { final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer( uuid ); if ( offlinePlayer != null && offlinePlayer.hasPlayedBefore() ) { kvantumPlayers.add( new KvantumPlayer( offlinePlayer ) ); } } } } else if ( !kvantumPlayer.getWorld().isEmpty() ) { final World world = Bukkit.getWorld( kvantumPlayer.getWorld() ); if ( world != null ) { for ( final Player player : world.getPlayers() ) { kvantumPlayers.add( new KvantumPlayer( player ) ); } } } else { kvantumPlayers.addAll( PlayerUtil.getOnlinePlayers() ); } return kvantumPlayers; } }
35.131579
107
0.551311
adba73b0b9286e3b79376a627dfa4cb11282fec8
515
package com.ssm.aspectj.annotation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ssm.aspectj.UserDao; public class TestAspectjAnnotation { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ctn = new ClassPathXmlApplicationContext("com/ssm/aspectj/annotation/applicationContext.xml"); UserDao userDao = (UserDao) ctn.getBean("userDao"); userDao.addUser(); } }
28.611111
115
0.8
82e6358e14233e61b6463c159f4206a7f9035722
8,993
package com.vaadin.tutorial.crm.ui.view.questionnaire; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.listbox.ListBox; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.Route; import com.vaadin.tutorial.crm.backend.entity.Patient; import com.vaadin.tutorial.crm.backend.entity.Questionnaire; import com.vaadin.tutorial.crm.backend.entity.UserAnswers; import com.vaadin.tutorial.crm.backend.service.*; import com.vaadin.tutorial.crm.security.PatientDetails; import com.vaadin.tutorial.crm.ui.view.user.UserSurveyView; import org.springframework.security.core.context.SecurityContextHolder; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; @Route(value = "scl", layout = UserSurveyView.class) public class Survey extends VerticalLayout { private final AnswerService answerService; private QuestionService questionService; private QuestionnaireService questionnaireService; private ContactService contactService; private UserAnswerService userAnswerService; private TextField filterText = new TextField(); // Layout of survey private FormLayout surveyLayout = new FormLayout(); // Holds list of answers to display private ListBox<String> ansrList = new ListBox<>(); // Holds user selected answers private List<String> answers = new LinkedList<>(); // pop up private Pop popup = new Pop(); // Holds list of questions private List<String> questionList = new ArrayList<>(); // Grid to hold questions Grid<String> grid = new Grid<>(String.class); // Button to go to next question private Button nextBtn = new Button("Next"); // Button to save survey private Button saveBtn = new Button("Save"); // int to hold question number private int count = 0; // New Date for survey private Date date = new Date(); // Holds patient information private Patient user; // Creating new survey Questionnaire survey = new Questionnaire(); // New UseAnswer entry UserAnswers userAn = new UserAnswers(); // Question holder H2 question = new H2(); // Used to hold the selected answer String selectedAnswer = ""; public Survey(AnswerService answerService, UserAnswerService userAnswerService, QuestionService questionService, QuestionnaireService questionnaireService, ContactService contactService){ this.answerService = answerService; this.questionService = questionService; this.questionnaireService= questionnaireService; this.contactService = contactService; this.userAnswerService = userAnswerService; // Set the date of the survey survey.setDate(date); // Getting patient currently logged in PatientDetails patient = getPatient(); // Setting the patient to currently logged in patient user = patient.getPatient(); // Getting questionnaire answers getAnswers(); // Getting question for questionnaire getQuestions(); surveyLayout.addClassName("survey_layout"); // Adding class name to next button nextBtn.addClassName("survey_btn_layout"); // Adding class name to save button saveBtn.addClassName("save_button"); // Prime listener for first selection if(answers.isEmpty()){ addAnswer(); // Remove empty primer from front of list answers.remove(0); } // Calling function to get next question nextBtn.addClickListener(click -> nextQuestion()); // Calling function to save questionnaire saveBtn.addClickListener(click -> saveQuestionnaire()); // Setting patient userAn.setPatient(user); // Setting current question question.setText(questionList.get(count)); surveyLayout.setResponsiveSteps( new FormLayout.ResponsiveStep("0", 1) ); surveyLayout.setColspan(question, 4); // Setting layout to have question, answers, and navigation button surveyLayout.add(question,ansrList, nextBtn); // Adding layout add(surveyLayout); } private void getAnswers(){ ansrList.setItems(answerService.getAnswers(answerService)); } private void getQuestions(){ questionList.addAll(questionService.getQuestions(questionService)); } // Moves to the next question private void nextQuestion(){ // Display finish button if(count == questionList.size() - 2){ nextBtn.removeClassName("survey_btn_layout"); nextBtn.addClassName("btn_hide"); surveyLayout.add(saveBtn); } // Set next question value if(count != questionList.size() - 1){ if(addAnswer()){ popup.setB(false); question.setText(questionList.get(++count)); } else{ popup.setB(true); popup.getPopupContent(); } //Add selected answer to list //addAnswer(); ansrList.clear(); } } // Adds selected answer to list of answers private boolean addAnswer(){ ansrList.addValueChangeListener(event -> { selectedAnswer = event.getValue(); //System.out.println("Value of selected answer is " + answerService.getAnswerVal(selectedAnswer)); System.out.println("Value changed to " + selectedAnswer); }); if(answers.isEmpty()){ System.out.println("list is empty"); answers.add(0, selectedAnswer); } else{ if(selectedAnswer != null){ System.out.println("Selected answer is " + selectedAnswer); answers.add(selectedAnswer); System.out.println(answers); return true; } else{ return false; } } return false; } private void saveQuestionnaire(){ System.out.println(survey.getDate()); addAnswer(); saveAnswers(answers); questionnaireService.save(survey); userAnswerService.save(userAn); } private PatientDetails getPatient(){ Object patient = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return (PatientDetails) patient; } // Sets all of user selected answers private void saveAnswers(List<String> l){ userAn.setAnswerOne(answerService.getAnswerVal(l.get(0))); userAn.setAnswerTwo(answerService.getAnswerVal(l.get(1))); userAn.setAnswerThree(answerService.getAnswerVal(l.get(2))); userAn.setAnswerFour(answerService.getAnswerVal(l.get(3))); userAn.setAnswerFive(answerService.getAnswerVal(l.get(4))); userAn.setAnswerSix(answerService.getAnswerVal(l.get(5))); userAn.setAnswerSeven(answerService.getAnswerVal(l.get(6))); userAn.setAnswerEight(answerService.getAnswerVal(l.get(7))); userAn.setAnswerNine(answerService.getAnswerVal(l.get(8))); userAn.setAnswerTen(answerService.getAnswerVal(l.get(9))); userAn.setAnswerEleven(answerService.getAnswerVal(l.get(10))); userAn.setAnswerTwelve(answerService.getAnswerVal(l.get(11))); userAn.setAnswerThirteen(answerService.getAnswerVal(l.get(12))); userAn.setAnswerFourteen(answerService.getAnswerVal(l.get(13))); userAn.setAnswerFifteen(answerService.getAnswerVal(l.get(14))); userAn.setAnswerSixteen(answerService.getAnswerVal(l.get(15))); userAn.setAnswerSeventeen(answerService.getAnswerVal(l.get(16))); userAn.setAnswerEighteen(answerService.getAnswerVal(l.get(17))); userAn.setAnswerNineteen(answerService.getAnswerVal(l.get(18))); userAn.setAnswerTwenty(answerService.getAnswerVal(l.get(19))); userAn.setAnswerTwentyOne(answerService.getAnswerVal(l.get(20))); userAn.setAnswerTwentyTwo(answerService.getAnswerVal(l.get(21))); userAn.setAnswerTwentyThree(answerService.getAnswerVal(l.get(22))); userAn.setAnswerTwentyFour(answerService.getAnswerVal(l.get(23))); userAn.setAnswerTwentyFive(answerService.getAnswerVal(l.get(24))); userAn.setAnswerTwentySix(answerService.getAnswerVal(l.get(25))); userAn.setAnswerTwentySeven(answerService.getAnswerVal(l.get(26))); userAn.setAnswerTwentyEight(answerService.getAnswerVal(l.get(27))); userAn.setAnswerTwentyNine(answerService.getAnswerVal(l.get(28))); userAn.setAnswerThirty(answerService.getAnswerVal(l.get(29))); userAn.setAnswerThirtyOne(answerService.getAnswerVal(l.get(30))); } }
38.930736
191
0.677082
efcd479abf616ff28906e0037e5b3373c395cf13
1,710
/* * Copyright 2017 LINE Corporation * * LINE Corporation 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.server.annotation; import static com.linecorp.armeria.internal.server.annotation.DefaultValues.UNSPECIFIED; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Specifies the default value of an optional parameter. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR }) public @interface Default { /** * The default value to use as a fallback when the request parameter is not provided or has an empty value. * When {@link Default} annotation exists but {@link Default#value()} is not specified, {@code null} * value would be set if the parameter is not present in the request. * * {@link Default} annotation is not allowed for a path variable. If a user uses {@link Default} * annotation on a path variable, {@link IllegalArgumentException} would be raised. */ String value() default UNSPECIFIED; }
39.767442
111
0.750292
43869468cfd1cc8085129b0d4048b29cccd05c17
6,305
/* * 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.shenyu.common.dto; import java.util.Objects; /** * PluginData. * * @since 2.0.0 */ public class PluginData { private String id; private String name; private String config; private String role; private Boolean enabled; /** * no args constructor. */ public PluginData() { } /** * all args constructor. * * @param id id * @param name name * @param config config * @param role role * @param enabled enabled */ public PluginData(final String id, final String name, final String config, final String role, final Boolean enabled) { this.id = id; this.name = name; this.config = config; this.role = role; this.enabled = enabled; } /** * builder constructor. * * @param builder builder */ private PluginData(final Builder builder) { this.id = builder.id; this.name = builder.name; this.config = builder.config; this.role = builder.role; this.enabled = builder.enabled; } /** * class builder. * * @return Builder */ public static Builder builder() { return new Builder(); } /** * get id. * * @return id */ public String getId() { return id; } /** * set id. * * @param id id */ public void setId(final String id) { this.id = id; } /** * get name. * * @return name */ public String getName() { return name; } /** * set name. * * @param name name */ public void setName(final String name) { this.name = name; } /** * get config. * * @return config */ public String getConfig() { return config; } /** * set config. * * @param config config */ public void setConfig(final String config) { this.config = config; } /** * get role. * * @return role */ public String getRole() { return role; } /** * set role. * * @param role role */ public void setRole(final String role) { this.role = role; } /** * get enabled. * * @return enabled */ public Boolean getEnabled() { return enabled; } /** * set enabled. * * @param enabled enabled */ public void setEnabled(final Boolean enabled) { this.enabled = enabled; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PluginData that = (PluginData) o; return Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(config, that.config) && Objects.equals(role, that.role) && Objects.equals(enabled, that.enabled); } @Override public int hashCode() { return Objects.hash(id, name, config, role, enabled); } @Override public String toString() { return "PluginData{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", config='" + config + '\'' + ", role='" + role + '\'' + ", enabled=" + enabled + '}'; } /** * class builder. */ public static final class Builder { /** * id. */ private String id; /** * name. */ private String name; /** * config. */ private String config; /** * role. */ private String role; /** * enabled. */ private Boolean enabled; /** * no args constructor. */ private Builder() { } /** * build new Object. * * @return PluginData */ public PluginData build() { return new PluginData(this); } /** * build id. * * @param id id * @return this */ public Builder id(final String id) { this.id = id; return this; } /** * build name. * * @param name name * @return this */ public Builder name(final String name) { this.name = name; return this; } /** * build config. * * @param config config * @return this */ public Builder config(final String config) { this.config = config; return this; } /** * build role. * * @param role role * @return this */ public Builder role(final String role) { this.role = role; return this; } /** * build enabled. * * @param enabled enabled * @return this */ public Builder enabled(final Boolean enabled) { this.enabled = enabled; return this; } } }
20.14377
122
0.478033
64468315577e30b21f04427f6fd85cf15ce04eb3
2,366
package strings; public class detectCapital { public static void main(String[] args) { SolutionDC solution = new SolutionDC(); System.out.println(solution.detectCapitalUse("USA")); System.out.println(solution.detectCapitalUse("FLaG")); System.out.println(solution.detectCapitalUse("Google")); System.out.println(solution.detectCapitalUse("leetcode")); System.out.println(); System.out.println(solution.detectCapitalUseApproach2("USA")); System.out.println(solution.detectCapitalUseApproach2("FLaG")); System.out.println(solution.detectCapitalUseApproach2("Google")); System.out.println(solution.detectCapitalUseApproach2("leetcode")); } } class SolutionDC { // TC : O(N) // SC : O(N) // Brute Force : Using Extra space public boolean detectCapitalUse(String word) { String allCapital = word.toUpperCase(); String firstCapital = word.substring(0,1).toUpperCase()+word.substring(1).toLowerCase(); String lowerCase = word.toLowerCase(); return (word.equals(allCapital) || word.equals(firstCapital) || word.equals(lowerCase)); } // TC : O(N) // SC : O(1) // Runtime: 1 ms, faster than 99.35% of Java online submissions for Detect Capital. // Memory Usage: 39 MB, less than 43.48% of Java online submissions for Detect Capital. // Efficient Solution // o solve this problem, we count the number of capital letters in the word and then check all three conditions: // Number of capital letters is equal to the length of the word // Number of capital letters is zero // There is just one capital letter and it's the first letter // Time: O(n) - for the scan // Space: O(1) // Submitted by @ Kushvr public boolean detectCapitalUseApproach2(String word) { int len = word.length(); int countOfCapitalLetters = 0; boolean firstLetterIsCapital = word.charAt(0) >=65 && word.charAt(0) <=90; for(int i=0;i<len;i++){ int k = word.charAt(i); if(k>= 65 && k<= 90) countOfCapitalLetters++; } return ( countOfCapitalLetters == len || (firstLetterIsCapital && countOfCapitalLetters==1)|| countOfCapitalLetters==0 ); } }
31.546667
116
0.632291
593f3db3292c19607b64ee6a5fad335efa7b5451
8,968
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.usagestatistics.storage; import java.io.PrintStream; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import org.sosy_lab.common.configuration.Configuration; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.common.time.Timer; import org.sosy_lab.cpachecker.cpa.usagestatistics.TemporaryUsageStorage; import org.sosy_lab.cpachecker.cpa.usagestatistics.UsageInfo; import org.sosy_lab.cpachecker.cpa.usagestatistics.UsageStatisticsState; import org.sosy_lab.cpachecker.cpa.usagestatistics.refinement.RefinementResult; import org.sosy_lab.cpachecker.util.identifiers.SingleIdentifier; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class UsageContainer { private final SortedMap<SingleIdentifier, UnrefinedUsagePointSet> unrefinedIds; private final SortedMap<SingleIdentifier, RefinedUsagePointSet> refinedIds; private final UnsafeDetector detector; private final Set<SingleIdentifier> falseUnsafes; private final Set<SingleIdentifier> processedUnsafes = new HashSet<>(); //Only for statistics private Set<SingleIdentifier> initialSet = null; private int initialUsages; private final LogManager logger; public Timer resetTimer = new Timer(); int unsafeUsages = -1; int totalIds = 0; public UsageContainer(Configuration config, LogManager l) throws InvalidConfigurationException { this(new TreeMap<SingleIdentifier, UnrefinedUsagePointSet>(), new TreeMap<SingleIdentifier, RefinedUsagePointSet>(), new TreeSet<SingleIdentifier>(), l, new UnsafeDetector(config)); } private UsageContainer(SortedMap<SingleIdentifier, UnrefinedUsagePointSet> pUnrefinedStat, SortedMap<SingleIdentifier, RefinedUsagePointSet> pRefinedStat, Set<SingleIdentifier> pFalseUnsafes, LogManager pLogger, UnsafeDetector pDetector) { unrefinedIds = pUnrefinedStat; refinedIds = pRefinedStat; falseUnsafes = pFalseUnsafes; logger = pLogger; detector = pDetector; } public void addNewUsagesIfNecessary(TemporaryUsageStorage storage) { if (unsafeUsages == -1) { copyUsages(storage); getUnsafesIfNecessary(); } } public void forceAddNewUsages(TemporaryUsageStorage storage) { //This is a case of 'abort'-functions assert (unsafeUsages == -1); copyUsages(storage); } private void copyUsages(TemporaryUsageStorage storage) { for (SingleIdentifier id : storage.keySet()) { SortedSet<UsageInfo> list = storage.get(id); for (UsageInfo info : list) { if (info.getKeyState() == null) { //Means that it is stored near the abort function } else { add(id, info); } } } } public void add(final SingleIdentifier id, final UsageInfo usage) { UnrefinedUsagePointSet uset; if (falseUnsafes.contains(id)) { return; } if (refinedIds.containsKey(id)) { return; } if (!unrefinedIds.containsKey(id)) { uset = new UnrefinedUsagePointSet(); unrefinedIds.put(id, uset); } else { uset = unrefinedIds.get(id); } usage.setId(id); uset.add(usage); } private void getUnsafesIfNecessary() { if (unsafeUsages == -1) { processedUnsafes.clear(); unsafeUsages = 0; Set<SingleIdentifier> toDelete = new HashSet<>(); for (SingleIdentifier id : unrefinedIds.keySet()) { UnrefinedUsagePointSet tmpList = unrefinedIds.get(id); if (detector.isUnsafe(tmpList)) { unsafeUsages += tmpList.size(); } else { toDelete.add(id); falseUnsafes.add(id); } } for (SingleIdentifier id : toDelete) { removeIdFromCaches(id); } for (SingleIdentifier id : refinedIds.keySet()) { RefinedUsagePointSet tmpList = refinedIds.get(id); unsafeUsages += tmpList.size(); } if (initialSet == null) { assert refinedIds.isEmpty(); initialSet = Sets.newHashSet(unrefinedIds.keySet()); initialUsages = unsafeUsages; } } } private void removeIdFromCaches(SingleIdentifier id) { unrefinedIds.remove(id); processedUnsafes.add(id); } public Set<SingleIdentifier> getAllUnsafes() { getUnsafesIfNecessary(); Set<SingleIdentifier> result = new TreeSet<>(unrefinedIds.keySet()); result.addAll(refinedIds.keySet()); return result; } public Set<SingleIdentifier> getInitialUnsafes() { return initialSet; } public Iterator<SingleIdentifier> getUnsafeIterator() { return getAllUnsafes().iterator(); } public int getUnsafeSize() { getUnsafesIfNecessary(); return unrefinedIds.size() + refinedIds.size(); } public int getTrueUnsafeSize() { return refinedIds.size(); } public UnsafeDetector getUnsafeDetector() { return detector; } public void resetUnrefinedUnsafes() { resetTimer.start(); unsafeUsages = -1; for (UnrefinedUsagePointSet uset : unrefinedIds.values()) { uset.reset(); } logger.log(Level.FINE, "Unsafes are reseted"); resetTimer.stop(); } public void removeState(final UsageStatisticsState pUstate) { for (UnrefinedUsagePointSet uset : unrefinedIds.values()) { uset.remove(pUstate); } logger.log(Level.ALL, "All unsafes related to key state " + pUstate + " were removed from reached set"); } public AbstractUsagePointSet getUsages(SingleIdentifier id) { if (unrefinedIds.containsKey(id)) { return unrefinedIds.get(id); } else { return refinedIds.get(id); } } public void setAsFalseUnsafe(SingleIdentifier id) { falseUnsafes.add(id); removeIdFromCaches(id); } public void setAsRefined(SingleIdentifier id, RefinementResult result) { Preconditions.checkArgument(result.isTrue(), "Result is not true, can not set the set as refined"); setAsRefined(id, result.getTrueRace().getFirst(), result.getTrueRace().getSecond()); } public void setAsRefined(SingleIdentifier id, UsageInfo firstUsage, UsageInfo secondUsage) { refinedIds.put(id, RefinedUsagePointSet.create(firstUsage, secondUsage)); removeIdFromCaches(id); } public void printUsagesStatistics(final PrintStream out) { int allUsages = 0, maxUsage = 0; final int generalUnrefinedSize = unrefinedIds.keySet().size(); for (UnrefinedUsagePointSet uset : unrefinedIds.values()) { allUsages += uset.size(); if (maxUsage < uset.size()) { maxUsage = uset.size(); } } out.println("Total amount of unrefined variables: " + generalUnrefinedSize); out.println("Total amount of unrefined usages: " + allUsages + "(avg. " + (generalUnrefinedSize == 0 ? "0" : (allUsages/generalUnrefinedSize)) + ", max " + maxUsage + ")"); final int generalRefinedSize = refinedIds.keySet().size(); allUsages = 0; for (RefinedUsagePointSet uset : refinedIds.values()) { allUsages += uset.size(); } out.println("Total amount of refined variables: " + generalRefinedSize); out.println("Total amount of refined usages: " + allUsages + "(avg. " + (generalRefinedSize == 0 ? "0" : (allUsages/generalRefinedSize)) + ")"); out.println("Initial amount of unsafes (before refinement): " + initialSet.size()); out.println("Initial amount of usages (before refinement): " + initialUsages); out.println("Initial amount of refined false unsafes: " + falseUnsafes.size()); } @Override public UsageContainer clone() { UsageContainer result = new UsageContainer(Maps.newTreeMap(unrefinedIds), Maps.newTreeMap(refinedIds), Sets.newHashSet(falseUnsafes), logger, detector); return result; } public Set<SingleIdentifier> getProcessedUnsafes() { return processedUnsafes; } }
32.970588
108
0.696811
a8f089275164c0120acc33ffb8deccae3daacc76
1,371
/* * 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.netbeans.api.xml.cookies; // for JavaDoc import org.xml.sax.*; /** * It is structured XML processor {@link CookieMessage} detail. * Its specification is based on {@link SAXParseException}, but can be * explicitly overwriten here. * * @author Petr Kuzel * @since 0.5 */ public abstract class XMLProcessorDetail { public abstract int getColumnNumber(); public abstract int getLineNumber(); public abstract String getPublicId(); public abstract String getSystemId(); public abstract Exception getException(); }
29.804348
70
0.73523
04e4216fa6234ce8a03dc4e297f8891d7ca877c6
1,012
package cn.huse.utils; import java.util.UUID; /** * 文件上传的工具类 * @author jt * */ public class UploadUtils { /** * 传递一个文件名,返回一个唯一的文件名。 */ public static String getUuidFilename(String filename){ // 在Java的API中有一个类UUID可以产生随机的字符串。aa.txt // UUID.randomUUID().toString(); // 获得文件名的扩展名. int idx = filename.lastIndexOf("."); String extetions = filename.substring(idx); return UUID.randomUUID().toString().replace("-", "")+extetions; } /** * 目录分离的算法实现 * @param args */ public static String getRealPath(String uuidFilename){ int code1 = uuidFilename.hashCode(); int d1 = code1 & 0xf; int code2 = code1 >>> 4; int d2 = code2 & 0xf; return "/"+d1+"/"+d2; } public static void main(String[] args) { // System.out.println(UUID.randomUUID().toString().replace("-", "")); /*String s = getUuidFilename("aa.txt"); System.out.println(s);*/ String filename = "185363be735345bf8a971d15332601a3.txt"; int hashCode = filename.hashCode(); System.out.println(hashCode); } }
22
71
0.660079
3f1618ebefcd09a8b9d7d403a1aea4413e2c587b
30,402
package annotationInteraction; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Composite; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; @SuppressWarnings("serial") public class WorksheetViewer extends JPanel{ public static int resize_factor = 6; public static int viewer_width = (int) Math.round(PenPoint.raw_pixel_max_x / resize_factor); public static int viewer_height = (int) Math.round(PenPoint.raw_pixel_max_y / resize_factor); private JPanel stroke_viewer_panel; private JScrollPane stroke_viewer_panel_scroll_pane; private JPanel icons_panel; private JButton next_cluster_iteration, previous_cluster_iteration; private boolean cluster_iterations_visible = false; private Worksheet worksheet; private Poem worksheet_content_in_viewer; private int iteration_count = 0; private List<ClusterIteration> cluster_iterations; private boolean pen_stroke_was_previously_clicked = false; private long pen_stroke_previously_clicked_id = Long.MIN_VALUE; private boolean pen_stroke_is_currently_clicked = false; private long pen_stroke_currently_clicked_id = Long.MIN_VALUE; //private boolean are_pen_strokes_to_highlight = false; private boolean pen_strokes_were_previously_highlighted = false; private List<PenStroke> pen_strokes_previously_highlighted = new ArrayList<PenStroke>(); private List<PenStroke> pen_strokes_currently_highlighted = new ArrayList<PenStroke>(); public WorksheetViewer(Worksheet worksheet){ this.worksheet = worksheet; worksheet_content_in_viewer = poem_content_in_worksheet_viewer(); create_stroke_viewer_panel(); if(!cluster_iterations_visible){ setLayout(new BorderLayout()); add(stroke_viewer_panel_scroll_pane, BorderLayout.CENTER); } else{ create_icons_panel(); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(stroke_viewer_panel_scroll_pane); add(icons_panel); } } private void create_icons_panel(){ icons_panel = new JPanel(); icons_panel.setPreferredSize(new Dimension(viewer_width, 30)); icons_panel.setLayout(new BoxLayout(icons_panel, BoxLayout.LINE_AXIS)); icons_panel.setBackground(Color.WHITE); icons_panel.setBorder(BorderFactory.createMatteBorder(0, 1, 1, 1, Color.GRAY)); next_cluster_iteration = new JButton("next_iteration"); previous_cluster_iteration = new JButton("previous_iteration"); next_cluster_iteration.setEnabled(true); previous_cluster_iteration.setEnabled(false); next_cluster_iteration.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { if(iteration_count < cluster_iterations.size() - 1){ iteration_count++; if(!previous_cluster_iteration.isEnabled()){ previous_cluster_iteration.setEnabled(true); } updateStrokeViewer(); } else{ next_cluster_iteration.setEnabled(false); } } }); previous_cluster_iteration.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { if(iteration_count > 0){ iteration_count--; if(!next_cluster_iteration.isEnabled()){ next_cluster_iteration.setEnabled(true); } updateStrokeViewer(); } else{ previous_cluster_iteration.setEnabled(false); } } }); icons_panel.add(Box.createHorizontalGlue()); icons_panel.add(previous_cluster_iteration); icons_panel.add(Box.createHorizontalGlue()); icons_panel.add(next_cluster_iteration); icons_panel.add(Box.createHorizontalGlue()); } private void create_stroke_viewer_panel(){ stroke_viewer_panel = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; Stroke default_stroke = g2d.getStroke(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, viewer_width, viewer_height); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); //g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); //g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); //g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); display_worksheet_content(g2d); double width = 1.5; Stroke new_stroke = new BasicStroke((float) width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND); g2d.setStroke(new_stroke); Color stroke_color = new Color(70, 62, 237); Color stroke_color_on_click = new Color(255, 0, 0, 200); List<PenStroke> completed_pen_strokes = worksheet.getPenStrokes(); //TODO add code to filter out pen strokes too for(int i = 0; i < completed_pen_strokes.size(); i++){ long pen_stroke_id = completed_pen_strokes.get(i).getStrokeId(); boolean to_be_highlighted = false; if(!pen_strokes_currently_highlighted.isEmpty()){ for(int j = 0; j < pen_strokes_currently_highlighted.size(); j++){ if(pen_stroke_id == pen_strokes_currently_highlighted.get(j).getStrokeId()){ to_be_highlighted = true; break; } } } if(to_be_highlighted){ g2d.setColor(stroke_color_on_click); } else{ g2d.setColor(stroke_color); } if(pen_stroke_currently_clicked_id == pen_stroke_id){ g2d.setColor(stroke_color_on_click); } //g2d.draw(completed_pen_strokes.get(i).getViewerLinearStrokePath()); g2d.draw(completed_pen_strokes.get(i).getViewerSplineStrokePath()); //g2d.setColor(Color.BLACK); //g2d.draw(completed_pen_strokes.get(i).getViewerStrokeBounds()); } if (!worksheet.getIncompletePenStroke().isPenStrokeEmpty()){ g2d.setColor(stroke_color); g2d.draw(worksheet.getIncompletePenStroke().getViewerLinearStrokePath()); } g2d.setStroke(default_stroke); /* if(!completed_pen_strokes.isEmpty()){ ClusterGenerator cluster_generator_last_pen_stroke = worksheet.getLastGeneratedClusters(); if(cluster_generator_last_pen_stroke != null){ List<Cluster> clusters; if(!cluster_iterations_visible){ clusters = cluster_generator_last_pen_stroke.getClusterIterationAtStopIterationIndex().getClusters(); } else{ cluster_iterations = cluster_generator_last_pen_stroke.getClusterIterationsForPenStroke(); clusters = cluster_iterations.get(iteration_count).getClusters(); } for(int i = 0; i < clusters.size(); i++){ g2d.setColor(Color.BLACK); g2d.draw(clusters.get(i).getViewerClusterBounds()); } } }*/ } }; stroke_viewer_panel.setPreferredSize(new Dimension(viewer_width, viewer_height)); stroke_viewer_panel_scroll_pane = new JScrollPane(stroke_viewer_panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); stroke_viewer_panel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me){ Point2D point_on_stroke_viewer = me.getPoint(); if((point_on_stroke_viewer.getX() >= 0 && point_on_stroke_viewer.getX() <= viewer_width) && (point_on_stroke_viewer.getY() >= 0 && point_on_stroke_viewer.getY() <= viewer_height)){ boolean clicked_pen_stroke = false; long pen_stroke_clicked_id = Long.MIN_VALUE; List<PenStroke> completed_pen_strokes = worksheet.getPenStrokes(); for(int i = 0; i < completed_pen_strokes.size(); i++){ PenStroke pen_stroke = completed_pen_strokes.get(i); Rectangle2D stroke_bounds = pen_stroke.getViewerStrokeBounds(); if(stroke_bounds.contains(point_on_stroke_viewer)){ clicked_pen_stroke = true; pen_stroke_clicked_id = pen_stroke.getStrokeId(); pen_stroke_currently_clicked_id = pen_stroke_clicked_id; break; } } if(clicked_pen_stroke){ pen_stroke_is_currently_clicked = true; if(pen_stroke_was_previously_clicked){ if(pen_stroke_clicked_id != pen_stroke_previously_clicked_id){ worksheet.onPenClickOnPenStrokeInViewer(pen_stroke_clicked_id, false); stroke_viewer_panel.repaint(); } } else{ worksheet.onPenClickOnPenStrokeInViewer(pen_stroke_clicked_id, false); stroke_viewer_panel.repaint(); } pen_stroke_was_previously_clicked = true; pen_stroke_previously_clicked_id = pen_stroke_clicked_id; } else{ pen_stroke_currently_clicked_id = Long.MIN_VALUE; pen_stroke_is_currently_clicked = false; if(pen_stroke_was_previously_clicked){ pen_stroke_was_previously_clicked = false; pen_stroke_previously_clicked_id = Long.MIN_VALUE; worksheet.onPenClickOnPenStrokeInViewer(pen_stroke_previously_clicked_id, true); } stroke_viewer_panel.repaint(); } } } }); stroke_viewer_panel.addMouseMotionListener(new MouseAdapter() { public void mouseMoved(MouseEvent me){ Point2D point_on_stroke_viewer = me.getPoint(); if((point_on_stroke_viewer.getX() >= 0 && point_on_stroke_viewer.getX() <= viewer_width) && (point_on_stroke_viewer.getY() >= 0 && point_on_stroke_viewer.getY() <= viewer_height)){ List<PenStroke> completed_pen_strokes = worksheet.getPenStrokes(); boolean found_pen_strokes_to_highlight = false; List<PenStroke> pen_strokes_to_highlight = new ArrayList<PenStroke>(); for(int i = 0; i < completed_pen_strokes.size(); i++){ PenStroke pen_stroke = completed_pen_strokes.get(i); Rectangle2D stroke_bounds = pen_stroke.getViewerStrokeBounds(); if(stroke_bounds.contains(point_on_stroke_viewer)){ //System.out.println("in"); found_pen_strokes_to_highlight = true; pen_strokes_to_highlight = get_pen_strokes_to_highlight(pen_stroke); //System.out.println(pen_strokes_to_highlight.size()); pen_strokes_currently_highlighted = pen_strokes_to_highlight; break; } } if(found_pen_strokes_to_highlight){ if(pen_strokes_were_previously_highlighted){ if(pen_strokes_previously_highlighted.size() == pen_strokes_currently_highlighted.size()){ boolean same_as_previous = true; for(int i = 0; i < pen_strokes_previously_highlighted.size(); i++){ if(pen_strokes_previously_highlighted.get(i).getStrokeId() != pen_strokes_currently_highlighted.get(i).getStrokeId()){ same_as_previous = false; break; } } if(!same_as_previous){ stroke_viewer_panel.repaint(); pen_strokes_were_previously_highlighted = true; pen_strokes_previously_highlighted = pen_strokes_currently_highlighted; } } else{ stroke_viewer_panel.repaint(); pen_strokes_were_previously_highlighted = true; pen_strokes_previously_highlighted = pen_strokes_currently_highlighted; } } else{ stroke_viewer_panel.repaint(); pen_strokes_were_previously_highlighted = true; pen_strokes_previously_highlighted = pen_strokes_currently_highlighted; } } else{ found_pen_strokes_to_highlight = false; pen_strokes_currently_highlighted = new ArrayList<PenStroke>(); if(pen_strokes_were_previously_highlighted){ pen_strokes_were_previously_highlighted = false; pen_strokes_previously_highlighted = new ArrayList<PenStroke>(); } stroke_viewer_panel.repaint(); } } } }); } private List<PenStroke> get_pen_strokes_to_highlight(PenStroke pen_stroke){ List<PenStroke> pen_strokes_to_highlight = new ArrayList<PenStroke>(); long pen_stroke_id = pen_stroke.getStrokeId(); ClusterGenerator cluster_generator_last_pen_stroke = worksheet.getLastGeneratedClusters(); if(cluster_generator_last_pen_stroke != null){ List<Cluster> clusters = cluster_generator_last_pen_stroke.getClusterIterationAtStopIterationIndex().getClusters(); for(int j = 0; j < clusters.size(); j++){ List<PenStroke> pen_strokes_in_cluster = clusters.get(j).getPenStrokes(); for(int k = 0; k < pen_strokes_in_cluster.size(); k++){ if(pen_strokes_in_cluster.get(k).getStrokeId() == pen_stroke_id){ pen_strokes_to_highlight = pen_strokes_in_cluster; break; } } } } return pen_strokes_to_highlight; } private Poem poem_content_in_worksheet_viewer(){ Poem worksheet_content = worksheet.getWorksheetContent(); Stanza poem_header_viewer = stanza_content_in_worksheet_viewer(worksheet_content.getPoemHeader()); List<Stanza> poem_stanzas_in_viewer = new ArrayList<Stanza>(); List<Stanza> poem_stanzas = worksheet_content.getPoemStanzas().getStanzas(); for(int i = 0; i < poem_stanzas.size(); i++){ poem_stanzas_in_viewer.add(stanza_content_in_worksheet_viewer(poem_stanzas.get(i))); } Rectangle2D stanza_in_poem_bounds = worksheet_content.getPoemStanzas().getRawPixelBounds(); Rectangle2D stanza_bounds_viewer = new Rectangle2D.Double(stanza_in_poem_bounds.getX() / resize_factor, stanza_in_poem_bounds.getY() / resize_factor, stanza_in_poem_bounds.getWidth() / resize_factor, stanza_in_poem_bounds.getHeight() / resize_factor); return new Poem(poem_header_viewer, new PoemStanzas(poem_stanzas_in_viewer, stanza_bounds_viewer)); } private Stanza stanza_content_in_worksheet_viewer(Stanza stanza_in_poem){ List<Line> lines_in_stanza_viewer = new ArrayList<Line>(); List<Line> lines_in_stanza = stanza_in_poem.getLines(); for(int i = 0; i < lines_in_stanza.size(); i++){ lines_in_stanza_viewer.add(line_content_in_worksheet_viewer(lines_in_stanza.get(i))); } Rectangle2D stanza_in_poem_bounds = stanza_in_poem.getRawPixelBounds(); Rectangle2D stanza_bounds_viewer = new Rectangle2D.Double(stanza_in_poem_bounds.getX() / resize_factor, stanza_in_poem_bounds.getY() / resize_factor, stanza_in_poem_bounds.getWidth() / resize_factor, stanza_in_poem_bounds.getHeight() / resize_factor); return new Stanza(lines_in_stanza_viewer, stanza_bounds_viewer); } private Line line_content_in_worksheet_viewer(Line line_in_stanza){ List<Word> words_in_line_viewer = new ArrayList<Word>(); List<Word> words_in_line = line_in_stanza.getWords(); for(int i = 0 ; i < words_in_line.size(); i++){ Word word_in_line = words_in_line.get(i); List<Rectangle2D> characters_in_word_bounds = word_in_line.getCharactersRawPixelBounds(); List<Point2D> characters_in_word_locations = word_in_line.getCharactersTextLayoutLocations(); List<String> characters_in_word = word_in_line.getCharacters(); List<Rectangle2D> characters_in_word_bounds_viewer = new ArrayList<Rectangle2D>(); List<Point2D> characters_in_word_locations_viewer = new ArrayList<Point2D>(); for(int j = 0; j < characters_in_word.size(); j++){ Rectangle2D character_in_word_bounds = characters_in_word_bounds.get(j); Rectangle2D character_bounds_viewer = new Rectangle2D.Double(character_in_word_bounds.getX() / resize_factor, character_in_word_bounds.getY() / resize_factor, character_in_word_bounds.getWidth() / resize_factor, character_in_word_bounds.getHeight() / resize_factor); characters_in_word_bounds_viewer.add(character_bounds_viewer); Point2D character_location = characters_in_word_locations.get(j); characters_in_word_locations_viewer.add(new Point2D.Double(character_location.getX() / resize_factor, character_location.getY() / resize_factor)); } Rectangle2D word_in_line_bounds = word_in_line.getRawPixelBounds(); Rectangle2D word_bounds_viewer = new Rectangle2D.Double(word_in_line_bounds.getX() / resize_factor, word_in_line_bounds.getY() / resize_factor, word_in_line_bounds.getWidth() / resize_factor, word_in_line_bounds.getHeight() / resize_factor); words_in_line_viewer.add(new Word(word_in_line.getWord(), word_bounds_viewer, characters_in_word_bounds_viewer, characters_in_word_locations_viewer, word_in_line.getPOS())); } Rectangle2D line_in_stanza_bounds = line_in_stanza.getRawPixelBounds(); Rectangle2D line_bounds_viewer = new Rectangle2D.Double(line_in_stanza_bounds.getX() / resize_factor, line_in_stanza_bounds.getY() / resize_factor, line_in_stanza_bounds.getWidth() / resize_factor, line_in_stanza_bounds.getHeight() / resize_factor); return new Line(line_in_stanza.getLine(), line_bounds_viewer, words_in_line_viewer); } private void display_worksheet_content(Graphics2D g2d){ //get_poem_layout(g2d, g2d.getFontRenderContext()); FontRenderContext fontRenderContext = g2d.getFontRenderContext(); layout_stanza_content(g2d, fontRenderContext, worksheet_content_in_viewer.getPoemHeader()); List<Stanza> poem_stanzas = worksheet_content_in_viewer.getPoemStanzas().getStanzas(); for(int i = 0; i < poem_stanzas.size(); i++){ layout_stanza_content(g2d, fontRenderContext, poem_stanzas.get(i)); } } private void layout_stanza_content(Graphics2D g2d, FontRenderContext fontRenderContext, Stanza stanza_in_poem){ List<Line> lines_in_stanza = stanza_in_poem.getLines(); for(int i = 0; i < lines_in_stanza.size(); i++){ layout_line_content(g2d, fontRenderContext, lines_in_stanza.get(i)); } } private void layout_line_content(Graphics2D g2d, FontRenderContext fontRenderContext, Line line_in_stanza){ Font text_font = CompositeGenerator.text_font; text_font = new Font(text_font.getFontName(), text_font.getStyle(), Math.round(text_font.getSize() / resize_factor)); Color text_color = new Color(10, 10, 10, 250); List<Word> words_in_line = line_in_stanza.getWords(); for(int i = 0 ; i < words_in_line.size(); i++){ Word word_in_line = words_in_line.get(i); List<String> characters_in_word = word_in_line.getCharacters(); //List<Rectangle2D> characters_in_word_bounds = word_in_line.getCharactersRawPixelBounds(); List<Point2D> characters_in_word_locations = word_in_line.getCharactersTextLayoutLocations(); for(int j = 0; j < characters_in_word.size(); j++){ g2d.setColor(text_color); TextLayout layout = new TextLayout(characters_in_word.get(j), text_font, fontRenderContext); Point2D character_location = characters_in_word_locations.get(j); layout.draw(g2d, (float)character_location.getX(), (float)character_location.getY()); //g2d.draw(characters_in_word_bounds.get(j)); } //g2d.draw(word_in_line.getRawPixelBounds()); } } /* private void get_poem_layout(Graphics2D g2d, FontRenderContext fontRenderContext) { int top_offset = Math.round(CompositeGenerator.top_margin_space / resize_factor); Poem worksheet_content = worksheet.getWorksheetContent(); Stanza poem_header = get_stanza_layout(g2d, fontRenderContext, worksheet_content.getPoemHeader(), top_offset); top_offset += poem_header.getRawPixelBounds().getHeight() + Math.round(CompositeGenerator.poem_header_break_space / resize_factor); List<Stanza> poem_stanzas = worksheet_content.getPoemStanzas().getStanzas(); double poem_stanzas_min_x = Double.POSITIVE_INFINITY, poem_stanzas_max_x = Double.NEGATIVE_INFINITY; double poem_stanzas_min_y = Double.POSITIVE_INFINITY, poem_stanzas_max_y = Double.NEGATIVE_INFINITY; for(int i = 0; i < poem_stanzas.size(); i++){ Stanza poem_stanza = get_stanza_layout(g2d, fontRenderContext, poem_stanzas.get(i), top_offset); double poem_stanza_min_x = poem_stanza.getRawPixelBounds().getX(); double poem_stanza_max_x = poem_stanza.getRawPixelBounds().getX() + poem_stanza.getRawPixelBounds().getWidth(); if(i == 0){ poem_stanzas_min_y = poem_stanza.getRawPixelBounds().getY(); poem_stanzas_min_x = poem_stanza_min_x; poem_stanzas_max_x = poem_stanza_max_x; } else{ if(i == poem_stanzas.size() - 1){ poem_stanzas_max_y = poem_stanza.getRawPixelBounds().getY() + poem_stanza.getRawPixelBounds().getHeight(); } if(poem_stanza_min_x < poem_stanzas_min_x){ poem_stanzas_min_x = poem_stanza_min_x; } if(poem_stanza_max_x > poem_stanzas_max_x){ poem_stanzas_max_x = poem_stanza_max_x; } } top_offset += poem_stanza.getRawPixelBounds().getHeight() + Math.round(CompositeGenerator.stanza_break_space / resize_factor); } Rectangle2D poem_stanzas_bounds = new Rectangle2D.Double(poem_stanzas_min_x, poem_stanzas_min_y, poem_stanzas_max_x - poem_stanzas_min_x, poem_stanzas_max_y - poem_stanzas_min_y); //g2d.draw(poem_stanzas_bounds); new Poem(poem_header, new PoemStanzas(poem_stanzas, poem_stanzas_bounds)); } private Stanza get_stanza_layout(Graphics2D g2d, FontRenderContext fontRenderContext, Stanza poem_stanza, int top_offset){ List<Line> lines_in_stanza = poem_stanza.getLines(); double stanza_min_x = Double.POSITIVE_INFINITY, stanza_max_x = Double.NEGATIVE_INFINITY; double stanza_min_y = Double.POSITIVE_INFINITY, stanza_max_y = Double.NEGATIVE_INFINITY; for(int i = 0; i < lines_in_stanza.size(); i++){ Line line_in_stanza = get_line_layout(g2d, fontRenderContext, lines_in_stanza.get(i), top_offset); double line_min_x = line_in_stanza.getRawPixelBounds().getX(); double line_max_x = line_in_stanza.getRawPixelBounds().getWidth() + line_in_stanza.getRawPixelBounds().getX(); if(i == 0){ stanza_min_y = line_in_stanza.getRawPixelBounds().getY(); stanza_min_x = line_min_x; stanza_max_x = line_max_x; } else{ if(i == lines_in_stanza.size() - 1){ stanza_max_y = line_in_stanza.getRawPixelBounds().getY() + line_in_stanza.getRawPixelBounds().getHeight(); } if(line_min_x < stanza_min_x){ stanza_min_x = line_min_x; } if(line_max_x > stanza_max_x){ stanza_max_x = line_max_x; } } top_offset += line_in_stanza.getRawPixelBounds().getHeight() + Math.round(CompositeGenerator.line_break_space / resize_factor); } Rectangle2D stanza_bounds = new Rectangle2D.Double(stanza_min_x, stanza_min_y, stanza_max_x - stanza_min_x, stanza_max_y - stanza_min_y); //g2d.draw(stanza_bounds); return new Stanza(poem_stanza.getLines(), stanza_bounds); } private Line get_line_layout(Graphics2D g2d, FontRenderContext fontRenderContext, Line poem_line, int top_offset){ List<Word> words_in_line = poem_line.getWords(); int character_left_offset = Math.round(CompositeGenerator.left_margin_space / resize_factor); Font text_font = CompositeGenerator.text_font; text_font = new Font(text_font.getFontName(), text_font.getStyle(), Math.round(text_font.getSize() / resize_factor)); Color text_color = new Color(10, 10, 10, 250); double line_bounds_min_x = Double.POSITIVE_INFINITY, line_bounds_max_x = Double.NEGATIVE_INFINITY, line_bounds_min_y = Double.POSITIVE_INFINITY, line_bounds_max_y = Double.NEGATIVE_INFINITY; for(int i = 0; i < words_in_line.size(); i++){ Word word_in_line = words_in_line.get(i); List<String> characters_in_word = get_characters_in_word(word_in_line.getWord()); double word_bounds_min_x = Double.POSITIVE_INFINITY, word_bounds_max_x = Double.NEGATIVE_INFINITY, word_bounds_min_y = Double.POSITIVE_INFINITY, word_bounds_max_y = Double.NEGATIVE_INFINITY; for(int j = 0; j < characters_in_word.size(); j++){ g2d.setColor(text_color); TextLayout layout = new TextLayout(characters_in_word.get(j), text_font, fontRenderContext); layout.draw(g2d, character_left_offset, top_offset); g2d.setColor(new Color(255, 0, 0, 230)); Rectangle2D layout_bounds = layout.getBounds(); Rectangle2D char_bounds = new Rectangle2D.Double(character_left_offset + layout_bounds.getX(), top_offset + layout_bounds.getY(), layout_bounds.getWidth(), layout_bounds.getHeight()); //g2d.draw(char_bounds); double character_min_y = top_offset + layout_bounds.getY(); double character_max_y = top_offset + layout_bounds.getY() + layout_bounds.getHeight(); if(j == 0){ word_bounds_min_x = character_left_offset + layout_bounds.getX(); word_bounds_max_x = character_left_offset + layout_bounds.getX() + layout_bounds.getWidth(); word_bounds_min_y = character_min_y; word_bounds_max_y = character_max_y; } else{ if(j == characters_in_word.size() - 1){ word_bounds_max_x = character_left_offset + layout_bounds.getX() + layout_bounds.getWidth(); } if(character_min_y < word_bounds_min_y){ word_bounds_min_y = character_min_y; } if(character_max_y > word_bounds_max_y){ word_bounds_max_y = character_max_y; } } character_left_offset += layout_bounds.getX() + layout_bounds.getWidth(); } Rectangle2D word_bounds = new Rectangle2D.Double(word_bounds_min_x, word_bounds_min_y, word_bounds_max_x - word_bounds_min_x, word_bounds_max_y - word_bounds_min_y); //g2d.draw(word_bounds); if(i == 0){ line_bounds_min_x = word_bounds_min_x; line_bounds_max_x = word_bounds_max_x; line_bounds_min_y = word_bounds_min_y; line_bounds_max_y = word_bounds_max_y; } else{ if(i == words_in_line.size() - 1){ line_bounds_max_x = word_bounds_max_x; } if(word_bounds_min_y < line_bounds_min_y){ line_bounds_min_y = word_bounds_min_y; } if(word_bounds_max_y > line_bounds_max_y){ line_bounds_max_y = word_bounds_max_y; } } } Rectangle2D line_bounds = new Rectangle2D.Double(line_bounds_min_x, line_bounds_min_y, line_bounds_max_x - line_bounds_min_x, line_bounds_max_y - line_bounds_min_y); //g2d.draw(line_bounds); return new Line(poem_line.getLine(), line_bounds, words_in_line); } private List<String> get_characters_in_word(String word){ List<String> characters_in_word = new ArrayList<String>(); String word_trimmed = word.trim(); int leading_space_in_word = word.length() - word_trimmed.length(); for(int i = 0; i < word_trimmed.length(); i++){ String char_in_word = (i == 0) ? (leading_space_in_word > 0 ? (get_leading_whitespace(leading_space_in_word) + String.valueOf(word_trimmed.charAt(i))) : String.valueOf(word_trimmed.charAt(i))) : String.valueOf(word_trimmed.charAt(i)); characters_in_word.add(char_in_word); } return characters_in_word; } private String get_leading_whitespace(int no_of_leading_spaces){ String leading_space = ""; for(int i = 0; i < no_of_leading_spaces; i++){ leading_space += " "; } return leading_space; }*/ public void updateStrokeViewer(){ stroke_viewer_panel.repaint(); } public boolean isPenStrokeClicked(){ return pen_stroke_is_currently_clicked; } }
33.22623
271
0.681205
4e5ad148f5bde430a2a66a84e9560a24f92d3711
1,840
package com.fjx.mg.setting.companycer; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import com.fjx.mg.R; import com.fjx.mg.ToolBarManager; import com.library.common.base.BaseMvpActivity; import com.library.common.utils.CommonImageLoader; import com.library.repository.models.CompanyCerModel; import butterknife.BindView; import butterknife.ButterKnife; public class CompanyCerInfoActivity extends BaseMvpActivity<CompanyCerPresenter> implements CompanyCerContract.View { @BindView(R.id.tvRealName) TextView tvRealName; @BindView(R.id.tvIdCard) TextView tvIdCard; @BindView(R.id.ivImage1) ImageView ivImage1; @BindView(R.id.ivImage2) ImageView ivImage2; @Override protected CompanyCerPresenter createPresenter() { return new CompanyCerPresenter(this); } public static Intent newInstance(Context context) { Intent intent = new Intent(context, CompanyCerInfoActivity.class); return intent; } @Override protected int layoutId() { return R.layout.ac_certification_com_info; } @Override protected void initView() { ToolBarManager.with(this).setTitle(getString(R.string.Enterprise_Certification)); mPresenter.companyAuditInfo(); } @Override public void uploadImageSucces(String key, String imgeUrl) { } @Override public void commitSuccess() { } @Override public void showCompanyCerInfo(CompanyCerModel model) { tvRealName.setText(model.getCompanyName()); tvIdCard.setText(model.getBusinessLicense()); CommonImageLoader.load(model.getBusinessImg()).into(ivImage1); CommonImageLoader.load(model.getEmployImg()).into(ivImage2); } }
25.915493
117
0.730978
eb741aaaa11ca7eabe49ad1ff1b62e71bcde1751
768
package io.opentracing.contrib.specialagent.rule.dubbo26; import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.ReferenceConfig; import io.opentracing.contrib.specialagent.rule.GreeterService; public class MockClient { private ReferenceConfig<GreeterService> client; public MockClient(String ip, int port) { client = new ReferenceConfig<>(); client.setApplication(new ApplicationConfig("test")); client.setInterface(GreeterService.class); client.setUrl("dubbo://" + ip + ":" + port + "?scope=remote"); client.setScope("local"); client.setInjvm(true); } public GreeterService get() { return client.get(); } void stop() { client.destroy(); } }
28.444444
70
0.678385
25a121067c33f5b182e0c7b9cc015b885c815cb1
5,466
package com.mindforger.coachingnotebook.client.ui.social; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.mindforger.coachingnotebook.client.Ria; import com.mindforger.coachingnotebook.client.RiaContext; import com.mindforger.coachingnotebook.client.RiaMessages; import com.mindforger.coachingnotebook.client.RiaUtilities; import com.mindforger.coachingnotebook.client.ui.social.ConnectionActionPanel.ConnectionActionPanelMode; import com.mindforger.coachingnotebook.shared.beans.UserBean; public class ConnectionPanel extends VerticalPanel { public static enum ConnectionPanelMode { VIEW, TO_BE_ACCEPTED, TO_BE_ADDED, PENDING, CONFIRMED, }; private Ria ria; private UserProfilePanel userProfilePanel; private ConnectionsPanel connectionsPanel; private RiaMessages i18n; public ConnectionPanel(final UserBean user, ConnectionPanelMode mode, RiaContext ctx) { this.userProfilePanel=ctx.getUserProfilePanel(); this.ria=ctx.getRia(); i18n = ctx.getI18n(); this.connectionsPanel=ctx.getConnectionsPanel(); setStyleName("mf-connectionsProfilePanel"); HTML html, photoHtml; // gravatar String htmlString="<img border='0' src='"+RiaUtilities.getGravatatarUrl(user)+"?s=75&d=identicon'>"; photoHtml = new HTML(htmlString); photoHtml.setStyleName("mf-connectionsProfilePhoto"); if(!mode.equals(ConnectionPanelMode.TO_BE_ADDED)) { photoHtml.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { userProfilePanel.refreshProfile(user.getUserId()); ria.showUserProfile(); } }); } add(photoHtml); // link to profile String nickname=user.getNickname(); if(!mode.equals(ConnectionPanelMode.CONFIRMED)) { nickname=RiaUtilities.getPrivacySafeNickname(user.getNickname()); } if(mode.equals(ConnectionPanelMode.CONFIRMED) || mode.equals(ConnectionPanelMode.VIEW)) { UserProfileButton button=new UserProfileButton(nickname, user.getUserId(), "mf-showUserProfileConfirmed", ctx); add(button); } else { html = new HTML(nickname); html.setStyleName("mf-addFriendName"); add(html); } // role if(mode.equals(ConnectionPanelMode.CONFIRMED)) { html = new HTML(user.getRole()); html.setStyleName("mf-connectionsProfilePanelRole"); add(html); } // status if(mode.equals(ConnectionPanelMode.PENDING)) { html=new HTML(i18n.waitingForApproval()); html.setStyleName("mf-pendingFriend"); html.setTitle(i18n.yourFriendRequestWasNotAcceptedYet()); add(html); } else { if(mode.equals(ConnectionPanelMode.TO_BE_ACCEPTED)) { html=new HTML(i18n.connectionRequest()); html.setTitle(connectionRequestFromOtherUserIsWaiting()); html.setStyleName("mf-pendingFriend"); add(html); } } // add as/revoke button if(mode.equals(ConnectionPanelMode.TO_BE_ADDED)) { final ClickHandler openConnectionActionHandler = new ClickHandler() { public void onClick(ClickEvent event) { connectionsPanel.getConnectionActionsPanel().refresh( user, ConnectionActionPanelMode.ADD_AS_CONNECTION); connectionsPanel.showConnectionActionPanel(); } }; photoHtml.addClickHandler(openConnectionActionHandler); Button openConnectionActions=new Button(i18n.add(), openConnectionActionHandler); openConnectionActions.setStyleName("mf-button"); add(openConnectionActions); } else { if(mode.equals(ConnectionPanelMode.TO_BE_ACCEPTED)) { final ClickHandler openConnectionActionHandler = new ClickHandler() { public void onClick(ClickEvent event) { connectionsPanel.getConnectionActionsPanel().refresh( user, ConnectionActionPanelMode.ACCEPT_CONNECTION); // TODO another show for connections listing connectionsPanel.showConnectionActionPanel(); } }; photoHtml.addClickHandler(openConnectionActionHandler); HorizontalPanel acceptRejectPanel=new HorizontalPanel(); Button openConnectionActions=new Button(i18n.accept(), openConnectionActionHandler); openConnectionActions.setStyleName("mf-button"); acceptRejectPanel.add(openConnectionActions); Button rejectButton=new Button(i18n.reject(), openConnectionActionHandler); rejectButton.setStyleName("mf-button"); acceptRejectPanel.add(rejectButton); add(acceptRejectPanel); } else { if(mode.equals(ConnectionPanelMode.CONFIRMED)) { RevokeFriendButton button=new RevokeFriendButton(ctx); button.setTitle(i18n.revoke()); button.setText(i18n.revokeTheConnection()); button.setFriendId(user.getUserId()); button.init(); add(button); } else { if(mode.equals(ConnectionPanelMode.PENDING)) { RevokeFriendButton button=new RevokeFriendButton(ctx); button.setTitle(i18n.cancel()); button.setText(i18n.cancelYourPendingRequest()); button.setFriendId(user.getUserId()); button.init(); add(button); } } } } } private String connectionRequestFromOtherUserIsWaiting() { // TODO Auto-generated method stub return null; } }
36.198675
115
0.726674