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
f48c1b2dadfcd329a92fe615632a7e6adfe896d9
5,823
package com.simonalong.neo.core; import com.simonalong.neo.Columns; import com.simonalong.neo.NeoMap; import com.simonalong.neo.express.SearchQuery; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; /** * @author shizi * @since 2020/6/11 3:02 PM */ public interface CommandAsync extends Async { CompletableFuture<NeoMap> insertAsync(String tableName, NeoMap dataMap, Executor executor); CompletableFuture<NeoMap> insertAsync(String tableName, NeoMap dataMap); <T> CompletableFuture<T> insertAsync(String tableName, T object, Executor executor); <T> CompletableFuture<T> insertAsync(String tableName, T object); CompletableFuture<NeoMap> insertOfUnExistAsync(String tableName, NeoMap dataMap, Executor executor, String... searchColumnKey); CompletableFuture<NeoMap> insertOfUnExistAsync(String tableName, NeoMap dataMap, String... searchColumnKey); <T> CompletableFuture<T> insertOfUnExistAsync(String tableName, T object, Executor executor, String... searchColumnKey); <T> CompletableFuture<T> insertOfUnExistAsync(String tableName, T object, String... searchColumnKey); CompletableFuture<NeoMap> saveAsync(String tableName, NeoMap dataMap, Executor executor, String... searchColumnKey); CompletableFuture<NeoMap> saveAsync(String tableName, NeoMap dataMap, String... searchColumnKey); <T> CompletableFuture<T> saveAsync(String tableName, T object, Executor executor, String... searchColumnKey); <T> CompletableFuture<T> saveAsync(String tableName, T object, String... searchColumnKey); CompletableFuture<Integer> deleteAsync(String tableName, NeoMap dataMap, Executor executor); CompletableFuture<Integer> deleteAsync(String tableName, NeoMap dataMap); CompletableFuture<Integer> deleteAsync(String tableName, SearchQuery searchQuery, Executor executor); CompletableFuture<Integer> deleteAsync(String tableName, SearchQuery searchQuery); <T> CompletableFuture<Integer> deleteAsync(String tableName, T object, Executor executor); <T> CompletableFuture<Integer> deleteAsync(String tableName, T object); CompletableFuture<Integer> deleteAsync(String tableName, Number id, Executor executor); CompletableFuture<Integer> deleteAsync(String tableName, Number id); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, NeoMap searchMap, Executor executor); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, NeoMap searchMap); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, NeoMap searchMap, Executor executor); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, NeoMap searchMap); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, T searchEntity, Executor executor); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, T searchEntity); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, Number id, Executor executor); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, Number id); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, Number id, Executor executor); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, Number id); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, Columns columns, Executor executor); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, Columns columns); <T> CompletableFuture<T> updateAsync(String tableName, T entity, Columns columns, Executor executor); <T> CompletableFuture<T> updateAsync(String tableName, T entity, Columns columns); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, Executor executor); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap); <T> CompletableFuture<T> updateAsync(String tableName, T entity, Executor executor); <T> CompletableFuture<T> updateAsync(String tableName, T entity); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, SearchQuery searchQuery, Executor executor); CompletableFuture<NeoMap> updateAsync(String tableName, NeoMap dataMap, SearchQuery searchQuery); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, SearchQuery searchQuery, Executor executor); <T> CompletableFuture<T> updateAsync(String tableName, T setEntity, SearchQuery searchQuery); CompletableFuture<Integer> batchInsertAsync(String tableName, List<NeoMap> dataMapList); CompletableFuture<Integer> batchInsertAsync(String tableName, List<NeoMap> dataMapList, Executor executor); <T> CompletableFuture<Integer> batchInsertEntityAsync(String tableName, List<T> dataList); <T> CompletableFuture<Integer> batchInsertEntityAsync(String tableName, List<T> dataList, Executor executor); CompletableFuture<Integer> batchUpdateAsync(String tableName, List<NeoMap> dataList); CompletableFuture<Integer> batchUpdateAsync(String tableName, List<NeoMap> dataList, Executor executor); CompletableFuture<Integer> batchUpdateAsync(String tableName, List<NeoMap> dataList, Columns columns); CompletableFuture<Integer> batchUpdateAsync(String tableName, List<NeoMap> dataList, Columns columns, Executor executor); <T> CompletableFuture<Integer> batchUpdateEntityAsync(String tableName, List<T> dataList); <T> CompletableFuture<Integer> batchUpdateEntityAsync(String tableName, List<T> dataList, Executor executor); <T> CompletableFuture<Integer> batchUpdateEntityAsync(String tableName, List<T> dataList, Columns columns); <T> CompletableFuture<Integer> batchUpdateEntityAsync(String tableName, List<T> dataList, Columns columns, Executor executor); }
44.113636
131
0.785849
ef771ce6aabd2a6d161a0138a3e5a81bfff35038
751
package org.sedgewick.algorithms.part_one.week_three.question_five; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SelectionInTwoSortedArraysWithDuplicatesTest { @Test void select() { int[] nums1 = new int[]{1, 1, 2, 3, 3}; int[] nums2 = new int[]{0, 2, 2, 3, 4}; int result = new SelectionInTwoSortedArraysWithDuplicates().select(nums1, nums2, 4); assertEquals(3, result); } @Test void selectTwo() { int[] nums1 = new int[]{5, 5, 7, 7, 9}; int[] nums2 = new int[]{9, 11, 11, 11, 11, 11}; int result = new SelectionInTwoSortedArraysWithDuplicates().select(nums1, nums2, 4); assertEquals(11, result); } }
31.291667
92
0.637816
2ce71ca5d2d26bfe5ad7546df8ef36cef55b6a12
874
package com.likya.tlossw.model; public class MetaDataType { public final static int GLOBAL = 1; public final static int LOCAL = 2; private String documentId; private String documentType; private int scope = GLOBAL; public MetaDataType() { } public MetaDataType(String documentId, String documentType, int scope) { this.documentId = documentId; this.documentType = documentType; this.scope = scope; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } public String getDocumentType() { return documentType; } public void setDocumentType(String documentType) { this.documentType = documentType; } public int getScope() { return scope; } public void setScope(int scope) { this.scope = scope; } }
18.595745
74
0.689931
857a2856d94148e37f5bad45d73256d0c17f0050
923
package dev.vality.cm.converter; import dev.vality.cm.model.LegalAgreementModel; import dev.vality.damsel.domain.LegalAgreement; import dev.vality.geck.common.util.TypeUtil; import org.springframework.stereotype.Component; @Component public class LegalAgreementToLegalAgreementModelConverter implements ClaimConverter<LegalAgreement, LegalAgreementModel> { @Override public LegalAgreementModel convert(LegalAgreement legalAgreement) { LegalAgreementModel legalAgreementModel = new LegalAgreementModel(); legalAgreementModel.setLegalAgreementId(legalAgreement.getLegalAgreementId()); legalAgreementModel.setSignedAt(TypeUtil.stringToInstant(legalAgreement.getSignedAt())); if (legalAgreement.isSetValidUntil()) { legalAgreementModel.setValidUntil(TypeUtil.stringToInstant(legalAgreement.getValidUntil())); } return legalAgreementModel; } }
38.458333
104
0.785482
e8af8548d9677d44d978b91d85783e4b84f79d55
1,610
package org.mutabilitydetector.benchmarks.settermethod; /* * #%L * MutabilityDetector * %% * Copyright (C) 2008 - 2014 Graham Allan * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @SuppressWarnings("unused") public class ImmutableButSetsPrivateFieldOfInstanceOfSelf { private Object myField = null; private int primitiveField = 0; private ImmutableButSetsPrivateFieldOfInstanceOfSelf fieldOfSelfType = null; public ImmutableButSetsPrivateFieldOfInstanceOfSelf setPrivateFieldOnInstanceOfSelf() { ImmutableButSetsPrivateFieldOfInstanceOfSelf i = new ImmutableButSetsPrivateFieldOfInstanceOfSelf(); this.hashCode(); i.myField = new Object(); this.hashCode(); i.primitiveField++; return i; } } class MutableBySettingFieldOnThisInstanceAndOtherInstance { @SuppressWarnings("unused") private int myField = 0; public void setMyField(int newMyField, MutableBySettingFieldOnThisInstanceAndOtherInstance otherInstance) { this.myField = newMyField; otherInstance.myField = 42; } }
31.568627
111
0.734783
3ca38111ac42242bb88b6010faf804f0d9b7c762
7,360
package YMY.dto; import YMY.entities.Customer; import YMY.entities.User; import YMY.repositories.CompanyRepository; import YMY.repositories.CustomerRepository; import YMY.services.CacheService; import YMY.services.UserService; import YMY.utils.Check; import YMY.utils.Util; import org.springframework.stereotype.Service; import org.springframework.validation.BindingResult; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; @Service public class CustomerDto { final CompanyRepository companyRepository; final CustomerRepository customerRepository; final UserService userService; final CacheService cacheService; public CustomerDto(CompanyRepository companyRepository, CustomerRepository customerRepository, UserService userService, CacheService cacheService) { this.companyRepository = companyRepository; this.customerRepository = customerRepository; this.userService = userService; this.cacheService = cacheService; } //Save or Update customer information public Map<Check,Object> customerSaveOrUpdate(Customer customer, BindingResult bindingResult){ Map<Check,Object> hm = new LinkedHashMap<>(); User user = userService.userInfo(); try { if(!bindingResult.hasErrors()){ if(user.getId() != null){ customer.setUserId(user.getId()); customer.setStatus(true); customer.setDate(Util.generateDate()); customerRepository.saveAndFlush(customer); hm.put(Check.status,true); hm.put(Check.message,"Müşteri kayıt işlemi başarıyla tamamlandı!"); hm.put(Check.result,customer); cacheService.cacheRefresh("customerList"); //Refresh cache cacheService.cacheRefresh("invoiceAddListCustomersBySelectedCompany"); //Refresh cache } }else{ hm.put(Check.status,false); hm.put(Check.message,"Müşteri kayıt işlemi sırasında bir hata oluştu!"); hm.put(Check.error,bindingResult.getAllErrors()); } } catch (Exception e) { String error = "İşlem sırasında bir hata oluştu!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error + " " + e,Customer.class); } return hm; } //List of customers by status public Map<Check,Object> listCustomer(){ Map<Check,Object> hm = new LinkedHashMap<>(); User user = userService.userInfo(); try { if(user.getId() != null ){ hm.put(Check.status,true); hm.put(Check.message,"Müşteri listeleme işlemi başarılı!"); hm.put(Check.result,customerRepository.findByStatusAndUserIdOrderByIdAsc(true, user.getId())); }else{ String error = "Lütfen hesabınıza giriş yapıp tekrar deneyiniz!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error, Customer.class); } } catch (Exception e) { String error = "Listeleme işlemi sırasında bir hata oluştu!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error + " " + e,Customer.class); } return hm; } //List of customer by selected company public Map<Check,Object> listCustomersBySelectedCompany(String stId){ Map<Check,Object> hm = new LinkedHashMap<>(); User user = userService.userInfo(); try { if(user.getId() != null ){ int id = Integer.parseInt(stId); hm.put(Check.status,true); hm.put(Check.message,"Seçilen firmaya ait müşteri sıralama işlemi başarılı!"); hm.put(Check.result,customerRepository.findByStatusAndUserIdAndCompany_Id(true, user.getId(),id)); }else{ String error = "Lütfen hesabınıza giriş yapıp tekrar deneyiniz!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error, Customer.class); } } catch (NumberFormatException e) { String error = "Seçilen firmaya ait müşteri sıralama işlemi sırasında bir hata oluştu!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error + " " + e,Customer.class); } return hm; } //Delete Customer public Map<Check,Object> deleteCustomer(String stId){ Map<Check,Object> hm = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); Optional<Customer> optionalCustomer = customerRepository.findById(id); if(optionalCustomer.isPresent()){ Customer customer = optionalCustomer.get(); customer.setStatus(false); customerRepository.saveAndFlush(customer); hm.put(Check.status,true); hm.put(Check.message,"Müşteri silme işlemi başarıyla gerçekleştirildi!"); }else{ hm.put(Check.status,false); hm.put(Check.message,"Silinmek istenen müşteri bulunamadı!"); } } catch (NumberFormatException e) { String error = "Silme işlemi sırasında bir hata oluştu!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error + " " + e,Customer.class); } return hm; } //Details by selected customer public Map<Check,Object> detailCustomer(String stId){ Map<Check,Object> hm = new LinkedHashMap<>(); try { int id = Integer.parseInt(stId); hm.put(Check.status,true); hm.put(Check.message,"Müşteri detayları başarılı bir şekilde getirildi!"); hm.put(Check.result,customerRepository.findById(id).get()); } catch (Exception e) { String error = "Müşteri detayları getirilirken bir hata oluştu!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error + " " + e, Customer.class); } return hm; } //Listing all companies public Map<Check,Object> listAllCompany(){ Map<Check,Object> hm = new LinkedHashMap<>(); User user = userService.userInfo(); try { if(user.getId() != null){ hm.put(Check.status,true); hm.put(Check.message,"Firmalar başarılı bir şekilde listelendi!"); hm.put(Check.result,companyRepository.findByStatusEqualsAndUserIdEqualsOrderByIdAsc(true,user.getId())); }else{ String error = "Lütfen hesabınıza giriş yapıp tekrar deneyiniz!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error, Customer.class); } } catch (Exception e) { String error = "Firmalar listelenirken bir hata oluştu!"; hm.put(Check.status,false); hm.put(Check.message,error); Util.logger(error + " " + e, Customer.class); } return hm; } }
41.117318
152
0.597826
32c1892e9987d4d2fb27b0780b404a7e99761fed
269
package pes6j.datablocks; public class MessageBlockZero extends MessageBlock { static final byte[] MSG_DATA = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; public MessageBlockZero(int qId) { super(); header.setQuery(qId); setData(MSG_DATA); } }
20.692308
72
0.698885
bf79531e159a967091c7ac7c7b83220d7d6a5cb9
460
package org.esupportail.opi.web.utils.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class Coerce2zero implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent event) { System.setProperty("org.apache.el.parser.COERCE_TO_ZERO", "false"); } @Override public void contextDestroyed(ServletContextEvent event) { // NOOP } }
25.555556
75
0.752174
2926834e15771e39ff27d1ca8ba97c2b1b2a4f93
787
import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.CqlSession; import java.util.UUID; public class Main{ public static void main(String args[]){ try(CqlSession session = CqlSession.builder().build()){ InventoryMapper inventoryMapper = new InventoryMapperBuilder(session).build(); ProductDao dao = inventoryMapper.productDao(CqlIdentifier.fromCql("inventory")); UUID id = UUID.randomUUID(); Product newProduct = new Product(id, "Mechanical keyboard"); dao.save(newProduct); System.out.println("product created: " + newProduct); Product p = dao.findById(id); System.out.println("product found: " + p); dao.delete(p); System.out.println("product deleted: " + p); } } }
31.48
86
0.689962
215715ca1d98ccb7a6ff219acb4d17e5208ab28c
622
package com.sampullara.cli; import junit.framework.*; public class EnumTest extends TestCase { public void testCanUseAnEnumValue() { CommandCLI cli = new CommandCLI(); String[] args = new String[] {"-command", "START"}; Args.parse(cli, args); assertNotNull("Commands enum value not built", cli.getCommand()); assertEquals("retrieved command value is not Commands.START", Commands.START, cli.getCommand()); } public static class CommandCLI { @Argument() private Commands command; public Commands getCommand() { return command; } } public static enum Commands { START, STOP, PAUSE; } }
23.037037
98
0.709003
a389cb92727b5097f21a3e5b33c157c6f4ff2318
389
package com.rahul.udacity.cs2.ui.home; import com.rahul.udacity.cs2.ui.common.CommonView; /** * Created by rahulgupta on 11/11/16. */ public interface HomeView extends CommonView { /** * Called when an item in the navigation drawer is selected. * * @param navDrawerEnum Enum selected */ void onNavigationDrawerItemSelected(NavDrawerEnum navDrawerEnum); }
21.611111
69
0.712082
a18d1a7cf070a81d7dc1060e27252b41214dc1e7
2,606
package bob.eve.walle.ui.activity; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import bob.eve.walle.R; import bob.eve.walle.pojo.QunLiao; public class QunLiaoMainActivity extends AppCompatActivity { private EditText text; private Button bt; private RecyclerView recy; public List list; private lianjie lj; public Handler hand = new Handler() {//用于在子线程更新UI,收到信息和连接服务器成功时用到 @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: Toast.makeText(getApplicationContext(), "连接服务器成功", Toast.LENGTH_SHORT).show(); break; case 2: recy.setAdapter(new adapter1(list));//设置适配器 recy.scrollToPosition(list.size() - 1);//将屏幕移动到RecyclerView的底部 break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qun_liao_main); this.setTitle("群聊"); list = new ArrayList<xx>(); text = findViewById(R.id.text); bt = findViewById(R.id.bt); recy = findViewById(R.id.recy); LinearLayoutManager lin = new LinearLayoutManager(this); recy.setLayoutManager(lin); lj = new lianjie(this); bt.setOnClickListener(new View.OnClickListener() {//给发送按钮设置监听事件 @Override public void onClick(View v) { String s = text.getText().toString(); if (s == null || s.equals("")) { Toast.makeText(getApplicationContext(), "发送消息不能为空", Toast.LENGTH_SHORT).show(); } else { list.add(new xx(s, R.mipmap.gaara, false)); //new一个xx类,第一个参数的信息的内容,第二个参数是头像的图片id,第三个参数表示左右 //true为左边,false为右 lj.fa(new QunLiao(1,s,9).toString());//发送消息 recy.setAdapter(new adapter1(list));//再把list添加到适配器 text.setText(null); recy.scrollToPosition(list.size() - 1);//将屏幕移动到RecyclerView的底部 } } }); } }
35.69863
99
0.602456
35e3fac8b555a8152c30c61a271bc04ef4b66a3a
3,220
package ee.ristoseene.raytracer.eyebased.shading.common.compiled; import ee.ristoseene.raytracer.eyebased.core.compilation.CompilationCache; import ee.ristoseene.raytracer.eyebased.core.configuration.SampleValueFactory; import ee.ristoseene.raytracer.eyebased.core.constants.Vectors; import ee.ristoseene.raytracer.eyebased.core.raytracing.BounceContext; import ee.ristoseene.raytracer.eyebased.core.raytracing.SampleValue; import ee.ristoseene.raytracer.eyebased.core.raytracing.ShadingConfiguration; import ee.ristoseene.raytracer.eyebased.core.raytracing.ShadingContext; import ee.ristoseene.raytracer.eyebased.core.raytracing.ShadingPipeline; import ee.ristoseene.raytracer.eyebased.core.raytracing.TypedAttribute; import ee.ristoseene.raytracer.eyebased.shading.configuration.BounceSampleResolver; import ee.ristoseene.raytracer.eyebased.shading.configuration.BounceShadingFilter; import ee.ristoseene.raytracer.eyebased.shading.providers.ValueProvider; import ee.ristoseene.vecmath.Vector3; import java.util.Objects; import java.util.Optional; /** * Instances of this class rely on {@link BounceShadingFilter} for deciding whether to bounce rays further or consider * the surface as black. * * Instances of this class rely on {@link BounceSampleResolver} for resolving the bounce sampling result into the * {@link SampleValue} emitted by the current surface. * * Instances of this class rely on {@link SampleValueFactory} for producing shading results. * * @see BounceShadingFilter * @see BounceShadingFilter#KEY * * @see BounceSampleResolver * @see BounceSampleResolver#KEY * * @see SampleValueFactory * @see SampleValueFactory#KEY * * @see ShadingContext#getAttributeValue(TypedAttribute) */ public abstract class AbstractColorMultiplyingBounceShadingPipeline implements ShadingPipeline, ShadingConfiguration { protected final ValueProvider<Vector3.Accessible> colorMultiplierProvider; protected AbstractColorMultiplyingBounceShadingPipeline(final ValueProvider<Vector3.Accessible> colorMultiplierProvider) { this.colorMultiplierProvider = Objects.requireNonNull(colorMultiplierProvider, "Color multiplier not provided"); } protected abstract SampleValue shadeBouncing(final ShadingContext shadingContext, final BounceContext bounceContext); @Override public SampleValue shade(final ShadingContext shadingContext, final BounceContext bounceContext) { final Vector3.Accessible colorMultiplier = colorMultiplierProvider.getValue(shadingContext); if (shadingContext.getAttributeValue(BounceShadingFilter.KEY).test(bounceContext, colorMultiplier)) { final SampleValue bounceShadingResult = shadeBouncing(shadingContext, bounceContext); return shadingContext.getAttributeValue(BounceSampleResolver.KEY) .resolveBounceSample(shadingContext, bounceShadingResult, colorMultiplier); } else { return shadingContext.getAttributeValue(SampleValueFactory.KEY) .create(shadingContext, Vectors.VECTOR3_ZERO_ZERO_ZERO); } } @Override public ShadingPipeline compile(final Optional<CompilationCache> compilationCache) { return this; } }
46
126
0.802174
cac9ff1ea19e1221ea2b3de0576096350e39f4ff
2,259
/** * Copyright (C) 2006 Dragos Balan ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.reportengine.config; import java.text.Format; import net.sf.reportengine.config.DefaultGroupColumn.Builder; import net.sf.reportengine.core.algorithm.NewRowEvent; /** * * @author dragos balan (dragos dot balan at gmail dot com) * @since 0.4 */ public class DefaultPivotHeaderRow extends AbstractPivotHeaderRow { /** * */ private int inputColumnIndex; /** * * @param inputColumnIndex */ public DefaultPivotHeaderRow(int inputColumnIndex){ this(inputColumnIndex, null); } /** * * @param inputColumnIndex * @param formatter */ public DefaultPivotHeaderRow(int inputColumnIndex, Format formatter){ super(formatter); setInputColumnIndex(inputColumnIndex); } /** * * @param builder */ private DefaultPivotHeaderRow(Builder builder){ super(builder.formatter); setInputColumnIndex(builder.columnIndex); } public int getInputColumnIndex() { return inputColumnIndex; } public void setInputColumnIndex(int index){ this.inputColumnIndex = index; } public Object getValue(NewRowEvent newRowEvent){ return newRowEvent.getInputDataRow().get(inputColumnIndex); } public static class Builder{ private int columnIndex; private Format formatter = null; public Builder(int columnIndex){ this.columnIndex = columnIndex; } public Builder useFormatter(Format format){ this.formatter = format; return this; } public DefaultPivotHeaderRow build(){ return new DefaultPivotHeaderRow(this); } } }
23.53125
76
0.689686
0b16a7268b2c6d6c8a3ba33e510d681a9d5b3889
14,199
/* * Copyright 2004 Cordys R&D B.V. * * This file is part of the Cordys Script Connector. * * 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.cordys.coe.ac.scriptconnector; import com.cordys.coe.ac.scriptconnector.aclib.INomConnector; import com.cordys.coe.ac.scriptconnector.aclib.ISoapRequestContext; import com.cordys.coe.ac.scriptconnector.aclib.NomConnectorImpl; import com.cordys.coe.ac.scriptconnector.config.ScriptConnectorConfiguration; import com.cordys.coe.ac.scriptconnector.config.SoapMethodInfo; import com.cordys.coe.ac.scriptconnector.exception.ScriptConnectorException; import com.cordys.coe.ac.scriptconnector.exception.SoapFaultWrapException; import com.cordys.coe.ac.scriptconnector.soap.ScriptSoapMessage; import com.cordys.coe.util.soap.SoapFaultInfo; import com.eibus.connector.nom.Connector; import com.eibus.soap.ApplicationConnector; import com.eibus.soap.ApplicationTransaction; import com.eibus.soap.Processor; import com.eibus.soap.SOAPTransaction; import com.eibus.util.logger.CordysLogger; import com.eibus.util.system.EIBProperties; import com.eibus.xml.nom.Document; import com.eibus.xml.nom.Node; import java.io.File; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * An application connector that can run javascripts. */ public class ScriptConnector extends ApplicationConnector { /** * Identifies the Logger. */ private static CordysLogger LOG = CordysLogger.getCordysLogger(ScriptConnector.class); /** * Holds the name of the connector. */ private static final String CONNECTOR_NAME = "ScriptConnector Connector"; /** * Holds the configuration object for this connector. */ protected ScriptConnectorConfiguration acConfiguration; /** * NOM document for parsing the XML. */ protected Document dDoc = new Document(); /** * Holds the connector to use for sending messages to Cordys. */ protected INomConnector nomConnector; /** * Method information parsing is locked using this object. */ private Object methodInfoParseMutex = new Object(); /** * Contains cached infomation for each called SOAP method. */ private ConcurrentMap<String, SoapMethodInfo> soapMethodMap = new ConcurrentHashMap<String, SoapMethodInfo>(); /** * Timer object for executing delayed tasks. */ private Timer timer = new Timer(); /** * This method creates the transaction that will handle the requests. * * @param stTransaction The SOAP-transaction containing the message. * * @return The newly created transaction. */ @Override public ApplicationTransaction createTransaction(SOAPTransaction stTransaction) { return new ScriptConnectorTransaction(this); } /** * This method gets called when the processor is started. It reads the configuration of the * processor and creates the connector with the proper parameters. It will also create a client * connection to Cordys. * * @param pProcessor The processor that is started. */ @Override public void open(Processor pProcessor) { try { File installationFolder = getCordysInstallationFolder(); if (installationFolder == null) { throw new ScriptConnectorException("Unable to determine the Cordys installation folder."); } if (LOG.isDebugEnabled()) { LOG.debug("Connector installation folder is: " + installationFolder); } // Get the configuration acConfiguration = new ScriptConnectorConfiguration(this, getConfiguration(), installationFolder); // Open the client connector Connector conn = Connector.getInstance(CONNECTOR_NAME); if (!conn.isOpen()) { conn.open(); } nomConnector = new NomConnectorImpl(conn); if (LOG.isDebugEnabled()) { LOG.debug("ScriptConnector started."); } } catch (Exception e) { LOG.error(e, LogMessages.CONNECTOR_INITIALIZATION_FAILED); throw new IllegalStateException("Connector initialization failed.", e); } } /** * This method gets called when the processor is ordered to rest. * * @param processor The processor that is to be in reset state */ @Override public void reset(Processor processor) { if (LOG.isDebugEnabled()) { LOG.debug("Processor reset."); } // Clear the SOAP method information cache. soapMethodMap.clear(); } /** * Adds a task to be scheduled. * * @param task Task to be scheduled. * @param delay Time after the task is executed. This is in milliseconds. */ public void scheduleTasks(TimerTask task, long delay) { timer.schedule(task, delay); } /** * Sends a SOAP request. This method does not receive for a response. * * @param msg SOAP request to be sent. * * @throws ScriptConnectorException */ public void sendSoapRequest(ScriptSoapMessage msg) throws ScriptConnectorException { int requestEnvNode = 0; try { requestEnvNode = createSoapRequest(msg); if (LOG.isDebugEnabled()) { LOG.debug("Sending an asynchronous SOAP request: " + Node.writeToString(requestEnvNode, true)); } nomConnector.send(requestEnvNode); } catch (ScriptConnectorException e) { throw e; } catch (Exception e) { throw new ScriptConnectorException("SOAP request failed.", e); } finally { if (requestEnvNode != 0) { Node.delete(requestEnvNode); requestEnvNode = 0; } } } /** * Sends a SOAP request and returns a response. This checks for SOAP:Fault. * * @param msg SOAP request to be sent. * * @return Received SOAP message. Caller is responsible for deleting this. * * @throws ScriptConnectorException */ public ScriptSoapMessage sendSoapRequestAndWait(ScriptSoapMessage msg) throws ScriptConnectorException { return sendSoapRequestAndWait(msg, true); } /** * Sends a SOAP request and returns a response. * * @param msg SOAP request to be sent. * @param checkSoapFault If <code>true</code>, an exception is thrown when SOAP:Fault is * received. * * @return Received SOAP message. Caller is responsible for deleting this. * * @throws ScriptConnectorException */ public ScriptSoapMessage sendSoapRequestAndWait(ScriptSoapMessage msg, boolean checkSoapFault) throws ScriptConnectorException { int requestEnvNode = 0; int responseEnvNode = 0; try { requestEnvNode = createSoapRequest(msg); if (LOG.isDebugEnabled()) { LOG.debug("Sending a SOAP request: " + Node.writeToString(requestEnvNode, true)); } responseEnvNode = nomConnector.sendAndWait(requestEnvNode, acConfiguration.getSoapRequestTimeout(), false); if (LOG.isDebugEnabled()) { LOG.debug("Received a SOAP response: " + Node.writeToString(responseEnvNode, true)); } if (checkSoapFault) { SoapFaultInfo faultInfo = SoapFaultInfo.findSoapFault(responseEnvNode); if (faultInfo != null) { String faultCode = faultInfo.getFaultcode(); String faultString = faultInfo.getFaultstring(); String faultActor = faultInfo.getFaultactor(); String faultStr = null; int faultNode = SoapFaultInfo.findSoapFaultNode(responseEnvNode); if (faultNode != 0) { // Define the SOAP namespace. Node.setNSDefinition(faultNode, Node.getPrefix(faultNode), Node.getNamespaceURI(faultNode)); faultStr = Node.writeToString(faultNode, false); } // Delete the response (including the fault XML). Node.delete(responseEnvNode); responseEnvNode = 0; throw new SoapFaultWrapException(faultCode, faultActor, faultString, faultStr); } } ScriptSoapMessage res = new ScriptSoapMessage(dDoc); res.readFromSoapMessage(responseEnvNode); return res; } catch (SoapFaultWrapException e) { throw e; } catch (ScriptConnectorException e) { throw e; } catch (Exception e) { throw new ScriptConnectorException("SOAP request failed.", e); } finally { if (responseEnvNode != 0) { Node.delete(responseEnvNode); responseEnvNode = 0; } if (requestEnvNode != 0) { Node.delete(requestEnvNode); requestEnvNode = 0; } } } /** * Returns the Cordys installation folder. * * @return */ public File getCordysInstallationFolder() { String sCordysDir = EIBProperties.getInstallDir(); File fCordysDir; if (sCordysDir != null) { fCordysDir = new File(sCordysDir); } else { return null; } return fCordysDir; } /** * Returns the shared NOM document. * * @return The shared NOM document. */ public Document getDocument() { return dDoc; } /** * Returns the DN of the organization where this connector is running in. * * @return Organization DN. */ public String getOrganizationDn() { return getProcessor().getOrganization(); } /** * Returns the configuration object. * * @return returns the configuration object. */ public ScriptConnectorConfiguration getScriptConfig() { return acConfiguration; } /** * Returns cached SOAP method information for the given SOAP method. * * @param requestContext Current SOAP request. * * @return SOAP method information or <code>null</code> if no information could be found. */ public SoapMethodInfo getSoapMethodInfo(ISoapRequestContext requestContext) { String methodDn = requestContext.getMethodDefinition().getMethodDN(); if (methodDn == null) { if (LOG.isDebugEnabled()) { LOG.debug("No method DN found from the method definition."); } return null; } SoapMethodInfo methodInfo = soapMethodMap.get(methodDn); if (methodInfo != null) { return methodInfo; } // Parse the method information. synchronized (methodInfoParseMutex) { // Try to fetch it again, if someone else has already parsed it. methodInfo = soapMethodMap.get(methodDn); if (methodInfo != null) { return methodInfo; } methodInfo = new SoapMethodInfo(this, requestContext); soapMethodMap.put(methodDn, methodInfo); } return methodInfo; } /** * Creates a SOAP request envelope for the passed SOAP method. * * @param msg SOAP message object containing the SOAP method. * * @return SOAP request envelope for the passed SOAP method. * * @throws ScriptConnectorException */ private int createSoapRequest(ScriptSoapMessage msg) throws ScriptConnectorException { String userDn = msg.getUserDn(); String orgDn = msg.getOrgDn(); if ((orgDn == null) || (orgDn.length() == 0)) { orgDn = getOrganizationDn(); } int requestEnvNode = 0; try { String methodName = msg.getMethodName(); String namespace = msg.getNamespace(); // Create the SOAP request, add our method next to the created method and // delete the created method. requestEnvNode = Node.getRoot(nomConnector.createSoapMethod(orgDn, userDn, methodName, namespace)); msg.appendToSoapEnvelope(requestEnvNode, true); return requestEnvNode; } catch (Exception e) { throw new ScriptConnectorException("SOAP request failed.", e); } } }
30.082627
114
0.581379
06f5fd1a1ac351f8fe252387110cc00ccce070ab
58,252
package it.unibz.inf.ontop.iq.executor; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import it.unibz.inf.ontop.dbschema.*; import it.unibz.inf.ontop.dbschema.impl.OfflineMetadataProviderBuilder; import it.unibz.inf.ontop.iq.node.*; import it.unibz.inf.ontop.model.atom.DistinctVariableOnlyDataAtom; import it.unibz.inf.ontop.iq.*; import it.unibz.inf.ontop.model.atom.AtomPredicate; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.model.type.DBTermType; import org.junit.Ignore; import org.junit.Test; import java.util.Optional; import static it.unibz.inf.ontop.OptimizationTestingTools.*; import static it.unibz.inf.ontop.model.term.functionsymbol.InequalityLabel.LT; import static junit.framework.TestCase.assertEquals; /** * Optimizations for inner joins based on unique constraints (like PKs). * * For self-joins * */ public class RedundantSelfJoinTest { private final static NamedRelationDefinition TABLE1; private final static NamedRelationDefinition TABLE2; private final static NamedRelationDefinition TABLE3; private final static NamedRelationDefinition TABLE4; private final static NamedRelationDefinition TABLE5; private final static NamedRelationDefinition TABLE6; private final static AtomPredicate ANS1_PREDICATE = ATOM_FACTORY.getRDFAnswerPredicate( 3); private final static AtomPredicate ANS1_PREDICATE_1 = ATOM_FACTORY.getRDFAnswerPredicate( 1); private final static AtomPredicate ANS1_PREDICATE_2 = ATOM_FACTORY.getRDFAnswerPredicate( 2); private final static Variable X = TERM_FACTORY.getVariable("X"); private final static Variable Y = TERM_FACTORY.getVariable("Y"); private final static Variable Z = TERM_FACTORY.getVariable("Z"); private final static Variable A = TERM_FACTORY.getVariable("A"); private final static Variable B = TERM_FACTORY.getVariable("B"); private final static Variable C = TERM_FACTORY.getVariable("C"); private final static Variable F0 = TERM_FACTORY.getVariable("f0"); private final static Constant ONE = TERM_FACTORY.getDBConstant("1", TYPE_FACTORY.getDBTypeFactory().getDBLargeIntegerType()); private final static Constant TWO = TERM_FACTORY.getDBConstant("2", TYPE_FACTORY.getDBTypeFactory().getDBLargeIntegerType()); private final static Constant THREE = TERM_FACTORY.getDBConstant("3", TYPE_FACTORY.getDBTypeFactory().getDBLargeIntegerType()); private final static Variable M = TERM_FACTORY.getVariable("m"); private final static Variable M1 = TERM_FACTORY.getVariable("m1"); private final static Variable N = TERM_FACTORY.getVariable("n"); private final static Variable N1 = TERM_FACTORY.getVariable("n1"); private final static Variable N2 = TERM_FACTORY.getVariable("n2"); private final static Variable O = TERM_FACTORY.getVariable("o"); private final static Variable O1 = TERM_FACTORY.getVariable("o1"); private final static Variable O2 = TERM_FACTORY.getVariable("o2"); private final static ImmutableExpression EXPRESSION1 = TERM_FACTORY.getStrictEquality(M, N); static{ OfflineMetadataProviderBuilder builder = createMetadataProviderBuilder(); DBTermType integerDBType = builder.getDBTypeFactory().getDBLargeIntegerType(); /* * Table 1: non-composite unique constraint and regular field */ TABLE1 = builder.createDatabaseRelation("table1", "col1", integerDBType, false, "col2", integerDBType, false, "col3", integerDBType, false); UniqueConstraint.primaryKeyOf(TABLE1.getAttribute(1)); /* * Table 2: non-composite unique constraint and regular field */ TABLE2 = builder.createDatabaseRelation("table2", "col1", integerDBType, false, "col2", integerDBType, false, "col3", integerDBType, false); UniqueConstraint.primaryKeyOf(TABLE2.getAttribute(2)); /* * Table 3: composite unique constraint over the first TWO columns */ TABLE3 = builder.createDatabaseRelation("table3", "col1", integerDBType, false, "col2", integerDBType, false, "col3", integerDBType, false); UniqueConstraint.primaryKeyOf(TABLE3.getAttribute(1), TABLE3.getAttribute(2)); /* * Table 4: unique constraint over the first column */ TABLE4 = builder.createDatabaseRelation("table4", "col1", integerDBType, false, "col2", integerDBType, false); UniqueConstraint.primaryKeyOf(TABLE4.getAttribute(1)); /* * Table 5: unique constraint over the second column */ TABLE5 = builder.createDatabaseRelation("table5", "col1", integerDBType, false, "col2", integerDBType, false); UniqueConstraint.primaryKeyOf(TABLE5.getAttribute(2)); /* * Table 6: two atomic unique constraints over the first and third columns */ TABLE6 = builder.createDatabaseRelation("table6", "col1", integerDBType, false, "col2", integerDBType, false, "col3", integerDBType, false); UniqueConstraint.primaryKeyOf(TABLE6.getAttribute(1)); UniqueConstraint.builder(TABLE6, "table6-uc3") .addDeterminant(3) .build(); } @Test public void testJoiningConditionTest() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(EXPRESSION1); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2)))); ConstructionNode constructionNode1 = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(), SUBSTITUTION_FACTORY.getSubstitution(N, M)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, M, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode1, dataNode3)); optimizeAndCompare(initialIQ, expectedIQ); } /** * TODO: explain */ @Test public void testSelfJoinElimination1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE2, ImmutableList.of(M1, N, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2, dataNode3, dataNode4)))); InnerJoinNode joinNode1 = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode6 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(joinNode1, ImmutableList.of(dataNode5, dataNode6))); optimizeAndCompare(initialIQ, expectedIQ); } /** * TODO: explain */ @Test public void testSelfJoinElimination2() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ATOM_FACTORY.getRDFAnswerPredicate(1), Y); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE2, ImmutableList.of(X, Y, Z)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE2, ImmutableList.of(X, Y, TWO)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2)))); ExtensionalDataNode extensionalDataNode = IQ_FACTORY.createExtensionalDataNode(TABLE2, ImmutableMap.of(1, Y, 2, TWO)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, extensionalDataNode); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testNonEliminationTable1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ATOM_FACTORY.getRDFAnswerPredicate(1), Y); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(X, Y, Z)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(Z, Y, TWO)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2)))); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of( IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(1, Y, 2, Z)), dataNode2)))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSelfJoinElimination3() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ATOM_FACTORY.getRDFAnswerPredicate(1), Y); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE3, ImmutableList.of(X, Y, Z)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE3, ImmutableList.of(X, Y, TWO)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2)))); ExtensionalDataNode extensionalDataNode = IQ_FACTORY.createExtensionalDataNode(TABLE3, ImmutableMap.of(1, Y, 2, TWO)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, extensionalDataNode); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testNonEliminationTable3() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ATOM_FACTORY.getRDFAnswerPredicate(1), Y); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE3, ImmutableList.of(X, Z, Z)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE3, ImmutableList.of(X, Y, TWO)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2)))); IQ expectedIQ = initialIQ; optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSelfJoinElimination4() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE2, ImmutableList.of(M1, N2, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2, dataNode3, dataNode4)))); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of( dataNode5, createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O)), IQ_FACTORY.createExtensionalDataNode(TABLE2, ImmutableMap.of(2, O))))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSelfJoinElimination5() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2, dataNode3, dataNode4)))); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of( dataNode2, createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O))))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testPropagation1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2, dataNode3)))); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode6 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode5, dataNode6))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testPropagation2() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode leftJoinNode = IQ_FACTORY.createLeftJoinNode(); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(leftJoinNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2)), dataNode3))); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode6 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createBinaryNonCommutativeIQTree(leftJoinNode, dataNode5, dataNode6)); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testLoop1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE2, ImmutableList.of(M1, N1, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2, dataNode3, dataNode4)))); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode6 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode5, dataNode6))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testTopJoinUpdateOptimal() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(TERM_FACTORY.getDBDefaultInequality(LT, O1, N1)); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE2, ImmutableList.of(M1, N, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2, dataNode3, dataNode4)))); InnerJoinNode joinNode1 = IQ_FACTORY.createInnerJoinNode(TERM_FACTORY.getDBDefaultInequality(LT, O, N)); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode6 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(joinNode1, ImmutableList.of(dataNode5, dataNode6))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testTopJoinUpdateSubOptimal() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(TERM_FACTORY.getDBDefaultInequality(LT, O1, N1)); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE2, ImmutableList.of(M1, N, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2, dataNode3, dataNode4)))); InnerJoinNode joinNode1 = IQ_FACTORY.createInnerJoinNode(TERM_FACTORY.getDBDefaultInequality(LT, O, N)); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode6 = createExtensionalDataNode(TABLE2, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(joinNode1, ImmutableList.of(dataNode5, dataNode6))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testDoubleUniqueConstraints1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N1, TWO)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2)))); ConstructionNode newConstructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(), SUBSTITUTION_FACTORY.getSubstitution(O, TWO)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N, TWO)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(newConstructionNode, dataNode3)); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testDoubleUniqueConstraints2() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE6, ImmutableList.of(TWO, N2, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2, dataNode3)))); ConstructionNode newConstructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(), SUBSTITUTION_FACTORY.getSubstitution(M, TWO)); ExtensionalDataNode expectedDataNode = createExtensionalDataNode(TABLE6, ImmutableList.of(TWO, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(newConstructionNode, expectedDataNode)); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testDoubleUniqueConstraints3() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE6, ImmutableList.of(TWO, N1, O2)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2, dataNode3)))); ExtensionalDataNode expectedDataNode1 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N, O)); ExtensionalDataNode expectedDataNode2 = IQ_FACTORY.createExtensionalDataNode(TABLE6, ImmutableMap.of(0, TWO, 1, N)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(expectedDataNode1, expectedDataNode2))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testNonUnification1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, ONE, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE6, ImmutableList.of(TWO, TWO, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2, dataNode3)))); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createEmptyNode(projectionAtom.getVariables())); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testNonUnification2() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode leftJoinNode = IQ_FACTORY.createLeftJoinNode(); ConstructionNode leftConstructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(M)); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N2, O2)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, N, O1)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE6, ImmutableList.of(M, ONE, O)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE6, ImmutableList.of(TWO, TWO, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(leftJoinNode, IQ_FACTORY.createUnaryIQTree(leftConstructionNode, dataNode1), IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3, dataNode4))))); ConstructionNode newRootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(), SUBSTITUTION_FACTORY.getSubstitution(N, NULL, O, NULL)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(newRootNode, IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, M)))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testJoiningConditionRemoval() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ImmutableExpression joiningCondition = TERM_FACTORY.getDisjunction( TERM_FACTORY.getStrictEquality(O, ONE), TERM_FACTORY.getStrictEquality(O, TWO)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(joiningCondition); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, ONE)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2)))); ConstructionNode constructionNode1 = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(), SUBSTITUTION_FACTORY.getSubstitution(O, ONE)); ExtensionalDataNode dataNode5 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, ONE)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode1, dataNode5)); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testUnsatisfiedJoiningCondition() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); ImmutableExpression joiningCondition = TERM_FACTORY.getDisjunction( TERM_FACTORY.getStrictEquality(O, TWO), TERM_FACTORY.getStrictEquality(O, THREE)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(joiningCondition); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, ONE)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2)))); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createEmptyNode(projectionAtom.getVariables())); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testNoModification1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); ImmutableExpression joiningCondition = TERM_FACTORY.getDisjunction( TERM_FACTORY.getStrictEquality(O, TWO), TERM_FACTORY.getStrictEquality(O, THREE)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(joiningCondition); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, ONE)); ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(TABLE2, ImmutableMap.of(0, M, 2, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2))); IQ expectedIQ = initialIQ; optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testNoModification2() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE, M, N, O); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, ONE)); ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(TABLE2, ImmutableMap.of(0, M, 2, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2))); IQ expectedIQ = initialIQ; optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ1EqualityInJoiningCondition() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(M, N)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, M, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(TERM_FACTORY.getStrictEquality(N, M)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, M, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, dataNode4))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(M, N)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, M, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(TERM_FACTORY.getStrictEquality(N, M)); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, M, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, dataNode4))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ2() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(M, N)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, M)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, M, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); ConstructionNode newConstructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(), SUBSTITUTION_FACTORY.getSubstitution(O, TERM_FACTORY.getIfElseNull(TERM_FACTORY.getDBIsNotNull(F0), N))); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(TERM_FACTORY.getStrictEquality(M, N)); ConstructionNode rightConstruction = IQ_FACTORY.createConstructionNode( ImmutableSet.of(F0, N), SUBSTITUTION_FACTORY.getSubstitution(F0, TERM_FACTORY.getProvenanceSpecialConstant())); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE1, ImmutableList.of(N, N, N)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(newConstructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, IQ_FACTORY.createUnaryIQTree(rightConstruction, dataNode4)))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ3() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(M, N)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, dataNode4))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ4() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(M, N)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, dataNode3))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ5() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(M, N1)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N1, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, dataNode4))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ6() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(O, N)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1,ImmutableList.of( M, N, M)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, M, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); ConstructionNode newConstructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(), SUBSTITUTION_FACTORY.getSubstitution(M, TERM_FACTORY.getIfElseNull(TERM_FACTORY.getDBIsNotNull(F0), O))); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(TERM_FACTORY.getStrictEquality(N, O)); ConstructionNode rightConstructionNode = IQ_FACTORY.createConstructionNode( ImmutableSet.of(F0, O), SUBSTITUTION_FACTORY.getSubstitution(F0, TERM_FACTORY.getProvenanceSpecialConstant())); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE1, ImmutableList.of(O, O, O)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(newConstructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, IQ_FACTORY.createUnaryIQTree(rightConstructionNode, dataNode4)))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testOptimizationOnRightPartOfLJ7() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, O); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode ljNode = IQ_FACTORY.createLeftJoinNode(); ExtensionalDataNode leftNode = createExtensionalDataNode(TABLE4, ImmutableList.of(O, N)); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, N, N)); ExtensionalDataNode dataNode3 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, ONE, O)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(ljNode, leftNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode2, dataNode3))))); ConstructionNode newConstructionNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); LeftJoinNode newLJNode = IQ_FACTORY.createLeftJoinNode(TERM_FACTORY.getConjunction( TERM_FACTORY.getStrictEquality(N, ONE), TERM_FACTORY.getStrictEquality(O, ONE))); ExtensionalDataNode dataNode4 = createExtensionalDataNode(TABLE1, ImmutableList.of(M, ONE, ONE)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(newConstructionNode, IQ_FACTORY.createBinaryNonCommutativeIQTree(newLJNode, leftNode, dataNode4))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSubstitutionPropagationWithBlockingUnion1() { Constant constant = TERM_FACTORY.getDBStringConstant("constant"); DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_1, X); ConstructionNode initialRootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(Optional.empty()); UnionNode unionNode = IQ_FACTORY.createUnionNode(ImmutableSet.of(X)); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(A, B, constant)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(A, X, C)); ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(TABLE4, ImmutableMap.of(0, X)); ConstructionNode rightConstructionNode = IQ_FACTORY.createConstructionNode(unionNode.getVariables()); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(initialRootNode, IQ_FACTORY.createNaryIQTree(unionNode, ImmutableList.of( dataNode3, IQ_FACTORY.createUnaryIQTree(rightConstructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2))))))); /* * The following is only one possible syntactic variant of the expected query, * namely the one expected based on the current state of the implementation of self join elimination * and substitution propagation. */ ExtensionalDataNode dataNode4 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(1, X, 2, constant)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(unionNode, ImmutableList.of(dataNode3, dataNode4))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSubstitutionPropagationWithBlockingUnion2() { Constant constant = TERM_FACTORY.getDBStringConstant("constant"); DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, X, Y); ConstructionNode initialRootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables()); InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(); UnionNode unionNode = IQ_FACTORY.createUnionNode(ImmutableSet.of(X, Y)); ExtensionalDataNode dataNode1 = createExtensionalDataNode(TABLE1, ImmutableList.of(A, X, constant)); ExtensionalDataNode dataNode2 = createExtensionalDataNode(TABLE1, ImmutableList.of(A, Y, C)); ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(TABLE4, ImmutableMap.of(0, X, 1, Y)); ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(unionNode.getVariables()); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(initialRootNode, IQ_FACTORY.createNaryIQTree(unionNode, ImmutableList.of( dataNode3, IQ_FACTORY.createUnaryIQTree(constructionNode, IQ_FACTORY.createNaryIQTree(joinNode, ImmutableList.of(dataNode1, dataNode2))))))); /* * The following is only one possible syntactic variant of the expected query, * namely the one expected based on the current state of the implementation of self join elimination * and substitution propagation. */ ConstructionNode newConstructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(X, Y), SUBSTITUTION_FACTORY.getSubstitution(X, Y)); ExtensionalDataNode newDataNode = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(1, Y, 2, constant)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(unionNode, ImmutableList.of( dataNode3, IQ_FACTORY.createUnaryIQTree(newConstructionNode, newDataNode)))); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSelfJoinEliminationFunctionalGroundTerm1() { DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_2, M, N); GroundFunctionalTerm groundFunctionalTerm = (GroundFunctionalTerm) TERM_FACTORY.getImmutableFunctionalTerm( FUNCTION_SYMBOL_FACTORY.getDBFunctionSymbolFactory() .getRegularDBFunctionSymbol("fct", 1), ONE); ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, groundFunctionalTerm, 1, M)); ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, groundFunctionalTerm, 2, N)); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2))); ExtensionalDataNode expectedDataNode = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, groundFunctionalTerm, 1, M, 2, N)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree( IQ_FACTORY.createFilterNode(TERM_FACTORY.getDBIsNotNull(groundFunctionalTerm)), expectedDataNode)); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSelfJoinEliminationFunctionalGroundTerm2() { GroundFunctionalTerm groundFunctionalTerm = (GroundFunctionalTerm) TERM_FACTORY.getImmutableFunctionalTerm( FUNCTION_SYMBOL_FACTORY.getDBFunctionSymbolFactory() .getRegularDBFunctionSymbol("fct", 1), ONE); ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, M, 1, groundFunctionalTerm)); ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, M, 1, TWO)); DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_1, M); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2))); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(IQ_FACTORY.createFilterNode( TERM_FACTORY.getStrictEquality(groundFunctionalTerm, TWO)), dataNode2)); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void testSelfJoinEliminationFunctionalGroundTerm3() { GroundFunctionalTerm groundFunctionalTerm1 = (GroundFunctionalTerm) TERM_FACTORY.getImmutableFunctionalTerm( FUNCTION_SYMBOL_FACTORY.getDBFunctionSymbolFactory() .getRegularDBFunctionSymbol("fct", 1), ONE); GroundFunctionalTerm groundFunctionalTerm2 = (GroundFunctionalTerm) TERM_FACTORY.getImmutableFunctionalTerm( FUNCTION_SYMBOL_FACTORY.getDBFunctionSymbolFactory() .getRegularDBFunctionSymbol("g", 0)); ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, M, 1, groundFunctionalTerm1)); ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, M, 1, groundFunctionalTerm2)); DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_1, M); IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2))); ImmutableExpression condition = TERM_FACTORY.getConjunction( TERM_FACTORY.getDBIsNotNull(groundFunctionalTerm1), TERM_FACTORY.getStrictEquality(groundFunctionalTerm2, groundFunctionalTerm1)); IQ expectedIQ = IQ_FACTORY.createIQ(projectionAtom, IQ_FACTORY.createUnaryIQTree(IQ_FACTORY.createFilterNode(condition), dataNode1)); optimizeAndCompare(initialIQ, expectedIQ); } @Test public void test2LevelJoinWithAggregate() { ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, A, 1, B)); ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(0, A)); AggregationNode aggregationNode = IQ_FACTORY.createAggregationNode(ImmutableSet.of(B), SUBSTITUTION_FACTORY.getSubstitution(C, TERM_FACTORY.getDBCount(false))); ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(TABLE2, ImmutableMap.of(0, B)); NaryIQTree initialTree = IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of( dataNode3, IQ_FACTORY.createUnaryIQTree(aggregationNode, IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of(dataNode1, dataNode2))))); ExtensionalDataNode dataNode4 = IQ_FACTORY.createExtensionalDataNode(TABLE1, ImmutableMap.of(1, B)); NaryIQTree expectedTree = IQ_FACTORY.createNaryIQTree(IQ_FACTORY.createInnerJoinNode(), ImmutableList.of( dataNode3, IQ_FACTORY.createUnaryIQTree(aggregationNode, dataNode4))); DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom( ATOM_FACTORY.getRDFAnswerPredicate(2), B, C); optimizeAndCompare(IQ_FACTORY.createIQ(projectionAtom, initialTree), IQ_FACTORY.createIQ(projectionAtom, expectedTree)); } private static void optimizeAndCompare(IQ initialIQ, IQ expectedIQ) { System.out.println("\nBefore optimization: \n" + initialIQ); IQ optimizedIQ = JOIN_LIKE_OPTIMIZER.optimize(initialIQ); System.out.println("\n After optimization: \n" + optimizedIQ); System.out.println("\n Expected query: \n" + expectedIQ); assertEquals(expectedIQ, optimizedIQ); } }
58.01992
150
0.720834
0779e50d35d87dd0073fc138ebc28b084b068a5a
2,876
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.walkaround.wave.server.auth; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.walkaround.wave.server.auth.ServletAuthHelper.UserServiceAccountLookup; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Filter that initializes {@link UserContext} from App Engine's * {@link UserService}. Leaves the OAuth credentials in {@link UserContext} null if no * OAuth token is stored for the user. * * @author [email protected] (Christian Ohler) */ @Singleton public class InteractiveAuthFilter implements Filter { @SuppressWarnings("unused") private static final Logger log = Logger.getLogger(InteractiveAuthFilter.class.getName()); private final Provider<UserServiceAccountLookup> accountLookup; private final Provider<ServletAuthHelper> helper; private final Provider<User> user; @Inject public InteractiveAuthFilter(Provider<UserServiceAccountLookup> accountLookup, Provider<ServletAuthHelper> helper, Provider<User> user) { this.accountLookup = accountLookup; this.helper = helper; this.user = user; } @Override public void init(FilterConfig config) {} @Override public void destroy() {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse resp = (HttpServletResponse) response; helper.get().filter(req, resp, filterChain, accountLookup.get(), new ServletAuthHelper.NeedNewOAuthTokenHandler() { @Override public void sendNeedTokenResponse() throws IOException { helper.get().redirectToOAuthPage(req, resp, user.get().getEmail()); } }); } }
34.238095
97
0.761474
173c120c566fcbc8c7ee219576fd88bd2c1de7fd
2,129
package com.jzoom.zoom.token.hex; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.concurrent.TimeUnit; /** * 思路: * 1、在用户需要登录的时候,向服务器端申请客户端token * 客户端token与服务端token配对 * * 客户端token含如下内容: * (1) id: 根据设备号生成的随机数,本随机数用于索引服务端token * (2) pub: 离2017年1月1日到现在的秒数 * (3) exp: 超时时间,秒数 * (4) 签名 : sha256 + 固定64位秘钥 * * * 在下发token的是否附带并在客户端保存 * signKey: md5签名秘钥 * publicKey: rsa加密公钥1024 * * * * 客户端token的过期时间为30分钟 * * refreshToken: 另一个token,用于在客户端token过期之后换取新的token * 含如下内容: * (1) uid:用户号(aes 加密存储,公共秘钥) * (2) pub: 离2017年1月1日到现在的秒数 * (3) exp: 超时时间,秒数 * (4) 签名: sha256 + 固定64位秘钥 * * 服务端token含如下内容: * (1) id: 与客户端id同 * (2) signKey: md5签名秘钥,与客户端signKey同 * (3) uid: 用户id 起始为空值,在登录之后为实际用户id * (4) deviceId : 用户设备号,用于推送 * (5) phone: 用户手机号 * (6) privateKey: 用户数据解密秘钥 * * 2、在客户端在调用用户个人接口的时候,在http header上送客户端token * 形式: headers : { token :`${token}` } * * 3、服务端验证客户端token: * 相同的签名方式,使用服务端签名重新签名一次并与客户端签名做比对 * * 4、服务器端验证客户端签名: * 使用想用的签名方式,重新签名一次客户端数据 * * 5、超时机制: * 客户端超时:客户端颁发时间+超时时间 < 现在时间就超时了 * server端token:memcached超时,如果没有找到,那么就超时了, * 要求客户端使用refreshToken换取客户端签名 * * 6、refreshToken换取客户端签名流程: * 过期判断: 两周,只做客户端信息判断 * (1) 根据uid查询用户,确定用户状态 * (2) 如正常则颁发客户端token与服务端token配对 * (3) refreshToken的正常过期时间为2周 * (4) 离过期时间3天,下发refreshToken,并更新 * 优点:不需要refreshToken存储 * 如果用户两周没有用,则需要重新登录。 * * * * * * @author renxueliang * */ public class TokenUtil { private static final long START_TIME ; static{ try { START_TIME = new SimpleDateFormat("yyyyMMdd").parse("20170101").getTime(); } catch (ParseException e) { throw new RuntimeException(e); } } private static int getPubTime(){ return (int) ((System.currentTimeMillis() - START_TIME)/1000); } public static boolean isTimeout(int pub, int exp) { return pub + exp < getPubTime(); } public static ClientToken createToken( String userId , long duration, TimeUnit unit ) { ClientToken token = new ClientToken(); token.setId(userId); token.setPub( TokenUtil.getPubTime() ); token.setExp( (int) unit.toSeconds(duration) ); return token; } }
20.084906
88
0.68201
c7ae75422ca76dc71b52439c768090f704fadad6
2,518
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_package DECL|package|org.jabref.gui package|package name|org operator|. name|jabref operator|. name|gui package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Collection import|; end_import begin_import import|import name|javafx operator|. name|scene operator|. name|layout operator|. name|BorderPane import|; end_import begin_import import|import name|javafx operator|. name|scene operator|. name|layout operator|. name|VBox import|; end_import begin_comment comment|/** * The side pane is displayed at the left side of JabRef and shows instances of {@link SidePaneComponent}. */ end_comment begin_class DECL|class|SidePane specifier|public class|class name|SidePane extends|extends name|BorderPane block|{ DECL|field|mainPanel specifier|private specifier|final name|VBox name|mainPanel init|= operator|new name|VBox argument_list|() decl_stmt|; DECL|method|SidePane () specifier|public name|SidePane parameter_list|() block|{ name|setId argument_list|( literal|"sidePane" argument_list|) expr_stmt|; name|setCenter argument_list|( name|mainPanel argument_list|) expr_stmt|; block|} DECL|method|setComponents (Collection<SidePaneComponent> components) specifier|public name|void name|setComponents parameter_list|( name|Collection argument_list|< name|SidePaneComponent argument_list|> name|components parameter_list|) block|{ name|mainPanel operator|. name|getChildren argument_list|() operator|. name|clear argument_list|() expr_stmt|; for|for control|( name|SidePaneComponent name|component range|: name|components control|) block|{ name|BorderPane name|node init|= operator|new name|BorderPane argument_list|() decl_stmt|; name|node operator|. name|getStyleClass argument_list|() operator|. name|add argument_list|( literal|"sidePaneComponent" argument_list|) expr_stmt|; name|node operator|. name|setTop argument_list|( name|component operator|. name|getHeader argument_list|() argument_list|) expr_stmt|; name|node operator|. name|setCenter argument_list|( name|component operator|. name|getContentPane argument_list|() argument_list|) expr_stmt|; name|mainPanel operator|. name|getChildren argument_list|() operator|. name|add argument_list|( name|node argument_list|) expr_stmt|; name|VBox operator|. name|setVgrow argument_list|( name|node argument_list|, name|component operator|. name|getResizePolicy argument_list|() argument_list|) expr_stmt|; block|} block|} block|} end_class end_unit
14.067039
122
0.807387
604d12696a22ee9fd0adaf3a37ba3a6b83111a4f
123
package codeholic.domain; import lombok.Data; @Data public class SocketStatusMessage { private String accessToken; }
13.666667
34
0.780488
0f636cc2a9661e2e0dd15e0440f068374f5ccf33
1,481
package com.teamwizardry.inhumanresources.common.items; import java.util.List; import com.teamwizardry.inhumanresources.common.utils.IUpgradable; import com.teamwizardry.librarianlib.features.base.item.ItemModTool; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.living.LivingHurtEvent; public class ItemMistwroughtAxe extends ItemModTool implements IUpgradable { public ItemMistwroughtAxe(String name, ToolMaterial toolMaterial) { super(name, toolMaterial, "axe"); } @Override public void onAttackEntity(LivingHurtEvent event, EntityLivingBase attacker, EntityLivingBase target, ItemStack weapon, ItemStack offhand) { } @Override public boolean runActive(EntityPlayer player, ItemStack weapon, ItemStack offhand, boolean runAsMainhand) { return false; } @Override public List<String> getActives() { return null; } @Override public List<String> getActiveUpgrades(String active) { return null; } @Override public int getActiveCooldown(String active, String activeUpgrade) { return 0; } @Override public List<String> getOffensives() { return null; } @Override public List<String> getOffensiveUpgrades(String offensive) { return null; } @Override public List<String> getDefensives() { return null; } @Override public List<String> getDefensiveUpgrades(String defensive) { return null; } }
20.013514
139
0.779203
be7237c6aba1018d54254b67627c71a25233743d
539
package ee.pri.rl.indexer.mass.data.cache; import java.util.Map; /** * Sõnade vahemälu liides. * * @author raivo */ public interface WordCache extends Cache { /** * Sõna identifikaatori saamine. */ public int getId(String word); /** * Sõnade hoidla saamine. */ public Map<String, Integer> getWords(); /** * Sõnade lisamisel võetakse järgmine id lastId järgi. */ public void setLastId(int lastId); /** * Sõnade väljakirjutamisel kirjutatakse välja id-st dumpFrom. */ public void setDumpFrom(int dumpFrom); }
19.25
63
0.692022
d7383bbdcf286a7e51a3aeab8d662250f5b01a65
6,781
package ServerHawk; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.stage.Stage; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.GraphicsCard; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.OSProcess; import oshi.software.os.OperatingSystem; import oshi.util.FormatUtil; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; public class GPUController implements Initializable { private Stage stage; private Scene scene; private Parent root; @FXML private CategoryAxis Time; @FXML private LineChart<String, Number> gpuUtilizationGraph; @FXML private Button cpuSelect; @FXML private Button gpuSelect; @FXML private Label systemName; @FXML private Label gpu_Used_Memory; @FXML private Label gpu_Current_Clock; @FXML private Label gpu_Driver_Version; @FXML private Label gpu_Make_Model; @FXML private Label gpu_Memory; @FXML private Label gpu_Base_Clock; @FXML private Label gpu_Free_Memory; @FXML private Label gpu_Temperature; @FXML private Label gpu_Utilization; @FXML private Button homeSelect; @FXML private Button networkSelect; @FXML private Button ramSelect; @FXML private Button storageSelect; @FXML private NumberAxis totalUtilization; @Override public void initialize(URL url, ResourceBundle resourceBundle) { SystemInfo systemInfo = new SystemInfo(); HardwareAbstractionLayer hal = systemInfo.getHardware(); OperatingSystem os = systemInfo.getOperatingSystem(); GraphicsCard graphicsCard = hal.getGraphicsCards().get(0); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss"); XYChart.Series<String, Number> series = new XYChart.Series<>(); series.setName("% Utilization"); gpuUtilizationGraph.getData().add(series); systemName.setText("System Name: " + getSystemName(os)); gpu_Temperature.setText(String.format("%.1f °C", graphicsCard.getTemp())); gpu_Memory.setText(String.valueOf(FormatUtil.formatBytes(graphicsCard.getVRam()))); gpu_Make_Model.setText(hal.getGraphicsCards().get(0).getName()); gpu_Base_Clock.setText(String.format("%.2f Mhz",graphicsCard.getMaxFreq())); gpu_Current_Clock.setText(String.format("%.2f Mhz", graphicsCard.getCurrentFreq())); gpu_Driver_Version.setText(graphicsCard.getVersionInfo()); gpu_Utilization.setText(String.format("%.1f %%", graphicsCard.getUtil())); gpu_Free_Memory.setText(String.format("%.1f MB", graphicsCard.getFreeMem())); gpu_Used_Memory.setText(String.format("%.1f MB", graphicsCard.getUsedMem())); // A timer that serves to update the uptime label every second Timer gpuTimer = new Timer(); gpuTimer.schedule(new TimerTask() { // A timer task to update the seconds of the uptime label @Override public void run() { Platform.runLater(new Runnable() { public void run() { gpu_Temperature.setText(String.format("%.1f °C", graphicsCard.getTemp())); gpu_Utilization.setText(String.format("%.1f %%", graphicsCard.getUtil())); gpu_Current_Clock.setText(String.format("%.2f Mhz", graphicsCard.getCurrentFreq())); gpu_Free_Memory.setText(String.format("%.1f MB", graphicsCard.getFreeMem())); gpu_Used_Memory.setText(String.format("%.1f MB", graphicsCard.getUsedMem())); Date currentTime = new Date(); series.getData().add(new XYChart.Data<>(simpleDateFormat.format(currentTime), (graphicsCard.getUtil()))); if (series.getData().size() > 15) { series.getData().remove(0); } } }); } }, 1000, 1000); // Refresh every 1 second } public void switchToCPU (ActionEvent event) throws IOException { root = FXMLLoader.load(getClass().getResource("CPU.fxml")); stage = (Stage)((Node)event.getSource()).getScene().getWindow(); scene = new Scene(root); stage.setScene(scene); stage.show(); } public void switchToGPU (ActionEvent event) throws IOException { root = FXMLLoader.load(getClass().getResource("GPU.fxml")); stage = (Stage)((Node)event.getSource()).getScene().getWindow(); scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML void switchToNetwork(ActionEvent event) throws IOException { root = FXMLLoader.load(getClass().getResource("Network.fxml")); stage = (Stage)((Node)event.getSource()).getScene().getWindow(); scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML void switchToRAM(ActionEvent event) throws IOException { root = FXMLLoader.load(getClass().getResource("RAM.fxml")); stage = (Stage)((Node)event.getSource()).getScene().getWindow(); scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML void switchToStorage(ActionEvent event) throws IOException { root = FXMLLoader.load(getClass().getResource("HDD-SDD.fxml")); stage = (Stage)((Node)event.getSource()).getScene().getWindow(); scene = new Scene(root); stage.setScene(scene); stage.show(); } @FXML void switchToHome(ActionEvent event) throws IOException { root = FXMLLoader.load(getClass().getResource("ServerHawk.fxml")); stage = (Stage)((Node)event.getSource()).getScene().getWindow(); scene = new Scene(root); stage.setScene(scene); stage.show(); } public String getSystemName(OperatingSystem os) { OSProcess process = os.getProcess(os.getProcessId()); for (Map.Entry<String, String> e : process.getEnvironmentVariables().entrySet()) { if(e.getKey().equals("COMPUTERNAME")) { return e.getValue(); } } return "DefaultValue"; } }
31.686916
129
0.647102
283810fa7388c95a95f39554e9b38cfb911da907
6,299
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aesh.console; import org.jboss.aesh.console.command.Command; import org.jboss.aesh.console.command.activator.AeshOptionActivatorProvider; import org.jboss.aesh.console.command.activator.OptionActivatorProvider; import org.jboss.aesh.console.command.completer.AeshCompleterInvocationProvider; import org.jboss.aesh.console.command.completer.CompleterInvocationProvider; import org.jboss.aesh.console.command.converter.AeshConverterInvocationProvider; import org.jboss.aesh.console.command.converter.ConverterInvocationProvider; import org.jboss.aesh.console.command.invocation.CommandInvocationServices; import org.jboss.aesh.console.command.registry.CommandRegistry; import org.jboss.aesh.console.command.registry.MutableCommandRegistry; import org.jboss.aesh.console.command.validator.AeshValidatorInvocationProvider; import org.jboss.aesh.console.command.validator.ValidatorInvocationProvider; import org.jboss.aesh.console.helper.ManProvider; import org.jboss.aesh.console.settings.CommandNotFoundHandler; import org.jboss.aesh.console.settings.Settings; import org.jboss.aesh.console.settings.SettingsBuilder; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:[email protected]">Ståle W. Pedersen</a> */ public class AeshConsoleBuilder { private Settings settings; private Prompt prompt; private CommandRegistry registry; private CommandInvocationServices commandInvocationServices; private CommandNotFoundHandler commandNotFoundHandler; private ManProvider manProvider; private CompleterInvocationProvider completerInvocationProvider; private ConverterInvocationProvider converterInvocationProvider; private ValidatorInvocationProvider validatorInvocationProvider; private OptionActivatorProvider optionActivatorProvider; private List<Command> commands; private String execute; public AeshConsoleBuilder() { commands = new ArrayList<>(); } public AeshConsoleBuilder commandRegistry(CommandRegistry registry) { this.registry = registry; return this; } public AeshConsoleBuilder settings(Settings settings) { this.settings = settings; return this; } public AeshConsoleBuilder prompt(Prompt prompt) { this.prompt = prompt; return this; } public AeshConsoleBuilder commandInvocationProvider(CommandInvocationServices commandInvocationServices) { this.commandInvocationServices = commandInvocationServices; return this; } public AeshConsoleBuilder commandNotFoundHandler(CommandNotFoundHandler commandNotFoundHandler) { this.commandNotFoundHandler = commandNotFoundHandler; return this; } public AeshConsoleBuilder completerInvocationProvider(CompleterInvocationProvider completerInvocationProvider) { this.completerInvocationProvider = completerInvocationProvider; return this; } public AeshConsoleBuilder converterInvocationProvider(ConverterInvocationProvider converterInvocationProvider) { this.converterInvocationProvider = converterInvocationProvider; return this; } public AeshConsoleBuilder validatorInvocationProvider(ValidatorInvocationProvider validatorInvocationProvider) { this.validatorInvocationProvider = validatorInvocationProvider; return this; } public AeshConsoleBuilder optionActivatorProvider(OptionActivatorProvider optionActivatorProvider) { this.optionActivatorProvider = optionActivatorProvider; return this; } public AeshConsoleBuilder manProvider(ManProvider manProvider) { this.manProvider = manProvider; return this; } public AeshConsoleBuilder addCommand(Command command) { commands.add(command); return this; } public AeshConsoleBuilder executeAtStart(String execute) { this.execute = execute; return this; } public AeshConsole create() { if(settings == null) settings = new SettingsBuilder().create(); if(registry == null) { registry = new MutableCommandRegistry(); } if(commands.size() > 0 && registry instanceof MutableCommandRegistry) ((MutableCommandRegistry) registry).addAllCommands(commands); if(commandInvocationServices == null) commandInvocationServices = new CommandInvocationServices(); if(completerInvocationProvider == null) completerInvocationProvider = new AeshCompleterInvocationProvider(); if(converterInvocationProvider == null) converterInvocationProvider = new AeshConverterInvocationProvider(); if(validatorInvocationProvider == null) validatorInvocationProvider = new AeshValidatorInvocationProvider(); if(optionActivatorProvider == null) optionActivatorProvider = new AeshOptionActivatorProvider(); AeshConsoleImpl aeshConsole = new AeshConsoleImpl(settings, registry, commandInvocationServices, commandNotFoundHandler, completerInvocationProvider, converterInvocationProvider, validatorInvocationProvider, optionActivatorProvider, manProvider); if(prompt != null) aeshConsole.setPrompt(prompt); if(execute != null) aeshConsole.execute(execute); return aeshConsole; } }
38.408537
116
0.750278
549c86e9e5bfd58296e76b418200aff7324313ad
1,425
package com.example.unit.testing; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class BankAccountTest { private BankAccount bankAccount; @BeforeEach void setup() { bankAccount = new BankAccount("Vlad", "Kondratuk", 900.00, BankAccount.CHECKING); } @Test void deposit() { double balance = bankAccount.deposit(350.00, true); assertEquals(1250.00, balance, 0); } @Test void withdraw_branch() { double balance = bankAccount.withdraw(350.00, true); assertEquals(550.00, balance, 0); } @Test void withdraw_notBranch() { Exception exception = assertThrows(IllegalArgumentException.class, () -> bankAccount.withdraw(550.00, false)); String expectedMessage = "You cannot withdraw more than 500.00 at an ATM"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } @Test void getBalance_deposit() { bankAccount.deposit(350.00, true); assertEquals(1250.00, bankAccount.getBalance(), 0); } @Test void getBalance_withdraw() { bankAccount.withdraw(350.00, true); assertEquals(550.00, bankAccount.getBalance(), 0); } @Test void isChecking() { assertTrue(bankAccount.isChecking()); } }
25.446429
89
0.647018
e282c41578d341e46cf4a0d32bb55a96f96ef419
17,520
/** * 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 com.chinamobile.bcbsp.fault.browse; import java.util.*; import com.chinamobile.bcbsp.fault.browse.MessageService; import com.chinamobile.bcbsp.fault.storage.Fault; /** * get and set the page information and get * the page information in html. * @author hadoop * */ public class PageService { /**default pagenum*/ private int pageNumber = 1; /**fault type*/ private String type; /**fault level*/ private String level; /**fault time*/ private String time; /**fault happened worker*/ private String worker; /**fault specific key*/ private String key; /**fault happened month?*/ private String month; /** * get fault month * @return month information. */ public String getMonth() { return month; } /** * set the month information * @param month * month to set. */ public void setMonth(String month) { if (month == null) { this.month = ""; } else if (month.equals("null")) { this.month = ""; } else { this.month = month; } } /** * get fault level. * @return fault level */ public String getLevel() { return level; } /** * set fault level * @param level * fault level to set. */ public void setLevel(String level) { this.level = level; } /** * get fault happen time * @return * fault happen time */ public String getTime() { return time; } /** * set fault happened time * @param time * fault hadppened to set. */ public void setTime(String time) { if (time == null) { this.time = ""; } else if (time.equals("null")) { this.time = ""; } else { this.time = time; } } /** * get fault happened worker * @return fault happened worker */ public String getWorker() { return worker; } /** * set fault happened worker * @param worker * fault happened worker */ public void setWorker(String worker) { if (worker == null) { this.worker = ""; } else if (worker.equals("null")) { this.worker = ""; } else { this.worker = worker; } } /** * fault specific key * @return fault specific key */ public String getKey() { return key; } /** * set fault specific key * @param key * fault key to be set. */ public void setKey(String key) { if (key == null) { this.key = ""; } else if (key.equals("null")) { this.key = ""; } else { this.key = key; } } /** * get fault type * @return fault type */ public String getType() { return type; } /** * set fault type * @param type * fault type to be set. */ public void setType(String type) { this.type = type; } /** * set pageNum * @param pageNumber * pagenum to be set. */ public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } /** * get the pageNum * @return page num */ public int getPageNumber() { return this.pageNumber; } /** * get the page into html which contains the fault information get from page * according to type * @param path * fault storagepath ? * @return html in string */ public String getPageByType(String path) { MessageService service = new MessageService(); String monthNum = getMonth(); List<Fault> res; if (monthNum == null || monthNum.equals("") || monthNum.equals("null")) { res = service.getPageByType(pageNumber, type); } else { int month = Integer.valueOf(monthNum); if (month < 0 || month > 20) { res = service.getPageByType(pageNumber, type); } else { res = service.getPageByType(pageNumber, type, month); } } StringBuffer html = new StringBuffer(); html.append("<font size = '3' >"); html.append("<table frame = 'box' >"); html.append("<tr><td width='59' bgcolor='#78A5D1'>TIME</td><td width='59'" + "bgcolor='#78A5D1'>TYPE</td><td width='59'" + "bgcolor='#78A5D1'>LEVEL</td><td width='59'" + "bgcolor='#78A5D1'>WORKER</td>"); html.append("<td width='59' bgcolor='#78A5D1'>JOBNAME</td><td width='59'" + "bgcolor='#78A5D1'>STAFFNAME</td><td width='59'" + "bgcolor='#78A5D1'>STATUS</td><td width='59'" + "bgcolor='#78A5D1'>EXCEPTIONMESSAGE</td></tr>"); if (res.size() == 0) { html.append("</table>"); html.append("<label>no such records</label>"); html.append("</font>"); return html.toString(); } for (int i = 0; i < res.size(); i++) { Fault fault = res.get(i); html.append("<tr>"); html.append("<td>" + fault.getTimeOfFailure() + "</td>"); html.append("<td>" + fault.getType() + "</td>"); html.append("<td>" + fault.getLevel() + "</td>"); html.append("<td>" + fault.getWorkerNodeName() + "</td>"); html.append("<td>" + fault.getJobName() + "</td>"); html.append("<td>" + fault.getStaffName() + "</td>"); html.append("<td>" + fault.isFaultStatus() + "</td>"); html.append("<td>" + fault.getExceptionMessage() + "</td>"); html.append("</tr>"); } int totalPages = service.getTotalPages(); html.append("<tr>"); if (pageNumber <= 1) { html.append("<td>first page</td>"); html.append("<td>previous page</td>"); html.append("<td><a href='" + path + "?pageNumber=" + 2 + "&type=" + getType() + "&month=" + getMonth() + "'>next page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + totalPages + "&type=" + getType() + "&month=" + getMonth() + "'>last page</a></td>"); } else if (pageNumber > 1 && pageNumber < totalPages) { html.append("<td><a href='" + path + "?pageNumber=" + 1 + "&type=" + getType() + "&month=" + getMonth() + "'>first page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber - 1) + "&type=" + getType() + "&month=" + getMonth() + "'>previous page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber + 1) + "&type=" + getType() + "&month=" + getMonth() + "'>next page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + totalPages + "&type=" + getType() + "&month=" + getMonth() + "'>last page</a></td>"); } else if (pageNumber == totalPages) { html.append("<td><a href='" + path + "?pageNumber=" + 1 + "&type=" + getType() + "&month=" + getMonth() + "'>first page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber - 1) + "&type=" + getType() + "&month=" + getMonth() + "'>previous page</a></td>"); html.append("<td>next page</td>"); html.append("<td>last page</td>"); } html.append("<td>currentPage " + pageNumber + "</td>"); html.append("<td>TotalPage " + totalPages + "</td>"); html.append("</tr>"); html.append("</table>"); html.append("</font>"); return html.toString(); } /** * get the page into html which contains the fault information get from page * according to type * @param path * fault storagepath ? * @return html in string */ public String getPageBykey(String path) { MessageService service = new MessageService(); String monthNum = getMonth(); List<Fault> res; if (monthNum == null || monthNum.equals("") || monthNum.equals("null")) { res = service.getPageByKey(pageNumber, key); } else { int month = Integer.valueOf(monthNum); if (month < 0 || month > 20) { res = service.getPageByKey(pageNumber, key); } else { res = service.getPageByKey(pageNumber, key, month); } } StringBuffer html = new StringBuffer(); html.append("<font size = '3' >"); html.append("<table frame = 'box' >"); html.append("<tr><td width='59' bgcolor='#78A5D1'>TIME</td><td width='59'" + "bgcolor='#78A5D1'>TYPE</td><td width='59'" + "bgcolor='#78A5D1'>LEVEL</td><td width='59'" + "bgcolor='#78A5D1'>WORKER</td>"); html.append("<td width='59' bgcolor='#78A5D1'>JOBNAME</td><td width='59'" + "bgcolor='#78A5D1'>STAFFNAME</td><td width='59'" + "bgcolor='#78A5D1'>STATUS</td><td width='59'" + "bgcolor='#78A5D1'>EXCEPTIONMESSAGE</td></tr>"); if (res.size() == 0) { html.append("</table>"); html.append("<label>no such records</label>"); html.append("</font>"); return html.toString(); } for (int i = 0; i < res.size(); i++) { Fault fault = res.get(i); html.append("<tr>"); html.append("<td>" + fault.getTimeOfFailure() + "</td>"); html.append("<td>" + fault.getType() + "</td>"); html.append("<td>" + fault.getLevel() + "</td>"); html.append("<td>" + fault.getWorkerNodeName() + "</td>"); html.append("<td>" + fault.getJobName() + "</td>"); html.append("<td>" + fault.getStaffName() + "</td>"); html.append("<td>" + fault.isFaultStatus() + "</td>"); html.append("<td>" + fault.getExceptionMessage() + "</td>"); html.append("</tr>"); } int totalPages = service.getTotalPages(); html.append("<tr>"); if (pageNumber <= 1) { html.append("<td>first page</td>"); html.append("<td>previous page</td>"); html.append("<td><a href='" + path + "?pageNumber=" + 2 + "&key=" + getKey() + "&month=" + getMonth() + "'>next page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + totalPages + "&key=" + getKey() + "&month=" + getMonth() + "'>last page</a></td>"); } else if (pageNumber > 1 && pageNumber < totalPages) { html.append("<td><a href='" + path + "?pageNumber=" + 1 + "&key=" + getKey() + "&month=" + getMonth() + "'>first page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber - 1) + "&key=" + getKey() + "&month=" + getMonth() + "'>previous page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber + 1) + "&key=" + getKey() + "&month=" + getMonth() + "'>next page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + totalPages + "&key=" + getKey() + "&month=" + getMonth() + "'>last page</a></td>"); } else if (pageNumber == totalPages) { html.append("<td><a href='" + path + "?pageNumber=" + 1 + "&key=" + getKey() + "&month=" + getMonth() + "'>first page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber - 1) + "&key=" + getKey() + "&month=" + getMonth() + "'>previous page</a></td>"); html.append("<td>next page</td>"); html.append("<td>last page</td>"); } html.append("<td>currentPage " + pageNumber + "</td>"); html.append("<td>TotalPage " + totalPages + "</td>"); html.append("</tr>"); html.append("</table>"); html.append("</font>"); return html.toString(); } /** * get the first page into html. * @return first page html information. */ public String getFirstPage() { StringBuffer html = new StringBuffer(); html.append("<font size = '3' >"); html.append("<table frame = 'box' >"); html.append("<tr><td width='59' bgcolor='#78A5D1'>TIME</td><td width='59'" + "bgcolor='#78A5D1'>TYPE</td><td width='59'" + "bgcolor='#78A5D1'>LEVEL</td><td width='59'" + "bgcolor='#78A5D1'>WORKER</td>"); html.append("<td width='59' bgcolor='#78A5D1'>JOBNAME</td><td width='59'" + "bgcolor='#78A5D1'>STAFFNAME</td><td width='59'" + "bgcolor='#78A5D1'>STATUS</td><td width='59'" + "bgcolor='#78A5D1'>EXCEPTIONMESSAGE</td></tr>"); html.append("</table>"); html.append("</font>"); return html.toString(); } /** * get the page into html which contains the fault information get from page * according to key * @param path * fault storagepath ? * @return html in string */ public String getPageByKeys(String path) { String[] keys = {getType(), getTime(), getLevel(), getWorker()}; MessageService service = new MessageService(); String monthNum = getMonth(); List<Fault> res; if (monthNum == null || monthNum.equals("") || monthNum.equals("null")) { res = service.getPageByKeys(pageNumber, keys); } else { int month = Integer.valueOf(monthNum); if (month < 0 || month > 20) { res = service.getPageByKeys(pageNumber, keys); } else { res = service.getPageByKeys(pageNumber, keys, month); } } StringBuffer html = new StringBuffer(); html.append("<font size = '3' >"); html.append("<table frame = 'box' >"); html.append("<tr><td width='59' bgcolor='#78A5D1'>TIME</td><td width='59'" + "bgcolor='#78A5D1'>TYPE</td><td width='59'" + "bgcolor='#78A5D1'>LEVEL</td><td width='59'" + "bgcolor='#78A5D1'>WORKER</td>"); html.append("<td width='59' bgcolor='#78A5D1'>JOBNAME</td><td width='59'" + "bgcolor='#78A5D1'>STAFFNAME</td><td width='59'" + "bgcolor='#78A5D1'>STATUS</td><td width='59'" + "bgcolor='#78A5D1'>EXCEPTIONMESSAGE</td></tr>"); if (res.size() == 0) { html.append("</table>"); html.append("<label>no such records</label>"); html.append("</font>"); return html.toString(); } for (int i = 0; i < res.size(); i++) { Fault fault = res.get(i); html.append("<tr>"); html.append("<td>" + fault.getTimeOfFailure() + "</td>"); html.append("<td>" + fault.getType() + "</td>"); html.append("<td>" + fault.getLevel() + "</td>"); html.append("<td>" + fault.getWorkerNodeName() + "</td>"); html.append("<td>" + fault.getJobName() + "</td>"); html.append("<td>" + fault.getStaffName() + "</td>"); html.append("<td>" + fault.isFaultStatus() + "</td>"); html.append("<td>" + fault.getExceptionMessage() + "</td>"); html.append("</tr>"); } int totalPages = service.getTotalPages(); html.append("<tr>"); if (pageNumber <= 1) { html.append("<td>first page</td>"); html.append("<td>previous page</td>"); html.append("<td><a href='" + path + "?pageNumber=" + 2 + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>next page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + totalPages + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>last page</a></td>"); } else if (pageNumber > 1 && pageNumber < totalPages) { html.append("<td><a href='" + path + "?pageNumber=" + 1 + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>first page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber - 1) + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>previous page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber + 1) + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>next page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + totalPages + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>last page</a></td>"); } else if (pageNumber == totalPages) { html.append("<td><a href='" + path + "?pageNumber=" + 1 + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>first page</a></td>"); html.append("<td><a href='" + path + "?pageNumber=" + (pageNumber - 1) + "&type=" + getType() + "&level=" + getLevel() + "&time=" + getTime() + "&worker=" + getWorker() + "&month=" + getMonth() + "'>previous page</a></td>"); html.append("<td>next page</td>"); html.append("<td>last page</td>"); } html.append("<td>currentPage " + pageNumber + "</td>"); html.append("<td>TotalPage " + totalPages + "</td>"); html.append("</tr>"); html.append("</table>"); html.append("</font>"); return html.toString(); } }
35.609756
80
0.542694
e38c1f42edea3ed2681275cb3cac02cb2678bc6e
3,872
package com.faforever.client.game; import com.faforever.client.i18n.I18n; import com.faforever.client.notification.ImmediateNotification; import com.faforever.client.notification.NotificationService; import com.faforever.client.notification.Severity; import com.faforever.client.preferences.PreferencesService; import com.faforever.client.preferences.event.MissingGamePathEvent; import com.faforever.client.ui.preferences.event.GameDirectoryChosenEvent; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.lang.invoke.MethodHandles; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; @Component public class GamePathHandler { private static final Collection<Path> USUAL_GAME_PATHS = Arrays.asList( Paths.get(System.getenv("ProgramFiles") + "\\THQ\\Gas Powered Games\\Supreme Commander - Forged Alliance"), Paths.get(System.getenv("ProgramFiles") + " (x86)\\THQ\\Gas Powered Games\\Supreme Commander - Forged Alliance"), Paths.get(System.getenv("ProgramFiles") + "\\Steam\\steamapps\\common\\supreme commander forged alliance"), Paths.get(System.getenv("ProgramFiles") + "\\Supreme Commander - Forged Alliance") ); private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final NotificationService notificationService; private final I18n i18n; private final EventBus eventBus; private final PreferencesService preferencesService; public GamePathHandler(NotificationService notificationService, I18n i18n, EventBus eventBus, PreferencesService preferencesService) { this.notificationService = notificationService; this.i18n = i18n; this.eventBus = eventBus; this.preferencesService = preferencesService; } @PostConstruct public void postConstruct() { eventBus.register(this); } /** * Checks whether the chosen game path contains a ForgedAlliance.exe (either directly if the user selected the "bin" * directory, or in the "bin" sub folder). If the path is valid, it is stored in the preferences. */ @Subscribe public void onGameDirectoryChosenEvent(GameDirectoryChosenEvent event) { Path path = event.getPath(); if (path == null || !Files.isDirectory(path)) { notificationService.addNotification(new ImmediateNotification(i18n.get("gameChosen.invalidPath"), i18n.get("gameChosen.couldNotLocatedGame"), Severity.WARN)); return; } if (!Files.isRegularFile(path.resolve(PreferencesService.FORGED_ALLIANCE_EXE)) && !Files.isRegularFile(path.resolve(PreferencesService.SUPREME_COMMANDER_EXE))) { onGameDirectoryChosenEvent(new GameDirectoryChosenEvent(path.resolve("bin"))); return; } // At this point, path points to the "bin" directory Path gamePath = path.getParent(); logger.info("Found game path at {}", gamePath); preferencesService.getPreferences().getForgedAlliance().setPath(gamePath); preferencesService.storeInBackground(); } private void detectGamePath() { for (Path path : USUAL_GAME_PATHS) { if (preferencesService.isGamePathValid(path.resolve("bin"))) { onGameDirectoryChosenEvent(new GameDirectoryChosenEvent(path)); return; } } logger.info("Game path could not be detected"); eventBus.post(new MissingGamePathEvent()); } public void detectAndUpdateGamePath() { Path faPath = preferencesService.getPreferences().getForgedAlliance().getPath(); if (faPath == null || Files.notExists(faPath)) { logger.info("Game path is not specified or non-existent, trying to detect"); detectGamePath(); } } }
39.510204
165
0.755682
899c2340a0f22cf6b272684e06ac6a1417baa827
2,332
/* * Copyright 2018 Akashic Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.zhihexireng.node; import dev.zhihexireng.core.NodeManager; import dev.zhihexireng.core.exception.NotValidateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; @Component @EnableScheduling class NodeScheduler { private static final Logger log = LoggerFactory.getLogger(NodeScheduler.class); private static final int BLOCK_MINE_SEC = 10; private final Queue<String> nodeQueue = new LinkedBlockingQueue<>(); private final MessageSender messageSender; private final NodeManager nodeManager; @Autowired public NodeScheduler(MessageSender messageSender, NodeManager nodeManager) { this.messageSender = messageSender; this.nodeManager = nodeManager; } @Scheduled(fixedRate = 1000 * 10) public void ping() { messageSender.ping(); } @Scheduled(initialDelay = 1000 * 5, fixedRate = 1000 * BLOCK_MINE_SEC) public void generateBlock() throws IOException, NotValidateException { if (nodeQueue.isEmpty()) { nodeQueue.addAll(nodeManager.getPeerUriList()); } String peerId = nodeQueue.poll(); assert peerId != null; if (peerId.equals(nodeManager.getNodeUri())) { nodeManager.generateBlock(); } else { log.debug("Skip generation by another " + peerId.substring(peerId.lastIndexOf("@"))); } } }
32.84507
97
0.728988
bbd5ab5b41a02a0713a59569a1a1312afd61b3e9
250
package ocp.bad; public class Rectangle { final double height; final double width; Rectangle(double height, double width) { this.height = height; this.width = width; } public double area() { return height * width; } }
14.705882
42
0.644
6412c63f6ae514c8758cb143dff7470012bb8129
1,354
package org.tests.delete; import io.ebean.xtest.BaseTestCase; import io.ebean.DB; import io.ebean.test.LoggedSql; import org.junit.jupiter.api.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class TestDeleteCascadeWithListener extends BaseTestCase { @Test public void test() { DcMaster m0 = new DcMaster("m0"); m0.getDetails().add(new DcDetail()); m0.getDetails().add(new DcDetail()); m0.getDetails().add(new DcDetail()); DB.save(m0); DcMaster found = DB.find(DcMaster.class, m0.getId()); LoggedSql.start(); DB.delete(found); List<String> sql = LoggedSql.stop(); if (isPersistBatchOnCascade()) { assertThat(sql).hasSize(6); assertSql(sql.get(0)).contains("select t0.id from dc_detail t0 where master_id=?"); assertSql(sql.get(1)).contains("delete from dc_detail where id=?"); assertSqlBind(sql, 2, 4); assertThat(sql.get(5)).contains("delete from dc_master where id=? and version=?"); } awaitListenerPropagation(); List<Object> beans = DcListener.deletedBeans(); assertThat(beans).hasSize(3); } private void awaitListenerPropagation() { try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } }
26.038462
89
0.677991
718120a6952c93a862530d5ee416b465564ba3df
3,073
/* * 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.kafka.streams.processor.internals; import org.apache.kafka.clients.producer.MockProducer; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.serialization.Serializer; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.errors.StreamsException; import org.apache.kafka.streams.state.StateSerdes; import org.apache.kafka.test.MockProcessorContext; import org.junit.Test; import java.util.Properties; public class SinkNodeTest { @Test(expected = StreamsException.class) @SuppressWarnings("unchecked") public void invalidInputRecordTimestampTest() { final Serializer anySerializer = Serdes.Bytes().serializer(); final StateSerdes anyStateSerde = StateSerdes.withBuiltinTypes("anyName", Bytes.class, Bytes.class); final MockProcessorContext context = new MockProcessorContext(anyStateSerde, new RecordCollectorImpl(null, null)); context.setTime(-1); final SinkNode sink = new SinkNode<>("name", "output-topic", anySerializer, anySerializer, null); sink.init(context); sink.process(null, null); } @Test(expected = StreamsException.class) @SuppressWarnings("unchecked") public void shouldThrowStreamsExceptionOnKeyValyeTypeSerializerMissmatch() { final Serializer anySerializer = Serdes.Bytes().serializer(); final StateSerdes anyStateSerde = StateSerdes.withBuiltinTypes("anyName", Bytes.class, Bytes.class); Properties config = new Properties(); config.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); final MockProcessorContext context = new MockProcessorContext(anyStateSerde, new RecordCollectorImpl(new MockProducer<byte[], byte[]>(true, anySerializer, anySerializer), null)); context.setTime(0); final SinkNode sink = new SinkNode<>("name", "output-topic", anySerializer, anySerializer, null); sink.init(context); try { sink.process("", ""); } catch (final StreamsException e) { if (e.getCause() instanceof ClassCastException) { throw e; } throw new RuntimeException(e); } } }
42.680556
186
0.728604
760f6b099b9073d52674bd6e203860d1dfd90c1d
6,626
/* * Copyright 2016 - 2020 Anton Tananaev ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.database; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.helper.DateUtil; import org.traccar.model.Statistics; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import java.sql.SQLException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; public class StatisticsManager { private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsManager.class); private static final int SPLIT_MODE = Calendar.DAY_OF_MONTH; private final Config config; private final DataManager dataManager; private final Client client; private final ObjectMapper objectMapper; private final AtomicInteger lastUpdate = new AtomicInteger(Calendar.getInstance().get(SPLIT_MODE)); private final Set<Long> users = new HashSet<>(); private final Map<Long, String> deviceProtocols = new HashMap<>(); private int requests; private int messagesReceived; private int messagesStored; private int mailSent; private int smsSent; private int geocoderRequests; private int geolocationRequests; @Inject public StatisticsManager(Config config, DataManager dataManager, Client client, ObjectMapper objectMapper) { this.config = config; this.dataManager = dataManager; this.client = client; this.objectMapper = objectMapper; } private void checkSplit() { int currentUpdate = Calendar.getInstance().get(SPLIT_MODE); if (lastUpdate.getAndSet(currentUpdate) != currentUpdate) { Statistics statistics = new Statistics(); synchronized (this) { statistics.setCaptureTime(new Date()); statistics.setActiveUsers(users.size()); statistics.setActiveDevices(deviceProtocols.size()); statistics.setRequests(requests); statistics.setMessagesReceived(messagesReceived); statistics.setMessagesStored(messagesStored); statistics.setMailSent(mailSent); statistics.setSmsSent(smsSent); statistics.setGeocoderRequests(geocoderRequests); statistics.setGeolocationRequests(geolocationRequests); if (!deviceProtocols.isEmpty()) { Map<String, Integer> protocols = new HashMap<>(); for (String protocol : deviceProtocols.values()) { protocols.compute(protocol, (key, count) -> count != null ? count + 1 : 1); } statistics.setProtocols(protocols); } users.clear(); deviceProtocols.clear(); requests = 0; messagesReceived = 0; messagesStored = 0; mailSent = 0; smsSent = 0; geocoderRequests = 0; geolocationRequests = 0; } try { dataManager.addObject(statistics); } catch (SQLException e) { LOGGER.warn("Error saving statistics", e); } String url = config.getString(Keys.SERVER_STATISTICS); if (url != null) { String time = DateUtil.formatDate(statistics.getCaptureTime()); Form form = new Form(); form.param("version", getClass().getPackage().getImplementationVersion()); form.param("captureTime", time); form.param("activeUsers", String.valueOf(statistics.getActiveUsers())); form.param("activeDevices", String.valueOf(statistics.getActiveDevices())); form.param("requests", String.valueOf(statistics.getRequests())); form.param("messagesReceived", String.valueOf(statistics.getMessagesReceived())); form.param("messagesStored", String.valueOf(statistics.getMessagesStored())); form.param("mailSent", String.valueOf(statistics.getMailSent())); form.param("smsSent", String.valueOf(statistics.getSmsSent())); form.param("geocoderRequests", String.valueOf(statistics.getGeocoderRequests())); form.param("geolocationRequests", String.valueOf(statistics.getGeolocationRequests())); if (statistics.getProtocols() != null) { try { form.param("protocols", objectMapper.writeValueAsString(statistics.getProtocols())); } catch (JsonProcessingException e) { LOGGER.warn("Failed to serialize protocols", e); } } client.target(url).request().async().post(Entity.form(form)); } } } public synchronized void registerRequest(long userId) { checkSplit(); requests += 1; if (userId != 0) { users.add(userId); } } public synchronized void registerMessageReceived() { checkSplit(); messagesReceived += 1; } public synchronized void registerMessageStored(long deviceId, String protocol) { checkSplit(); messagesStored += 1; if (deviceId != 0) { deviceProtocols.put(deviceId, protocol); } } public synchronized void registerMail() { checkSplit(); mailSent += 1; } public synchronized void registerSms() { checkSplit(); smsSent += 1; } public synchronized void registerGeocoderRequest() { checkSplit(); geocoderRequests += 1; } public synchronized void registerGeolocationRequest() { checkSplit(); geolocationRequests += 1; } }
37.01676
112
0.624962
0971e732f08e6dfd6d2b8f463436dbac5ebff93d
2,460
package com.neueda.jetbrains.plugin.graphdb.jetbrains.ui.console.table.renderer; import com.intellij.ui.treeStructure.Tree; import com.neueda.jetbrains.plugin.graphdb.jetbrains.ui.helpers.SerialisationHelper; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Arrays; import java.util.List; public class CompositeTableCellRenderer implements TableCellRenderer { private final TreeModelTableCellRenderer treeModelTableCellRenderer; private final DefaultTableCellRenderer defaultTableCellRenderer; public CompositeTableCellRenderer() { defaultTableCellRenderer = new DefaultTableCellRenderer(); defaultTableCellRenderer.setVerticalAlignment(SwingConstants.TOP); treeModelTableCellRenderer = new TreeModelTableCellRenderer(); } private static final KeyAdapter COPY_KEY_ADAPTER = new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.isControlDown()) { if (e.getKeyCode() == KeyEvent.VK_C) { // Copy List<TreePath> v = Arrays.asList(((Tree) e.getComponent()).getSelectionModel().getSelectionPaths()); String str = SerialisationHelper.convertToCsv(v); StringSelection selection = new StringSelection(str); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); } } } }; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value instanceof Tree) { Component component = treeModelTableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (Arrays.stream(((Tree) value).getKeyListeners()).noneMatch(o -> o.equals(COPY_KEY_ADAPTER))) { ((Tree) value).addKeyListener(COPY_KEY_ADAPTER); } return component; } return defaultTableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } }
42.413793
140
0.70935
5592f5160f1d21c35b9bae7a1073a419eb1ff8db
1,068
package by.homesite.gator.service; import by.homesite.gator.service.dto.RateDTO; import java.util.List; import java.util.Optional; /** * Service Interface for managing {@link by.homesite.gator.domain.Rate}. */ public interface RateService { /** * Save a rate. * * @param rateDTO the entity to save. * @return the persisted entity. */ RateDTO save(RateDTO rateDTO); /** * Partially updates a rate. * * @param rateDTO the entity to update partially. * @return the persisted entity. */ Optional<RateDTO> partialUpdate(RateDTO rateDTO); /** * Get all the rates. * * @return the list of entities. */ List<RateDTO> findAll(); /** * Get the "id" rate. * * @param id the id of the entity. * @return the entity. */ Optional<RateDTO> findOne(Long id); Optional<RateDTO> findByCode(String code); /** * Delete the "id" rate. * * @param id the id of the entity. */ void delete(Long id); void fetchRates(); }
20.150943
72
0.594569
ba9a244dca408ce863ae971545b795a243d7d87a
311
package com.datasaver.api.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.datasaver.api.domains.DeviceBatteryLog; @Repository public interface DeviceBatteryLogRepository extends JpaRepository<DeviceBatteryLog, Long> { }
31.1
91
0.858521
626c516966bec6dd759912a90a009fb2d1684a91
703
package org.reflections.serializers; import com.google.common.collect.*; import java.lang.reflect.*; import com.google.gson.*; class JsonSerializer$2 implements JsonSerializer<Multimap> { final /* synthetic */ JsonSerializer this$0; JsonSerializer$2(final JsonSerializer a1) { this.this$0 = a1; super(); } @Override public JsonElement serialize(final Multimap a1, final Type a2, final JsonSerializationContext a3) { return a3.serialize(a1.asMap()); } @Override public /* bridge */ JsonElement serialize(final Object o, final Type a2, final JsonSerializationContext a3) { return this.serialize((Multimap)o, a2, a3); } }
29.291667
113
0.679943
432f3dc0c81b472357169f2272a9d997303d1214
779
package dao; import db.DB; import org.junit.rules.ExternalResource; import org.sql2o.*; public class DatabaseRule extends ExternalResource{ @Override public void before(){ DB.sql2o = new Sql2o("jdbc:postgresql://localhost:5432/news_portal_test", "sitati", "Access"); } @Override public void after(){ try(Connection conn = DB.sql2o.open()){ String deleteUserQuery = "DELETE FROM users"; String deleteDepartmentsQuery = "DELETE FROM departments"; String deleteNewsQuery = "DELETE FROM news"; conn.createQuery(deleteUserQuery).executeUpdate(); conn.createQuery(deleteDepartmentsQuery).executeUpdate(); conn.createQuery(deleteNewsQuery).executeUpdate(); } } }
31.16
102
0.662388
398bfd75e5abb823651e3608246a38ffd3f58153
929
package com.sparta.eng82.stepdefs; import com.sparta.eng82.components.pages.HomePageImpl; import com.sparta.eng82.stepdefs.utility.Pages; import com.sparta.eng82.stepdefs.utility.WebDriverManager; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.junit.jupiter.api.Assertions; import org.openqa.selenium.chrome.ChromeDriver; public class AddToBasketStepdefs { @Given("I am on the home page") public void iAmOnTheHomePage() { WebDriverManager.driver = new ChromeDriver(); Pages.homePage = new HomePageImpl(WebDriverManager.driver); } @When("I add an item to the basket") public void iAddAnItemToTheBasket() { Pages.homePage.addItemToCart(); } @Then("I see an item in my basket") public void iSeeAnItemInMyBasket() { Assertions.assertTrue(((HomePageImpl) Pages.homePage).addToBasketStatus()); } }
30.966667
83
0.735199
05670f4a7aeeb7b6a08a11acc02f21eff2faf698
909
package me.ele.jarch.athena.util; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JacksonObjectMappers { // fix about parnew gc cost long time to scan string table private final static JsonFactory factory = new JsonFactory().disable(JsonFactory.Feature.INTERN_FIELD_NAMES); private final static ObjectMapper mapper; private final static ObjectMapper prettyMapper; static { mapper = new ObjectMapper(factory); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); prettyMapper = mapper.copy().configure(SerializationFeature.INDENT_OUTPUT, true); } public static ObjectMapper getMapper() { return mapper; } public static ObjectMapper getPrettyMapper() { return prettyMapper; } }
30.3
89
0.742574
fc0dc7a3e96efca87da5e9f2e65dfaa1f1cb40a8
4,849
package com.example.schedulemanager.CustomElements; import static android.graphics.Paint.Style.FILL; import static android.graphics.PorterDuff.Mode.CLEAR; import static androidx.core.content.ContextCompat.getColor; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuffXfermode; import android.util.AttributeSet; import android.util.Property; import android.view.View; import com.example.schedulemanager.R; import butterknife.ButterKnife; public class CircularRippleEffect extends View { private static final int ADDITIONAL_SIZE_TO_CLEAR_ANTIALIASING = 1; private Paint circlePaint = new Paint(); private Paint maskPaint = new Paint(); private Bitmap tempBitmap; private Canvas tempCanvas; private float outerCircleRadiusProgress = 0f; private float innerCircleRadiusProgress = 0f; private int maxCircleSize; private int rippleSize; public CircularRippleEffect(Context context) { super(context); init(); } public CircularRippleEffect(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CircularRippleEffect, 0, 0); try { rippleSize = typedArray.getDimensionPixelSize( R.styleable.CircularRippleEffect_rippleSize, 500); } finally { typedArray.recycle(); } init(); } public CircularRippleEffect(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { ButterKnife.bind(this); int dotColor = getColor(getContext(), R.color.colorPrimaryDark); circlePaint.setStyle(FILL); circlePaint.setAntiAlias(true); circlePaint.setColor(dotColor); maskPaint.setXfermode(new PorterDuffXfermode(CLEAR)); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); maxCircleSize = w / 2; tempBitmap = Bitmap.createBitmap(getWidth(), getWidth(), Bitmap.Config.ARGB_8888); tempCanvas = new Canvas(tempBitmap); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); tempCanvas.drawColor(Color.WHITE, CLEAR); tempCanvas.drawCircle(getWidth() / 2, getHeight() / 2, outerCircleRadiusProgress * maxCircleSize, circlePaint); tempCanvas.drawCircle(getWidth() / 2, getHeight() / 2, innerCircleRadiusProgress * (maxCircleSize + ADDITIONAL_SIZE_TO_CLEAR_ANTIALIASING), maskPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(rippleSize, rippleSize); } public void setInnerCircleRadiusProgress(float innerCircleRadiusProgress) { this.innerCircleRadiusProgress = innerCircleRadiusProgress; postInvalidate(); } public float getInnerCircleRadiusProgress() { return innerCircleRadiusProgress; } public void setOuterCircleRadiusProgress(float outerCircleRadiusProgress) { this.outerCircleRadiusProgress = outerCircleRadiusProgress; postInvalidate(); } public float getOuterCircleRadiusProgress() { return outerCircleRadiusProgress; } public static final Property<CircularRippleEffect, Float> INNER_CIRCLE_RADIUS_PROGRESS = new Property<CircularRippleEffect, Float>(Float.class, "innerCircleRadiusProgress") { @Override public Float get(CircularRippleEffect object) { return object.getInnerCircleRadiusProgress(); } @Override public void set(CircularRippleEffect object, Float value) { object.setInnerCircleRadiusProgress(value); } }; public static final Property<CircularRippleEffect, Float> OUTER_CIRCLE_RADIUS_PROGRESS = new Property<CircularRippleEffect, Float>(Float.class, "outerCircleRadiusProgress") { @Override public Float get(CircularRippleEffect object) { return object.getOuterCircleRadiusProgress(); } @Override public void set(CircularRippleEffect object, Float value) { object.setOuterCircleRadiusProgress(value); } }; }
34.390071
97
0.673541
9123cb23d7aa8c0a8e99671ee56bb77827519dc7
492
package com.tahn.quizapplicationv3.objectClass; public class WordNote { private String word; private String desc; public WordNote(String word, String desc) { this.word = word; this.desc = desc; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
17.571429
47
0.587398
c7d4322c3182c32a1a1a18c1ca67e7145334041a
1,851
package com.aptoide.amethyst.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.widget.Toast; import com.aptoide.amethyst.R; import com.aptoide.amethyst.preferences.SecurePreferences; import com.aptoide.amethyst.utils.AptoideUtils; import com.aptoide.amethyst.webservices.v2.AddApkCommentVoteRequest; import com.aptoide.amethyst.webservices.v2.AlmostGenericResponseV2RequestListener; import com.aptoide.dataprovider.webservices.json.GenericResponseV2; import com.aptoide.dataprovider.webservices.models.Defaults; import com.octo.android.robospice.request.listener.RequestListener; import com.aptoide.amethyst.callbacks.AddCommentVoteCallback; import com.aptoide.amethyst.fragments.store.LatestCommentsFragment; public class MoreCommentsActivity extends MoreActivity implements AddCommentVoteCallback { @Override protected Fragment getFragment(Bundle args) { Fragment fragment = LatestCommentsFragment.newInstance(args); fragment.setArguments(args); return fragment; } @Override protected String getScreenName() { return "All Comments"; } @Override public void voteComment(int commentId, AddApkCommentVoteRequest.CommentVote vote) { RequestListener<GenericResponseV2> commentRequestListener = new AlmostGenericResponseV2RequestListener() { @Override public void CaseOK() { Toast.makeText(MoreCommentsActivity.this, getString(R.string.vote_submitted), Toast.LENGTH_LONG).show(); } }; AptoideUtils.VoteUtils.voteComment( spiceManager, commentId, Defaults.DEFAULT_STORE_NAME, SecurePreferences.getInstance().getString("token", "empty"), commentRequestListener, vote); } }
35.596154
120
0.732577
b40b3159d1226b3d8e83696f1baf450e5196efb7
2,235
package am.jsl.listings.domain.reminder; import java.io.Serializable; /** * The transfer details domain object. * * @author hamlet */ public class ReminderTransfer implements Serializable { /** * The internal identifier */ private long id; /** * The reminder id */ private long reminderId; /** * The target account id */ private long targetAccountId; /** * The converted amount */ private double convertedAmount; /** * The exchange rate of currency which is used when calculated the convertedAmount */ private double rate; /** * Gets id. * * @return the id */ public long getId() { return id; } /** * Sets id. * * @param id the id */ public void setId(long id) { this.id = id; } /** * Gets reminder id. * * @return the reminder id */ public long getReminderId() { return reminderId; } /** * Sets reminder id. * * @param reminderId the reminder id */ public void setReminderId(long reminderId) { this.reminderId = reminderId; } /** * Gets target account id. * * @return the target account id */ public long getTargetAccountId() { return targetAccountId; } /** * Sets target account id. * * @param targetAccountId the target account id */ public void setTargetAccountId(long targetAccountId) { this.targetAccountId = targetAccountId; } /** * Gets converted amount. * * @return the converted amount */ public double getConvertedAmount() { return convertedAmount; } /** * Sets converted amount. * * @param convertedAmount the converted amount */ public void setConvertedAmount(double convertedAmount) { this.convertedAmount = convertedAmount; } /** * Gets rate. * * @return the rate */ public double getRate() { return rate; } /** * Sets rate. * * @param rate the rate */ public void setRate(double rate) { this.rate = rate; } }
17.738095
86
0.550783
00731b00aa218639b9e82c7e877a6f1f182a5c37
6,471
/** * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.thinkgem.jeesite.common.utils; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringEscapeUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.LocaleResolver; /** * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 * @author ThinkGem * @version 2013-05-22 */ public class StringUtils extends org.apache.commons.lang3.StringUtils { public static String lowerFirst(String str){ if(StringUtils.isBlank(str)) { return ""; } else { return str.substring(0,1).toLowerCase() + str.substring(1); } } public static String upperFirst(String str){ if(StringUtils.isBlank(str)) { return ""; } else { return str.substring(0,1).toUpperCase() + str.substring(1); } } /** * 替换掉HTML标签方法 */ public static String replaceHtml(String html) { if (isBlank(html)){ return ""; } String regEx = "<.+?>"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(html); String s = m.replaceAll(""); return s; } /** * 缩略字符串(不区分中英文字符) * @param str 目标字符串 * @param length 截取长度 * @return */ public static String abbr(String str, int length) { if (str == null) { return ""; } try { StringBuilder sb = new StringBuilder(); int currentLength = 0; for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) { currentLength += String.valueOf(c).getBytes("GBK").length; if (currentLength <= length - 3) { sb.append(c); } else { sb.append("..."); break; } } return sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } /** * 缩略字符串(替换html) * @param str 目标字符串 * @param length 截取长度 * @return */ public static String rabbr(String str, int length) { return abbr(replaceHtml(str), length); } /** * 转换为Double类型 */ public static Double toDouble(Object val){ if (val == null){ return 0D; } try { return Double.valueOf(trim(val.toString())); } catch (Exception e) { return 0D; } } /** * 转换为Float类型 */ public static Float toFloat(Object val){ return toDouble(val).floatValue(); } /** * 转换为Long类型 */ public static Long toLong(Object val){ return toDouble(val).longValue(); } /** * 转换为Integer类型 */ public static Integer toInteger(Object val){ return toLong(val).intValue(); } /** * 获得i18n字符串 */ public static String getMessage(String code, Object[] args) { LocaleResolver localLocaleResolver = SpringContextHolder.getBean(LocaleResolver.class); HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); Locale localLocale = localLocaleResolver.resolveLocale(request); return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale); } /** * 获得用户远程地址 */ public static String getRemoteAddr(HttpServletRequest request){ String remoteAddr = request.getHeader("X-Real-IP"); if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("X-Forwarded-For"); }else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("Proxy-Client-IP"); }else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("WL-Proxy-Client-IP"); } return remoteAddr != null ? remoteAddr : request.getRemoteAddr(); } /** * 根据标志以及标志的序号进行字符串切割,主要用于 类似于日期切割:2014-03-04-2015-04-06 切割成 2014-03-04 和 2015-04-06 * @param str * @param token 标志 * @param index 标志序号 * @return */ public static String[] splitWithTokenIndex(String str,String token,int index){ int target_index = 0; int temp_index = 0; String[] strArry = new String[2]; for(int i = 0 ; i < index ; i++){ temp_index = str.indexOf(token, temp_index+1); if(temp_index > target_index){ target_index = temp_index; }else{ break; } } if(target_index>0){ strArry[0] = str.substring(0, target_index); strArry[1] = str.substring(target_index+1, str.length()); } return strArry; } /** * 检查查询参数map中,是否全部为空 * @param param request中的参数map * @param keys 传入的key的数组 * @return */ public static boolean checkParameterIsAllBlank(Map<String,Object> param,String...keys){ for(String key : keys){ if(isNotBlank((String)param.get(key))){ return false; } } return true; } /** * 检测字符串是否为日期格式 * @param datestr * @return */ public static boolean isDate(String datestr){ if(null != DateUtils.parseDate(datestr)){ return true; } return false; } public static String createInSql(String incolumn,List<String> values){ StringBuffer result = new StringBuffer(); StringBuffer tmpStr = new StringBuffer(); int tmpLong = 50; int loopsize = values.size()/tmpLong; int looplastsize = values.size()%tmpLong; int subloopsize = 0; for(int j = 1 ; j <= loopsize ; j++){ tmpStr = new StringBuffer(); result.append(" or ").append(incolumn).append(" in ( "); subloopsize = j*tmpLong; for(int i = (j-1)*tmpLong ; i < subloopsize ; i ++){ tmpStr.append("'").append(values.get(i)).append("',"); } result.append(tmpStr.substring(0, tmpStr.length()-1)); result.append(" ) "); } tmpStr = new StringBuffer(); for(int i = loopsize*tmpLong ; i < values.size(); i ++){ tmpStr.append("'").append(values.get(i)).append("',"); } if(tmpStr.length() > 0){//判断是否有余下的 result.append(" or ").append(incolumn).append(" in ( "); result.append(tmpStr.substring(0, tmpStr.length()-1)); result.append(" ) "); } return result.toString().replaceFirst("or", "and"); } public static void main(String[] args){ Date date = DateUtils.parseDate("30"); System.out.println("11"); } }
25.678571
119
0.637769
7fda3409c762161f3d9da6c638ca87ec2dc99c3e
4,945
package com.jn.kiku.net; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.jn.kiku.net.retrofit.body.RetrofitBodyHelp; import com.jn.kiku.net.retrofit.callback.ProgressListener; import com.jn.kiku.net.retrofit.manager.IRetrofitManage; import com.jn.kiku.net.retrofit.manager.RetrofitManagerFactory; import java.io.File; import java.util.Map; import io.reactivex.Observable; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Author:Stevie.Chen Time:2019/8/6 * Class Comment:网络请求管理 */ public class RetrofitManage { private static RetrofitManage instance = null; private Retrofit mRetrofit = null; private String mBaseUrl; private RetrofitManage() { } public static synchronized RetrofitManage getInstance() { if (instance == null) instance = new RetrofitManage(); return instance; } /** * 初始化Retrofit * <p> * 请在Application中使用 * </P> * * @param BASE_URL 服务器域名地址 */ public void initRetrofit(String BASE_URL) { mBaseUrl = BASE_URL; } /** * 创建请求服务 * <p> * 用于普通请求 * </P> * * @param service Class<T> * @param <T> T * @return T */ public <T> T create(final Class<T> service) { if (mBaseUrl == null) throw new NullPointerException("BaseUrl is empty,please initRetrofit in Application"); if (mRetrofit == null) { IRetrofitManage iRetrofitManage = RetrofitManagerFactory.create(RetrofitManagerFactory.REQUEST, mBaseUrl, null); mRetrofit = iRetrofitManage.createRetrofit(); } return mRetrofit.create(service); } /** * 创建请求服务 * <p> * 用于普通请求 * </P> * * @param service Class<T> * @param <T> T * @return T */ public <T> T create(@NonNull String BASE_URL, final Class<T> service) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(service); } /** * 创建请求服务 * <p> * 用于下载 * </P> * * @param service Class<T> * @param <T> T * @param listener 进度监听器 * @return T */ public <T> T createDownload(final Class<T> service, ProgressListener listener) { if (mBaseUrl == null) throw new NullPointerException("BaseUrl is empty,please initRetrofit in Application"); IRetrofitManage iRetrofitManage = RetrofitManagerFactory.create(RetrofitManagerFactory.DOWNLOAD, mBaseUrl, listener); Retrofit retrofit = iRetrofitManage.createRetrofit(); return retrofit.create(service); } /** * 创建请求服务 * <p> * 用于上传 * </P> * * @param service Class<T> * @param <T> T * @param listener 进度监听器 * @return T */ public <T> T createUpload(final Class<T> service, ProgressListener listener) { if (mBaseUrl == null) throw new NullPointerException("BaseUrl is empty,please initRetrofit in Application"); IRetrofitManage iRetrofitManage = RetrofitManagerFactory.create(RetrofitManagerFactory.UPLOAD, mBaseUrl, listener); Retrofit retrofit = iRetrofitManage.createRetrofit(); return retrofit.create(service); } /** * 获取下载文件的Observable * * @param url 下载地址 * @param listener 进度监听器 * @return Observable<ResponseBody> */ public Observable<ResponseBody> getDownloadObservable(@NonNull String url, ProgressListener listener) { RetrofitApiService apiService = createDownload(RetrofitApiService.class, listener); return apiService.downloadFile(url); } /** * 获取上传单张图片的Observable * * @param url 上传地址 * @param fileParams 文件参数信息 * @return Observable<ResponseBody> */ public Observable<ResponseBody> getUploadObservable(@NonNull String url, @NonNull Map<String, File> fileParams) { return getUploadObservable(url, fileParams, null); } /** * 获取上传多张图片的Observable * * @param url String * @param fileParams Map<String, File> * @param params Map<String, String * @return Observable<ResponseBody> */ public Observable<ResponseBody> getUploadObservable(@NonNull String url, @NonNull Map<String, File> fileParams, @Nullable Map<String, String> params) { RequestBody requestBody = RetrofitBodyHelp.getFileUploadRequestBody(fileParams, params); RetrofitApiService apiService = create(RetrofitApiService.class); return apiService.uploadFile(url, requestBody); } }
29.789157
155
0.644489
1c61ee416811917db91a363f8a45620cf4bfae38
414
package com.shpun.mall.common.service; import com.shpun.mall.common.model.MallAdmin; /** * @Description: * @Author: sun * @Date: 2020/8/22 10:36 */ public interface MallAdminService { void deleteByPrimaryKey(Integer adminId); void insertSelective(MallAdmin record); MallAdmin selectByPrimaryKey(Integer adminId); void updateByPrimaryKeySelective(MallAdmin record); }
19.714286
56
0.707729
ccaf2eb232fa1efd84a251285bd9632558ee8954
663
package net.dodogang.plume.ash; import dev.architectury.injectables.annotations.ExpectPlatform; import java.nio.file.Path; public final class Environment { private Environment() {} @ExpectPlatform public static boolean isDevelopmentEnvironment() { throw new AssertionError(); } /** * Gets the platform during runtime. * Quilt will be supported in the future. * * @return the runtime platform */ @ExpectPlatform public static Platform getPlatform() { throw new AssertionError(); } @ExpectPlatform public static Path getConfigDir() { throw new AssertionError(); } }
21.387097
63
0.666667
45e6fad766e230a32939b88b1c17a34ce2fafdd2
10,195
package com.github.sulir.vcmapper.home; import com.github.sulir.vcmapper.base.CommandExecutor; import com.github.sulir.vcmapper.base.VoiceControlTest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests using sample commands controlling a smart home. * * The natural language sentences and method names represent a sample from * the Fluent Speech Commands dataset by Fluent.ai (used with permission). * Dataset: https://www.fluent.ai/research/fluent-speech-commands/. * License: http://fluent.ai:2052/Fluent_Speech_Commands_Public_License.pdf. */ @RunWith(MockitoJUnitRunner.class) public class SmartHomeTest extends VoiceControlTest { private final LightsService lightsService = mock(LightsService.class); private final MusicService musicService = mock(MusicService.class); private final ObjectBringerService objectBringerService = mock(ObjectBringerService.class); private final HeatingService heatingService = mock(HeatingService.class); private final VolumeService volumeService = mock(VolumeService.class); private final LanguageService languageService = mock(LanguageService.class); @Before public void setUp() { executor = new CommandExecutor(lightsService, musicService, objectBringerService, heatingService, volumeService, languageService); } @Test public void activateLightsBedroom1() { execute("Lights on in the bedroom"); verify(lightsService).turnLightsOn(Room.BEDROOM); } @Test public void activateLightsBedroom2() { execute("Switch on the lights in the bedroom"); verify(lightsService).turnLightsOn(Room.BEDROOM); } @Test public void activateLightsBedroom3() { execute("Turn on the lights in the bedroom"); verify(lightsService).turnLightsOn(Room.BEDROOM); } @Test public void activateLightsKitchen() { execute("Turn the lights on in the kitchen"); verify(lightsService).turnLightsOn(Room.KITCHEN); } @Test public void activateLightsWashroom1() { execute("Washroom lights on"); verify(lightsService).turnLightsOn(Room.WASHROOM); } // enum-local synonym needed @Test public void activateLightsWashroom2() { execute("Switch on the bathroom lights"); verify(lightsService).turnLightsOn(Room.WASHROOM); } @Test public void activateLightsWashroom3() { execute("Switch on the washroom lights"); verify(lightsService).turnLightsOn(Room.WASHROOM); } @Test public void activateMusicNone() { execute("Start the music"); verify(musicService).start(); } // synonyms should be definable in any direction // stemming of sentence vs. parameter words @Test public void bringNewspaperNone() { execute("Get me the newspaper"); verify(objectBringerService).bring("newspaper"); } @Test public void deactivateLampNone() { execute("Lamp off"); verify(lightsService).turnLampOff(); } @Test public void deactivateLightsKitchen() { execute("Turn the lights off in the kitchen"); verify(lightsService).turnLightsOff(Room.KITCHEN); } @Test public void deactivateMusicNone() { execute("Stop music"); verify(musicService).stop(); } // multi-word synonyms required @Test public void decreaseHeatBedroom() { execute("Turn the temperature in the bedroom down"); verify(heatingService).decreaseTemperature(Room.BEDROOM); } @Test public void decreaseHeatKitchen1() { execute("Turn down the temperature in the kitchen"); verify(heatingService).decreaseTemperature(Room.KITCHEN); } @Test public void decreaseHeatKitchen2() { execute("Decrease the temperature in the kitchen"); verify(heatingService).decreaseTemperature(Room.KITCHEN); } @Test public void decreaseHeatKitchen3() { execute("Turn the heat down in the kitchen"); verify(heatingService).decreaseTemperature(Room.KITCHEN); } @Test public void decreaseHeatNone1() { execute("Heat down"); verify(heatingService).decreaseTemperature(); } // the sentence is completely different than the other ones - fallback could be a better fit than synonyms // "decrease" and "cooler" are not synonyms in the traditional sense @Test public void decreaseHeatNone2() { execute("Make it cooler"); verify(heatingService).decreaseTemperature(); } @Test public void decreaseHeatNone3() { execute("Decrease the heating"); verify(heatingService).decreaseTemperature(); } @Test public void decreaseHeatNone4() { execute("Decrease the temperature"); verify(heatingService).decreaseTemperature(); } @Test public void decreaseHeatNone5() { execute("Turn the heat down"); verify(heatingService).decreaseTemperature(); } @Test public void decreaseHeatWashroom1() { execute("Turn the heat down in the washroom"); verify(heatingService).decreaseTemperature(Room.WASHROOM); } @Test public void decreaseHeatWashroom2() { execute("Decrease the heating in the bathroom"); verify(heatingService).decreaseTemperature(Room.WASHROOM); } @Test public void decreaseHeatWashroom3() { execute("Turn the heat down in the bathroom"); verify(heatingService).decreaseTemperature(Room.WASHROOM); } // again - a too different sentence, synonyms not ideal @Test public void decreaseVolumeNone1() { execute("Make it quieter"); verify(volumeService).decrease(); } // the first part of the sentence is redundant, could be removed @Test public void decreaseVolumeNone2() { execute("It's too loud, turn the volume down"); verify(volumeService).decrease(); } @Test public void decreaseVolumeNone3() { execute("Decrease volume"); verify(volumeService).decrease(); } @Test public void decreaseVolumeNone4() { execute("Turn down the volume"); verify(volumeService).decrease(); } @Test public void decreaseVolumeNone5() { execute("Lower the volume"); verify(volumeService).decrease(); } @Test public void decreaseVolumeNone6() { execute("Decrease audio volume"); verify(volumeService).decrease(); } // fallback + word analysis for the same method required @Test public void decreaseVolumeNone7() { execute("That's too loud"); verify(volumeService).decrease(); } @Test public void changeLanguageEnglishNone() { execute("Set my phone's language to English"); verify(languageService).setLanguage(Language.ENGLISH); } // the argument ensures the correct result despite many redundant words @Test public void changeLanguageGermanNone() { execute("I need to practice my German. Switch the language"); verify(languageService).setLanguage(Language.GERMAN); } @Test public void changeLanguageChineseNone() { execute("I need to practice my Chinese. Switch the language"); verify(languageService).setLanguage(Language.CHINESE); } @Test public void changeLanguageKoreanNone() { execute("OK now switch the main language to Korean"); verify(languageService).setLanguage(Language.KOREAN); } @Test public void changeLanguageNoneNone1() { execute("Switch the language"); verify(languageService).switchLanguage(); } @Test public void changeLanguageNoneNone2() { execute("Set the language"); verify(languageService).switchLanguage(); } // synonym "settings"-"switch" was not necessary (settings -> set), but it would be a strange synonym @Test public void changeLanguageNoneNone3() { execute("Language settings"); verify(languageService).switchLanguage(); } @Test public void increaseHeatKitchen() { execute("Kitchen heat up"); verify(heatingService).increaseTemperature(Room.KITCHEN); } @Test public void increaseHeatNone1() { execute("Increase the temperature"); verify(heatingService).increaseTemperature(); } @Test public void increaseHeatNone2() { execute("Turn the temperature up"); verify(heatingService).increaseTemperature(); } @Test public void increaseHeatWashroom1() { execute("Turn up the heat in the washroom"); verify(heatingService).increaseTemperature(Room.WASHROOM); } @Test public void increaseHeatWashroom2() { execute("Turn up the bathroom temperature"); verify(heatingService).increaseTemperature(Room.WASHROOM); } @Test public void increaseVolumeNone1() { execute("Volume max"); verify(volumeService).increase(); } @Test public void increaseVolumeNone2() { execute("Louder please"); verify(volumeService).increase(); } @Test public void increaseVolumeNone3() { execute("Volume up"); verify(volumeService).increase(); } @Test public void increaseVolumeNone4() { execute("That's too quiet"); verify(volumeService).increase(); } // application of multiple synonyms per method is necessary @Test public void increaseVolumeNone5() { execute("Make the music louder"); verify(volumeService).increase(); } @Test public void increaseVolumeNone6() { execute("Turn it up"); verify(volumeService).increase(); } // groups in a regex do not have to be parameters of a method @Test public void increaseVolumeNone7() { execute("I can't hear that"); verify(volumeService).increase(); } }
29.212034
110
0.665522
35141f5c6deb28e73c96d2684f952269d712fb4f
3,197
/* * Copyright (c) 2010, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ /* * $Id: Evidence.java,v 1.2 2010-10-21 15:38:00 snajper Exp $ */ package com.sun.xml.wss.saml.assertion.saml11.jaxb20; import com.sun.xml.wss.saml.SAMLException; import com.sun.xml.wss.logging.LogDomainConstants; import com.sun.xml.wss.saml.internal.saml11.jaxb20.EvidenceType; import com.sun.xml.wss.saml.util.SAMLJAXBUtil; import java.util.List; import java.util.logging.Logger; import jakarta.xml.bind.JAXBContext; /** * The <code>Evidence</code> element specifies an assertion either by * reference or by value. An assertion is specified by reference to the value of * the assertion's <code>AssertionIDReference</code> element. * An assertion is specified by value by including the entire * <code>Assertion</code> object */ public class Evidence extends EvidenceType implements com.sun.xml.wss.saml.Evidence { protected static final Logger log = Logger.getLogger( LogDomainConstants.WSS_API_DOMAIN, LogDomainConstants.WSS_API_DOMAIN_BUNDLE); /** * Constructs an <code>Evidence</code> object from a block of existing XML * that has already been built into a DOM. * * @param element A <code>org.w3c.dom.Element</code> * representing DOM tree for <code>Evidence</code> object. * @exception SAMLException if it could not process the Element properly, * implying that there is an error in the sender or in the * element definition. */ public static EvidenceType fromElement(org.w3c.dom.Element element) throws SAMLException { try { JAXBContext jc = SAMLJAXBUtil.getJAXBContext(); jakarta.xml.bind.Unmarshaller u = jc.createUnmarshaller(); return (EvidenceType)u.unmarshal(element); } catch ( Exception ex) { throw new SAMLException(ex.getMessage()); } } @SuppressWarnings("unchecked") private void setAssertionIDReferenceOrAssertion(List evidence) { this.assertionIDReferenceOrAssertion = evidence; } /** * Constructs an Evidence from a Set of <code>Assertion</code> and * <code>AssertionIDReference</code> objects. * * @param assertionIDRef Set of <code>AssertionIDReference</code> objects. * @param assertion Set of <code>Assertion</code> objects. * @exception SAMLException if either Set is empty or has invalid object. */ public Evidence(List assertionIDRef, List assertion) { if ( assertionIDRef != null) setAssertionIDReferenceOrAssertion(assertionIDRef); else if ( assertion != null) setAssertionIDReferenceOrAssertion(assertion); } public Evidence(EvidenceType eveType){ setAssertionIDReferenceOrAssertion(eveType.getAssertionIDReferenceOrAssertion()); } }
34.75
89
0.686268
70db9a465c42c902537bae065cc2c70d9f993053
3,637
/* * This software is in the public domain under CC0 1.0 Universal plus a * Grant of Patent License. * * To the extent possible under law, the author(s) have dedicated all * copyright and related and neighboring rights to this software to the * public domain worldwide. This software is distributed without any * warranty. * * You should have received a copy of the CC0 Public Domain Dedication * along with this software (see the LICENSE.md file). If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ package org.moqui.workflow.activity; import org.moqui.util.ContextUtil; import org.moqui.util.TimestampUtil; import org.moqui.workflow.util.WorkflowEventType; import org.moqui.workflow.util.WorkflowInstanceStatus; import org.moqui.workflow.util.WorkflowUtil; import org.apache.commons.lang3.time.StopWatch; import org.json.JSONObject; import org.moqui.context.ExecutionContext; import org.moqui.entity.EntityValue; import org.moqui.service.ServiceFacade; /** * Workflow activity used as an exit point to stop a workflow instance. */ public class WorkflowExitActivity extends AbstractWorkflowActivity { /** * Creates a new activity. * * @param activity Activity entity */ public WorkflowExitActivity(EntityValue activity) { this.activity = activity; } @Override public boolean execute(ExecutionContext ec, EntityValue instance) { // start the stop watch StopWatch stopWatch = new StopWatch(); stopWatch.start(); // shortcuts for convenience ServiceFacade sf = ec.getService(); // get attributes String activityId = activity.getString("activityId"); String activityTypeEnumId = activity.getString("activityTypeEnumId"); String activityTypeDescription = activity.getString("activityTypeDescription"); String instanceId = instance.getString("instanceId"); // generate a new log ID String logId = ContextUtil.getLogId(ec); logger.debug(String.format("[%s] Executing %s activity (%s) ...", logId, activityTypeEnumId, activityId)); // get attributes JSONObject nodeData = new JSONObject(activity.getString("nodeData")); Integer resultCode = nodeData.has("resultCode") ? nodeData.getInt("resultCode") : null; // update workflow instance logger.debug(String.format("[%s] Exiting instance %s with result code %s", logId, instanceId, resultCode)); sf.sync().name("update#moqui.workflow.WorkflowInstance") .parameter("instanceId", instanceId) .parameter("statusId", WorkflowInstanceStatus.WF_INST_STAT_COMPLETE) .parameter("resultCode", resultCode) .parameter("lastUpdateDate", TimestampUtil.now()) .call(); // create event WorkflowUtil.createWorkflowEvent( ec, instanceId, WorkflowEventType.WF_EVENT_ACTIVITY, String.format("Executed %s activity (%s)", activityTypeDescription, activityId), false ); // create event WorkflowUtil.createWorkflowEvent( ec, instanceId, WorkflowEventType.WF_EVENT_FINISH, "Workflow finished", false ); // log the processing time stopWatch.stop(); logger.debug(String.format("[%s] %s activity (%s) executed in %d milliseconds", logId, activityTypeEnumId, activityId, stopWatch.getTime())); // activity executed successfully return true; } }
36.37
149
0.665109
3b1b6a77dfef1ea232d0a31ec0b8cedb23ab2ec6
159
package im.access; public class AnInputAuthorization extends AMessage<String> { public AnInputAuthorization(String theUserName) { super(theUserName); } }
19.875
60
0.792453
aad3759ee9d8dfeadabd0910a48eb78965eb1acb
1,642
package org.nutz.dao.test.normal.psql; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.nutz.dao.test.DaoCase; import org.nutz.lang.Lang; public class PsqlArrayTest extends DaoCase { @Override protected void before() { if (!dao.meta().isPostgresql()) return; dao.create(StudentArray.class, true); } @Test public void crud() { if (!dao.meta().isPostgresql()) return; StudentArray student = new StudentArray(); Integer[] payByQuarter = {1000, 1300, 1500, 1200}; String[] schedule = new String[]{"02", "05", "08", "11"}; student.setPayByQuarter(payByQuarter); student.setSchedule(schedule); int insertId = dao.insert(student).getId(); StudentArray insertStudent = dao.fetch(StudentArray.class, insertId); assertTrue(Lang.equals(payByQuarter, insertStudent.getPayByQuarter())); assertTrue(Lang.equals(schedule, insertStudent.getSchedule())); payByQuarter[2] = 2500; schedule[2] = "09"; insertStudent.setPayByQuarter(payByQuarter); insertStudent.setSchedule(schedule); dao.updateIgnoreNull(insertStudent); StudentArray updateStudent = dao.fetch(StudentArray.class, insertId); assertEquals(Integer.valueOf(2500), updateStudent.getPayByQuarter()[2]); assertEquals("09", updateStudent.getSchedule()[2]); dao.delete(StudentArray.class, insertId); assertNull(dao.fetch(StudentArray.class, insertId)); } }
34.93617
80
0.670524
572d24a32ce12a40236f85fb7e2c16d3c8e31c75
1,281
package org.javers.spring.boot.mongo; import org.javers.spring.auditable.CommitPropertiesProvider; import org.javers.spring.auditable.CommitPropertiesProviderContext; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * @author pawelszymczyk */ @Configuration @EnableAutoConfiguration @ComponentScan("org.javers.spring.boot.mongo") public class TestApplication { @Bean public CommitPropertiesProvider commitPropertiesProvider() { final Map<String, String> rv = new HashMap<>(); rv.put("key", "ok"); return new CommitPropertiesProvider() { @Override public Map<String, String> provide(CommitPropertiesProviderContext context, Object domainObject) { return Collections.unmodifiableMap(rv); } @Override public Map<String, String> provideForDeleteById(Class<?> domainObjectClass, Object domainObjectId) { return Collections.unmodifiableMap(rv); } }; } }
32.846154
112
0.724434
c64d8cdcc3eeb067d8eec8a22c88405845f7373a
3,200
package com.example.servemesystem; import java.sql.Date; public class ServiceRequest { private int serviceId; private int customerId; private int vendorId; private ServiceCategory category; private String serviceTime; private String location; private String title; private String description; private String status; private boolean isReviewed; private String servicedBy; private String requestedBy; private ServiceBid winningBid; private ServiceBid pendingBid; private VendorRating vendorRating; private int numBids; public ServiceRequest() { } public void setRating(VendorRating inVendorRating) { this.vendorRating = inVendorRating; } public void setNumBids(int inNumBids){ this.numBids = inNumBids; } public void setCustomerId(int customerId){ this.customerId = customerId; } public void setVendorId(int vendorId){ this.vendorId = vendorId; } public void setCategory(ServiceCategory category){ this.category = category; } public void setServiceTime(String serviceTime){ this.serviceTime = serviceTime; } public void setLocation(String location){ this.location = location; } public void setTitle(String title){ this.title = title; } public void setDescription(String description){ this.description = description; } public void setStatus(String status){ this.status = status; } public void setReviewed(boolean reviewed) { isReviewed = reviewed; } public void setServiceId(int serviceId) { this.serviceId = serviceId; } public void setServicedBy(String servicedBy) { this.servicedBy = servicedBy; } public void setWinningBid(ServiceBid winningBid) { this.winningBid = winningBid; } public void setPendingBid(ServiceBid pendingBid) { this.pendingBid = pendingBid; } public void setRequestedBy(String requestedBy) { this.requestedBy = requestedBy; } public ServiceBid getWinningBid() { return winningBid; } public ServiceBid getPendingBid() { return pendingBid; } public int getCustomerId(){ return customerId; } public int getVendorId(){ return vendorId; } public boolean isReviewed() { return isReviewed; } public String getServiceTime() { return serviceTime; } public ServiceCategory getCategory() { return category; } public String getDescription() { return description; } public String getLocation() { return location; } public String getStatus() { return status; } public String getTitle() { return title; } public int getServiceId() { return serviceId; } public String getServicedBy() { return servicedBy; } public String getRequestedBy() { return requestedBy; } public int getNumBids(){ return numBids; } public VendorRating getVendorRating() { return vendorRating; } }
20.382166
56
0.640938
9d2c551a407fc07485f032a1cd0b87ad015d3ea1
523
package com.mit.campus.rest.modular.poverty.service; import com.baomidou.mybatisplus.service.IService; import com.mit.campus.rest.modular.poverty.model.ShowPoorArea; import java.util.List; /** * * 学院平均消费 * @author shuyy * @date 2018年9月6日 */ public interface IShowPoorAreaService extends IService<ShowPoorArea> { /** * * 获取贫困区域 * @param @param year 指定年份 * @param @param top10 是否是前十名 * @param @return * @return List<ShowPoorArea> * @throws */ List<ShowPoorArea> findPoorArea(String year,boolean top10); }
19.37037
70
0.734226
90259b5ecbc31887c744cd6f098975bf13b2bf2e
322
package com.gtnewhorizon.structurelib.structure; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public interface IStructureElementNoPlacement<T> extends IStructureElement<T> { @Override default boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) { return false; } }
26.833333
87
0.78882
1e8b99ca825cd24bd153ba1d8c207f2a8ceb783b
4,649
package com.AdvancedProgramming.Menus; import com.AdvancedProgramming.MiniNet; import com.AdvancedProgramming.States; import com.AdvancedProgramming.Users.User; import java.util.Objects; import java.util.Optional; import java.util.Scanner; /** * MainMenu is the initial user interface that is displayed when MiniNet is run. * * @version 1.0.0 22nd March 2018 * @author Tejas Cherukara */ public class MainMenu implements Menu { public MainMenu() {} /** * Main menu options. */ @Override public void getMenu() { System.out.println("\nMain Menu:"); System.out.println(MiniNet.DIVIDER); System.out.println("1. List all users"); System.out.println("2. Add new user"); System.out.println("3. Are these two friends?"); System.out.println("4. Select a user"); } /** * Parses user actions for main menu. * @param input */ @Override public void doAction(Scanner input) { System.out.print("Select number from menu: "); String action = input.nextLine(); if(MiniNet.isInputInt(action)){ int actionInt = Integer.parseInt(action); switch(actionInt){ case 1: showUsers(); break; case 2: MiniNet.switchState(States.ADD_USER); break; case 3: areTheseFriends(input); break; case 4: selectUser(input); break; default: defaultAction(actionInt); break; } } else { System.out.println("Please input one of the options above."); } } /** * Show all the users in the system. */ private void showUsers() { if (userService.getUsers().size() > 0) { userService.getUsers().stream().filter(Objects::nonNull).forEach(user -> { System.out.println("\nName: "+user.getName()); System.out.println("Age: "+user.getAge()); if (!Objects.equals(user.getProfilePicture(), "")) { System.out.println("Profile Picture: "+user.getProfilePicture()); } if (!Objects.equals(user.getStatus(), "")) { System.out.println("Status: "+user.getStatus()+"\n"); } }); } else { System.out.println("\nNo users currently registered.\n"); } } /** * Selects a user and changes the menu. * @param input */ private void selectUser(Scanner input) { userService.displayUsers(); Optional<User> user; String name; do { System.out.println("Name of the user (from list above):"); name = input.nextLine(); user = userService.getUserWithName(name); if (isSpecialInput(name)) { break; } } while (!user.isPresent()); if (user.isPresent()) { userService.setSelectedUser(user.get()); MiniNet.switchState(States.SELECT_USER); } else { checkSpecialInput(name); } } /** * Checks if 2 users have a relation. * @param input */ private void areTheseFriends(Scanner input){ userService.displayUsers(); Optional<User> user1, user2; String userOne, userTwo; do{ System.out.println("Enter the name of user:"); userOne = input.nextLine(); user1 = userService.getUserWithName(userOne); if(isSpecialInput(userOne)){ break; } } while(!user1.isPresent()); //Check if the back / exit / help input is given. if(!user1.isPresent()){ checkSpecialInput(userOne); } do{ System.out.println("Enter the name of second user:"); userTwo = input.nextLine(); user2 = userService.getUserWithName(userTwo); if(isSpecialInput(userTwo)){ break; } } while(!user2.isPresent()); if(!user2.isPresent()){ checkSpecialInput(userOne); } else { if (user1.get().getUserRelation(user2.get()).isPresent()) { System.out.println(user2.get().getName()+" and "+user1.get().getName()+" has a relation."); } else { System.out.println("\n\nThey are not friends.\n"); } } } }
28.697531
107
0.521618
9d7c9d724d387a3c1f79737abcc92fa81b334688
5,594
// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 // ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see // LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, // please see LICENSE-APACHE2. // // This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, // either express or implied. See the LICENSE file for specific language governing // rights and limitations of this software. // // If you have any questions regarding licensing, please contact us at // [email protected]. package com.datastax.oss.starlight.rabbitmqtests.javaclient.functional; import static org.junit.Assert.assertEquals; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeoutException; import org.awaitility.Awaitility; import org.junit.Test; public class ExchangeDeclare extends ExchangeEquivalenceBase { static final String TYPE = "direct"; static final String NAME = "exchange_test"; public void releaseResources() throws IOException { channel.exchangeDelete(NAME); } @Test public void exchangeNoArgsEquivalence() throws IOException { channel.exchangeDeclare(NAME, TYPE, false, false, null); verifyEquivalent(NAME, TYPE, false, false, null); } @Test public void singleLineFeedStrippedFromExchangeName() throws IOException { channel.exchangeDeclare("exchange_test\n", TYPE, false, false, null); verifyEquivalent(NAME, TYPE, false, false, null); } @Test public void multipleLineFeedsStrippedFromExchangeName() throws IOException { channel.exchangeDeclare("exchange\n_test\n", TYPE, false, false, null); verifyEquivalent(NAME, TYPE, false, false, null); } @Test public void multipleLineFeedAndCarriageReturnsStrippedFromExchangeName() throws IOException { channel.exchangeDeclare("e\nxc\rhange\n\r_test\n\r", TYPE, false, false, null); verifyEquivalent(NAME, TYPE, false, false, null); } @Test public void exchangeNonsenseArgsEquivalent() throws IOException { channel.exchangeDeclare(NAME, TYPE, false, false, null); Map<String, Object> args = new HashMap<String, Object>(); args.put("nonsensical-argument-surely-not-in-use", "foo"); verifyEquivalent(NAME, TYPE, false, false, args); } @Test public void exchangeDurableNotEquivalent() throws IOException { channel.exchangeDeclare(NAME, TYPE, false, false, null); verifyNotEquivalent(NAME, TYPE, true, false, null); } @Test public void exchangeTypeNotEquivalent() throws IOException { channel.exchangeDeclare(NAME, "direct", false, false, null); verifyNotEquivalent(NAME, "fanout", false, false, null); } @Test public void exchangeAutoDeleteNotEquivalent() throws IOException { channel.exchangeDeclare(NAME, "direct", false, false, null); verifyNotEquivalent(NAME, "direct", false, true, null); } @Test public void exchangeDeclaredWithEnumerationEquivalentOnNonRecoverableConnection() throws IOException, InterruptedException { doTestExchangeDeclaredWithEnumerationEquivalent(channel); } @Test public void exchangeDeclaredWithEnumerationEquivalentOnRecoverableConnection() throws IOException, TimeoutException, InterruptedException { ConnectionFactory connectionFactory = newConnectionFactory(); connectionFactory.setAutomaticRecoveryEnabled(true); connectionFactory.setTopologyRecoveryEnabled(false); Connection c = connectionFactory.newConnection(); try { doTestExchangeDeclaredWithEnumerationEquivalent(c.createChannel()); } finally { c.abort(); } } private void doTestExchangeDeclaredWithEnumerationEquivalent(Channel channel) throws IOException, InterruptedException { assertEquals("There are 4 standard exchange types", 4, BuiltinExchangeType.values().length); for (BuiltinExchangeType exchangeType : BuiltinExchangeType.values()) { channel.exchangeDeclare(NAME, exchangeType); verifyEquivalent(NAME, exchangeType.getType(), false, false, null); channel.exchangeDelete(NAME); channel.exchangeDeclare(NAME, exchangeType, false); verifyEquivalent(NAME, exchangeType.getType(), false, false, null); channel.exchangeDelete(NAME); channel.exchangeDeclare(NAME, exchangeType, false, false, null); verifyEquivalent(NAME, exchangeType.getType(), false, false, null); channel.exchangeDelete(NAME); channel.exchangeDeclare(NAME, exchangeType, false, false, false, null); verifyEquivalent(NAME, exchangeType.getType(), false, false, null); channel.exchangeDelete(NAME); channel.exchangeDeclareNoWait(NAME, exchangeType, false, false, false, null); Awaitility.await() .atMost(Duration.ofSeconds(5)) .until( () -> gatewayService .getContextMetadata() .model() .getVhosts() .get("public/default") .getExchanges() .containsKey(NAME)); verifyEquivalent(NAME, exchangeType.getType(), false, false, null); channel.exchangeDelete(NAME); } } }
36.802632
96
0.724169
d6df2c8e925f5ce461ce3ea41b1db3c4272445e8
162
package beans; import org.springframework.stereotype.Component; @Component public class UserDao { public void printName() { System.out.println("张三"); } }
12.461538
48
0.734568
c947853bc9e19db33a1b27065162d91da61e4a61
43,247
/* * Copyright 2010-2013 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.beatrix.integration.overdue; import java.math.BigDecimal; import java.util.Collection; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.testng.annotations.Test; import com.ning.billing.api.TestApiListener.NextEvent; import com.ning.billing.beatrix.integration.BeatrixIntegrationModule; import com.ning.billing.beatrix.util.InvoiceChecker.ExpectedInvoiceItemCheck; import com.ning.billing.catalog.api.BillingPeriod; import com.ning.billing.catalog.api.Currency; import com.ning.billing.catalog.api.PriceListSet; import com.ning.billing.catalog.api.ProductCategory; import com.ning.billing.entitlement.api.user.EntitlementUserApiException; import com.ning.billing.entitlement.api.user.Subscription; import com.ning.billing.invoice.api.Invoice; import com.ning.billing.invoice.api.InvoiceItemType; import com.ning.billing.invoice.api.InvoicePayment; import com.ning.billing.junction.api.BlockingApiException; import com.ning.billing.payment.api.Payment; import com.ning.billing.util.svcapi.junction.DefaultBlockingState; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; @Test(groups = "slow") public class TestOverdueIntegration extends TestOverdueBase { @Override public String getOverdueConfig() { final String configXml = "<overdueConfig>" + " <bundleOverdueStates>" + " <state name=\"OD3\">" + " <condition>" + " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + " <unit>DAYS</unit><number>50</number>" + " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + " </condition>" + " <externalMessage>Reached OD3</externalMessage>" + " <blockChanges>true</blockChanges>" + " <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>" + " <autoReevaluationInterval>" + " <unit>DAYS</unit><number>5</number>" + " </autoReevaluationInterval>" + " </state>" + " <state name=\"OD2\">" + " <condition>" + " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + " <unit>DAYS</unit><number>40</number>" + " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + " </condition>" + " <externalMessage>Reached OD2</externalMessage>" + " <blockChanges>true</blockChanges>" + " <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>" + " <autoReevaluationInterval>" + " <unit>DAYS</unit><number>5</number>" + " </autoReevaluationInterval>" + " </state>" + " <state name=\"OD1\">" + " <condition>" + " <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + " <unit>DAYS</unit><number>30</number>" + " </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" + " </condition>" + " <externalMessage>Reached OD1</externalMessage>" + " <blockChanges>true</blockChanges>" + " <disableEntitlementAndChangesBlocked>false</disableEntitlementAndChangesBlocked>" + " <autoReevaluationInterval>" + " <unit>DAYS</unit><number>5</number>" + " </autoReevaluationInterval>" + " </state>" + " </bundleOverdueStates>" + "</overdueConfig>"; return configXml; } // We set the the property killbill.payment.retry.days=8,8,8,8,8,8,8,8 so that Payment retry logic does not end with an ABORTED state // preventing final instant payment to succeed. @Test(groups = "slow") public void testBasicOverdueState() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Set next invoice to fail and create subscription paymentPlugin.makeAllInvoicesFailWithError(true); final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // 2012, 5, 31 => DAY 30 have to get out of trial {I0, P0} addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // 2012, 6, 8 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 16 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 24 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 31 => P1 (We se 6/31 instead of 6/30 because invoice might happen later in that day) addDaysAndCheckForCompletion(7, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // 2012, 7, 2 => Retry P0 addDaysAndCheckForCompletion(1, NextEvent.PAYMENT_ERROR); checkODState("OD1"); // 2012, 7, 9 => Retry P1 addDaysAndCheckForCompletion(7, NextEvent.PAYMENT_ERROR); checkODState("OD1"); // 2012, 7, 10 => Retry P0 addDaysAndCheckForCompletion(1, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 17 => Retry P1 addDaysAndCheckForCompletion(7, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 18 => Retry P0 addDaysAndCheckForCompletion(1, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 23 => Should be 20 but notficationQ event occurs on 23... addDaysAndCheckForCompletion(5); checkODState("OD3"); paymentPlugin.makeAllInvoicesFailWithError(false); final Collection<Invoice> invoices = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext); for (final Invoice invoice : invoices) { if (invoice.getBalance().compareTo(BigDecimal.ZERO) > 0) { createPaymentAndCheckForCompletion(account, invoice, NextEvent.PAYMENT); } } checkODState(DefaultBlockingState.CLEAR_STATE_NAME); checkChangePlanWithOverdueState(baseSubscription, false); invoiceChecker.checkRepairedInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95")), // We paid up to 07-31, hence the adjustment new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 10), new LocalDate(2012, 7, 31), InvoiceItemType.REPAIR_ADJ, new BigDecimal("-166.64")), new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 23), new LocalDate(2012, 7, 23), InvoiceItemType.CBA_ADJ, new BigDecimal("166.64"))); invoiceChecker.checkInvoice(account.getId(), 4, callContext, // Item for the upgraded recurring plan new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 23), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("154.85")), // Credits consumed new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 23), new LocalDate(2012, 7, 23), InvoiceItemType.CBA_ADJ, new BigDecimal("-154.85"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // Verify the account balance: 249.95 - 74.99 - 154.85 assertEquals(invoiceUserApi.getAccountBalance(account.getId(), callContext).compareTo(new BigDecimal("-11.79")), 0); } // We set the the property killbill.payment.retry.days=8,8,8,8,8,8,8,8 so that Payment retry logic does not end with an ABORTED state // preventing final instant payment to succeed. @Test(groups = "slow") public void testSingleRepareeOnOverdueState() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Set next invoice to fail and create subscription paymentPlugin.makeAllInvoicesFailWithError(true); final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // 2012, 5, 31 => DAY 30 have to get out of trial {I0, P0} addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // 2012, 6, 8 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 16 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 24 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 31 => P1 (We se 6/31 instead of 6/30 because invoice might happen later in that day) addDaysAndCheckForCompletion(7, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // 2012, 7, 2 => Retry P0 addDaysAndCheckForCompletion(1, NextEvent.PAYMENT_ERROR); checkODState("OD1"); // 2012, 7, 9 => Retry P1 addDaysAndCheckForCompletion(7, NextEvent.PAYMENT_ERROR); checkODState("OD1"); // 2012, 7, 10 => Retry P0 addDaysAndCheckForCompletion(1, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 17 => Retry P1 addDaysAndCheckForCompletion(7, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 18 => Retry P0 addDaysAndCheckForCompletion(1, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 23 => Should be 20 but notficationQ event occurs on 23... addDaysAndCheckForCompletion(5); checkODState("OD3"); paymentPlugin.makeAllInvoicesFailWithError(false); final Collection<Invoice> invoices = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext); for (final Invoice invoice : invoices) { if (invoice.getBalance().compareTo(BigDecimal.ZERO) > 0) { createPaymentAndCheckForCompletion(account, invoice, NextEvent.PAYMENT); } } checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // Add 10 days to generate next invoice addDaysAndCheckForCompletion(10, NextEvent.INVOICE, NextEvent.INVOICE_ADJUSTMENT, NextEvent.PAYMENT); invoiceChecker.checkRepairedInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95")), // We paid up to 07-31, hence the adjustment new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 10), new LocalDate(2012, 7, 23), InvoiceItemType.REPAIR_ADJ, new BigDecimal("-102.13")), new ExpectedInvoiceItemCheck(new LocalDate(2012, 8, 2), new LocalDate(2012, 8, 2), InvoiceItemType.CBA_ADJ, new BigDecimal("102.13"))); invoiceChecker.checkInvoice(account.getId(), 4, callContext, // Item for the upgraded recurring plan new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 31), new LocalDate(2012, 8, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95")), // Credits consumed new ExpectedInvoiceItemCheck(new LocalDate(2012, 8, 2), new LocalDate(2012, 8, 2), InvoiceItemType.CBA_ADJ, new BigDecimal("-102.13"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 8, 31), callContext); // Verify the account balance: 249.95 - 74.99 - 154.85 assertEquals(invoiceUserApi.getAccountBalance(account.getId(), callContext).compareTo(BigDecimal.ZERO), 0); } // We set the the property killbill.payment.retry.days=8,8,8,8,8,8,8,8 so that Payment retry logic does not end with an ABORTED state // preventing final instant payment to succeed. @Test(groups = "slow") public void testMultipleRepareeOnOverdueState() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Set next invoice to fail and create subscription paymentPlugin.makeAllInvoicesFailWithError(true); final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, BillingPeriod.ANNUAL, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // 2012, 5, 31 => DAY 30 have to get out of trial {I0, P0} addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2013, 5, 31), InvoiceItemType.RECURRING, new BigDecimal("2399.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2013, 5, 31), callContext); // 2012, 6, 8 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 16 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 6, 24 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // 2012, 7, 2 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState("OD1"); // 2012, 7, 10 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 18 => Retry P0 addDaysAndCheckForCompletion(8, NextEvent.PAYMENT_ERROR); checkODState("OD2"); // 2012, 7, 23 => Should be 20 but notficationQ event occurs on 23... addDaysAndCheckForCompletion(5); checkODState("OD3"); paymentPlugin.makeAllInvoicesFailWithError(false); final Collection<Invoice> invoices = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext); for (final Invoice invoice : invoices) { if (invoice.getBalance().compareTo(BigDecimal.ZERO) > 0) { createPaymentAndCheckForCompletion(account, invoice, NextEvent.PAYMENT); } } checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // Move to 2012, 7, 31 and Make a change of plan addDaysAndCheckForCompletion(8); checkChangePlanWithOverdueState(baseSubscription, false); invoiceChecker.checkRepairedInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2013, 5, 31), InvoiceItemType.RECURRING, new BigDecimal("2399.95")), new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 10), new LocalDate(2012, 7, 23), InvoiceItemType.REPAIR_ADJ, new BigDecimal("-85.4588")), new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 31), new LocalDate(2013, 5, 31), InvoiceItemType.REPAIR_ADJ, new BigDecimal("-1998.9012")), new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 31), new LocalDate(2012, 7, 31), InvoiceItemType.CBA_ADJ, new BigDecimal("2084.36"))); invoiceChecker.checkInvoice(account.getId(), 3, callContext, // Item for the upgraded recurring plan new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 31), new LocalDate(2012, 8, 31), InvoiceItemType.RECURRING, new BigDecimal("599.95")), // Credits consumed new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 31), new LocalDate(2012, 7, 31), InvoiceItemType.CBA_ADJ, new BigDecimal("-599.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 8, 31), callContext); assertEquals(invoiceUserApi.getAccountBalance(account.getId(), callContext).compareTo(new BigDecimal("-1484.41")), 0); } @Test(groups = "slow") public void testOverdueStateIfNoPaymentMethod() throws Exception { // This test is similar to the previous one - but there is no default payment method on the account, so there // won't be any payment retry clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Make sure the account doesn't have any payment method accountInternalApi.removePaymentMethod(account.getId(), internalCallContext); // Create subscription final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // DAY 30 have to get out of trial before first payment. A payment error, one for each invoice, should be on the bus (because there is no payment method) addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 45 - 15 days after invoice addDaysAndCheckForCompletion(15); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 65 - 35 days after invoice // Single PAYMENT_ERROR here here triggered by the invoice addDaysAndCheckForCompletion(20, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // Now we should be in OD1 checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); // DAY 67 - 37 days after invoice addDaysAndCheckForCompletion(2); // Should still be in OD1 checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); // DAY 75 - 45 days after invoice addDaysAndCheckForCompletion(8); // Should now be in OD2 checkODState("OD2"); checkChangePlanWithOverdueState(baseSubscription, true); // DAY 85 - 55 days after invoice addDaysAndCheckForCompletion(10); // Should now be in OD3 checkODState("OD3"); checkChangePlanWithOverdueState(baseSubscription, true); // Add a payment method and set it as default paymentApi.addPaymentMethod(BeatrixIntegrationModule.NON_OSGI_PLUGIN_NAME, account, true, paymentMethodPlugin, callContext); // Pay all invoices final Collection<Invoice> invoices = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext); for (final Invoice invoice : invoices) { if (invoice.getBalance().compareTo(BigDecimal.ZERO) > 0) { createPaymentAndCheckForCompletion(account, invoice, NextEvent.PAYMENT); } } checkODState(DefaultBlockingState.CLEAR_STATE_NAME); checkChangePlanWithOverdueState(baseSubscription, false); invoiceChecker.checkRepairedInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95")), // We paid up to 07-31, hence the adjustment new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 15), new LocalDate(2012, 7, 31), InvoiceItemType.REPAIR_ADJ, new BigDecimal("-124.97")), new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 25), new LocalDate(2012, 7, 25), InvoiceItemType.CBA_ADJ, new BigDecimal("124.97"))); invoiceChecker.checkInvoice(account.getId(), 4, callContext, // Item for the upgraded recurring plan new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 25), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("116.09")), // Credits consumed new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 25), new LocalDate(2012, 7, 25), InvoiceItemType.CBA_ADJ, new BigDecimal("-116.09"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // Verify the account balance: 249.95 - 124.98 - 116.09 assertEquals(invoiceUserApi.getAccountBalance(account.getId(), callContext).compareTo(new BigDecimal("-8.88")), 0); } @Test(groups = "slow") public void testShouldBeInOverdueAfterExternalCharge() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Create a subscription without failing payments final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // Create an external charge on a new invoice addDaysAndCheckForCompletion(5); busHandler.pushExpectedEvents(NextEvent.INVOICE_ADJUSTMENT); invoiceUserApi.insertExternalChargeForBundle(account.getId(), bundle.getId(), BigDecimal.TEN, "For overdue", new LocalDate(2012, 5, 6), Currency.USD, callContext); assertTrue(busHandler.isCompleted(DELAY)); assertListenerStatus(); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 6), null, InvoiceItemType.EXTERNAL_CHARGE, BigDecimal.TEN)); // DAY 30 have to get out of trial before first payment addDaysAndCheckForCompletion(25, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // Should still be in clear state - the invoice for the bundle has been paid, but not the invoice with the external charge // We refresh overdue just to be safe, see below overdueUserApi.refreshOverdueStateFor(bundle, callContext); checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // Past 30 days since the external charge addDaysAndCheckForCompletion(6); // Note! We need to explicitly refresh here because overdue won't get notified to refresh up until the next // payment (when the next invoice is generated) // TODO - we should fix this overdueUserApi.refreshOverdueStateFor(bundle, callContext); // We should now be in OD1 checkODState("OD1"); // Pay the invoice final Invoice externalChargeInvoice = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext).iterator().next(); createExternalPaymentAndCheckForCompletion(account, externalChargeInvoice, NextEvent.PAYMENT); // We should be clear now checkODState(DefaultBlockingState.CLEAR_STATE_NAME); } @Test(groups = "slow") public void testShouldBeInOverdueAfterRefundWithoutAdjustment() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Create subscription and don't fail payments final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // DAY 30 have to get out of trial before first payment addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 45 - 15 days after invoice addDaysAndCheckForCompletion(15); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 65 - 35 days after invoice addDaysAndCheckForCompletion(20, NextEvent.INVOICE, NextEvent.PAYMENT); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // Now, refund the second (first non-zero dollar) invoice final Payment payment = paymentApi.getPayment(invoiceUserApi.getInvoicesByAccount(account.getId(), callContext).get(1).getPayments().get(0).getPaymentId(), false, callContext); refundPaymentAndCheckForCompletion(account, payment, NextEvent.INVOICE_ADJUSTMENT); // We should now be in OD1 checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); } @Test(groups = "slow") public void testShouldBeInOverdueAfterChargeback() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Create subscription and don't fail payments final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // DAY 30 have to get out of trial before first payment addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 45 - 15 days after invoice addDaysAndCheckForCompletion(15); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 65 - 35 days after invoice addDaysAndCheckForCompletion(20, NextEvent.INVOICE, NextEvent.PAYMENT); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // Now, create a chargeback for the second (first non-zero dollar) invoice final InvoicePayment payment = invoicePaymentApi.getInvoicePayments(invoiceUserApi.getInvoicesByAccount(account.getId(), callContext).get(1).getPayments().get(0).getPaymentId(), callContext).get(0); createChargeBackAndCheckForCompletion(payment, NextEvent.INVOICE_ADJUSTMENT); // We should now be in OD1 checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); } @Test(groups = "slow") public void testOverdueStateShouldClearAfterExternalPayment() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Set next invoice to fail and create subscription paymentPlugin.makeAllInvoicesFailWithError(true); final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // DAY 30 have to get out of trial before first payment addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 45 - 15 days after invoice addDaysAndCheckForCompletion(15, NextEvent.PAYMENT_ERROR); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 65 - 35 days after invoice addDaysAndCheckForCompletion(20, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // Now we should be in OD1 checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); // We have two unpaid non-zero dollar invoices at this point // Pay the first one via an external payment - we should then be 5 days apart from the second invoice // (which is the earliest unpaid one) and hence come back to a clear state (see configuration) final Invoice firstNonZeroInvoice = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext).iterator().next(); createExternalPaymentAndCheckForCompletion(account, firstNonZeroInvoice, NextEvent.PAYMENT); // We should be clear now checkODState(DefaultBlockingState.CLEAR_STATE_NAME); } @Test(groups = "slow", enabled = false) public void testOverdueStateAndWRITTEN_OFFTag() throws Exception { // TODO add/remove tag to invoice } @Test(groups = "slow") public void testOverdueStateShouldClearAfterCreditOrInvoiceItemAdjustment() throws Exception { clock.setTime(new DateTime(2012, 5, 1, 0, 3, 42, 0)); // Set next invoice to fail and create subscription paymentPlugin.makeAllInvoicesFailWithError(true); final Subscription baseSubscription = createSubscriptionAndCheckForCompletion(bundle.getId(), productName, ProductCategory.BASE, term, NextEvent.CREATE, NextEvent.INVOICE); invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 5, 1), callContext); // DAY 30 have to get out of trial before first payment addDaysAndCheckForCompletion(30, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 6, 30), callContext); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 45 - 15 days after invoice addDaysAndCheckForCompletion(15, NextEvent.PAYMENT_ERROR); // Should still be in clear state checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 65 - 35 days after invoice addDaysAndCheckForCompletion(20, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR, NextEvent.PAYMENT_ERROR); invoiceChecker.checkInvoice(account.getId(), 3, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 6, 30), new LocalDate(2012, 7, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // Now we should be in OD1 checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); // We have two unpaid non-zero dollar invoices at this point // Adjust the first (and only) item of the first invoice - we should then be 5 days apart from the second invoice // (which is the earliest unpaid one) and hence come back to a clear state (see configuration) final Invoice firstNonZeroInvoice = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext).iterator().next(); fullyAdjustInvoiceItemAndCheckForCompletion(account, firstNonZeroInvoice, 1, NextEvent.INVOICE_ADJUSTMENT); // We should be clear now checkODState(DefaultBlockingState.CLEAR_STATE_NAME); invoiceChecker.checkRepairedInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 6, 30), InvoiceItemType.RECURRING, new BigDecimal("249.95")), new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 31), new LocalDate(2012, 5, 31), InvoiceItemType.ITEM_ADJ, new BigDecimal("-249.95"))); invoiceChecker.checkChargedThroughDate(baseSubscription.getId(), new LocalDate(2012, 7, 31), callContext); // DAY 70 - 10 days after second invoice addDaysAndCheckForCompletion(5); // We should still be clear checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 80 - 20 days after second invoice addDaysAndCheckForCompletion(10, NextEvent.PAYMENT_ERROR); // We should still be clear checkODState(DefaultBlockingState.CLEAR_STATE_NAME); // DAY 95 - 35 days after second invoice addDaysAndCheckForCompletion(15, NextEvent.PAYMENT_ERROR, NextEvent.INVOICE, NextEvent.PAYMENT_ERROR); // We should now be in OD1 checkODState("OD1"); checkChangePlanWithOverdueState(baseSubscription, true); invoiceChecker.checkInvoice(account.getId(), 4, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 7, 31), new LocalDate(2012, 8, 31), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); // Fully adjust all invoices final Collection<Invoice> invoices = invoiceUserApi.getUnpaidInvoicesByAccountId(account.getId(), clock.getUTCToday(), callContext); for (final Invoice invoice : invoices) { if (invoice.getBalance().compareTo(BigDecimal.ZERO) > 0) { fullyAdjustInvoiceAndCheckForCompletion(account, invoice, NextEvent.INVOICE_ADJUSTMENT); } } // We should be cleared again checkODState(DefaultBlockingState.CLEAR_STATE_NAME); } private void checkChangePlanWithOverdueState(final Subscription subscription, final boolean shouldFail) { if (shouldFail) { try { subscription.changePlan("Pistol", term, PriceListSet.DEFAULT_PRICELIST_NAME, clock.getUTCNow(), callContext); } catch (EntitlementUserApiException e) { assertTrue(e.getCause() instanceof BlockingApiException); } } else { // Upgrade - we don't expect a payment here due to the scenario (the account will have some CBA) changeSubscriptionAndCheckForCompletion(subscription, "Assault-Rifle", BillingPeriod.MONTHLY, NextEvent.CHANGE, NextEvent.INVOICE); } } }
58.919619
209
0.669295
6712df232c6f530e57397eb4394d4ff417647445
505
package org.kushtrimhajrizi.rpalace.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) public class AccessTokenException extends RuntimeException { public AccessTokenException() { } public AccessTokenException(String message) { super(message); } public AccessTokenException(String message, Throwable cause) { super(message, cause); } }
25.25
66
0.760396
b05a366196d32098704b45da3731d1070b768006
231
package com.demo.security.securitycore.validate.core.sms; /** * @author : luofeng * @date : Created in 2019/4/16 11:17 * @description : 短信验证码 */ public interface SmsCodeSender { void send(String mobile,String code); }
17.769231
57
0.692641
d5e82ace4a7c907837857d2aa8f54e00253c24f5
207
package yuk.model.multi; import yuk.model.AbsFake; public abstract class AbsContainer extends AbsFake{ public String name = ""; public String command = ""; public abstract long getSize(); }
18.818182
52
0.705314
c2fe937fa72e809e831087327b3a44e55ad0fe55
4,047
/* * Copyright (c) 2019 Shane Funk - Javaseeds Consulting * All rights reserved. * 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 funk.shane.valid.control; import java.util.List; import java.util.stream.Collectors; import javax.validation.ConstraintViolationException; import javax.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import funk.shane.valid.pojo.Person; import funk.shane.valid.util.Utils; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping("api") @Slf4j public class ValidController { /** * validDemo - REST POST call to "write" a person to a data source (not provided in this demo app) * Only returns a String with either an affirmative valid message or explains why the input was incorrect * * @param person * @return */ @PostMapping(path = "/v1/valid", produces = MediaType.TEXT_PLAIN_VALUE) public ResponseEntity<String> validDemo(@Valid @RequestBody Person person) { log.info("inbound person: {}", person); return ResponseEntity.ok(String.format("Spring Boot person [%s] was valid", person)); } /** * Retrieve a person - even though there's an id sent in, this trivial example doesn't pull from a data source * in this version * @return */ @GetMapping(path = "/v1/get-a-person/{id}", produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<Person> getPerson(@PathVariable String id) { log.info("Get Person with id: [{}]", id); final Person person = Utils.getClassFromJsonFile(Person.class, "person-1.json"); log.info("Returning Person: {}", person); return ResponseEntity.ok().body(person); } /** * https://www.baeldung.com/exception-handling-for-rest-with-spring * Spring recommends having exceptions in their own @ControllerAdvice, but is ok for this simple example */ @ExceptionHandler({ConstraintViolationException.class}) public ResponseEntity<String> validationErrorHandler(ConstraintViolationException ex) { final List<String> validationStrings = ex.getConstraintViolations() .stream() .map(v -> v.getMessage()) .sorted() .collect(Collectors.toList()); log.error("Inbound REST call tripped validation error(s) [{}]", validationStrings.toString()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(validationStrings.toString()); } }
42.6
115
0.729676
a8d4901dd9a566d3c4a52dafaf9dcc8a9a2266ae
4,253
/* * The MIT License * * Copyright 2015 Adam Kowalewski. * * 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.adamkowalewski.opw.view.controller; import com.adamkowalewski.opw.OpwException; import com.adamkowalewski.opw.bean.MailBean; import com.adamkowalewski.opw.entity.OpwUser; import com.adamkowalewski.opw.bean.UserBean; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; /** * Provides reusable logic around User. * * @author Adam Kowalewski */ @Named @RequestScoped public class UserController implements Serializable { @EJB private UserBean bean; @Inject private MailBean mailBean; @Inject private ConfigController configController; public UserController() { } public boolean isDuplicate(String email) { return bean.isDuplicate(email); } public UserController(UserBean bean, MailBean mailController) { this.bean = bean; this.mailBean = mailController; } public boolean activateAccount(String email, String token) { return bean.activateAccount(email, token); } public OpwUser authenticate(String login, String password) { return bean.verifyCredentials(login, password, configController.getApplicationSalt()); } public void create(List<OpwUser> userList) { for (OpwUser user : userList) { create(user); } } /** * Creates a new user within database and generates a random password. * * @param user instance of user. * @author Adam Kowalewski * @version 2015.04.14 */ public void create(OpwUser user) { String passwordPlain = bean.generatePassword(); String userSalt = bean.generatePassword(8); user.setSalt(userSalt); user.setToken(bean.generateToken()); if (user.getType() == null) { user.setType("U"); // TODO enum } user.setActive(false); user.setDateCreated(new Date()); if (configController.isConfigMailOutboundActive()){ mailBean.sendMailWelcome(user, passwordPlain, true); } user.setPassword(bean.saltPassword(configController.getApplicationSalt(), userSalt, passwordPlain)); bean.create(user); } /** * Generates and persists a new password for user as well as triggers E-Mail * notification. * * @param user instance of user. * * @author Adam Kowalewski * @version 2015.03.29 */ public void resetPassword(OpwUser user) { String passwordPlain = bean.generatePassword(); mailBean.sendMailPasswordNew(user, passwordPlain); user.setPassword(bean.saltPassword(configController.getApplicationSalt(), user.getSalt(), passwordPlain)); bean.edit(user); } public void delete(OpwUser user) { bean.remove(user); } public OpwUser find(int id) { return bean.findUser(id); } public void edit(OpwUser user) { bean.edit(user); } public List<OpwUser> findAll() { return bean.findAll(); } }
30.818841
114
0.687515
77334d1b7ab6c1f5a36bd401cc5ee5cd8581a138
333
package com.fermich.nolfix.fix.msg; import com.fermich.nolfix.broker.ApiSettings; abstract public class FixmlRequest extends FixmlMessage { public Fixml pack() { return new Fixml() .setV(ApiSettings.FIXML_V) .setR(ApiSettings.FIXML_R) .setS(ApiSettings.FIXML_S); } }
25.615385
57
0.63964
71ad1df059ef77fdbf7fd5cc6a22285b019f0529
814
package cn.solwind.excel.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author chfenix * @version 创建时间:2019-05-09 * * 表格行尾注解 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Foot{ /** * 行尾固定值 * @return */ public String value(); /** * 背景色 * @return */ public int background() default 0; /** * 字体名称 * @return */ public String fontFamily() default ""; /** * 字体大小 * @return */ public int fontSize() default 0; /** * 颜色 * @return */ public int color() default 0; /** * 加粗 * @return */ public boolean bold() default false; /** * 水平对齐 * @return */ public int align() default 0; }
13.129032
44
0.632678
2f3739cbd50fb1c492409ce74f5e41a93535cdb7
726
package io.lumify.mapping.xform; import java.util.Arrays; import org.junit.runners.Parameterized.Parameters; public class StringValueTransformerTest extends AbstractValueTransformerTest<String> { @Parameters(name="{index}: {0}->{0}") public static Iterable<Object[]> getTestValues() { return Arrays.asList(new Object[][] { { null, null }, { "", null }, { "\n \t\t \n", null }, { "foo", "foo" }, { "bar", "bar" }, { "FiZZ", "FiZZ" }, { "BUZZ", "BUZZ" } }); } public StringValueTransformerTest(final String input, final String expected) { super(new StringValueTransformer(), input, expected); } }
30.25
86
0.570248
e7851ea343b83f2f60ce44124a1b6dcd0432d72a
5,375
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.solutions.ml.api.vision; import com.google.api.client.util.ExponentialBackOff; import com.google.api.gax.rpc.ResourceExhaustedException; import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.AnnotateImageResponse; import com.google.cloud.vision.v1.Feature; import com.google.cloud.vision.v1.Image; import com.google.cloud.vision.v1.ImageAnnotatorClient; import com.google.cloud.vision.v1.ImageSource; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.values.KV; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Calls Google Cloud Vision API to annotate a batch of GCS files. * * The GCS file URIs are provided in the incoming PCollection and should not exceed the limit * imposed by the API (maximum of 16 images per request). * * The resulting PCollection contains key/value pair with the GCS file URI as the key and the API * response as the value. */ public class AnnotateImagesDoFn extends DoFn<Iterable<String>, KV<String, AnnotateImageResponse>> { private static final long serialVersionUID = 1L; public static final Logger LOG = LoggerFactory.getLogger(AnnotateImagesDoFn.class); private final List<Feature> featureList = new ArrayList<>(); private ImageAnnotatorClient visionApiClient; public AnnotateImagesDoFn(List<Feature.Type> featureTypes) { featureTypes.forEach( type -> featureList.add(Feature.newBuilder().setType(type).build())); } @Setup public void setupAPIClient() { try { visionApiClient = ImageAnnotatorClient.create(); } catch (IOException e) { LOG.error("Failed to create Vision API Service Client: {}", e.getMessage()); throw new RuntimeException(e); } } @Teardown public void tearDownAPIClient() { if (visionApiClient != null) { visionApiClient.shutdownNow(); try { int waitTime = 10; if (!visionApiClient.awaitTermination(waitTime, TimeUnit.SECONDS)) { LOG.warn( "Failed to shutdown the annotation client after {} seconds. Closing client anyway.", waitTime); } } catch (InterruptedException e) { // Do nothing } visionApiClient.close(); } } @ProcessElement public void processElement(@Element Iterable<String> imageFileURIs, OutputReceiver<KV<String, AnnotateImageResponse>> out) { List<AnnotateImageRequest> requests = new ArrayList<>(); imageFileURIs.forEach( imageUri -> { Image image = Image.newBuilder() .setSource(ImageSource.newBuilder().setImageUri(imageUri).build()) .build(); AnnotateImageRequest.Builder request = AnnotateImageRequest.newBuilder().setImage(image).addAllFeatures(featureList); requests.add(request.build()); }); List<AnnotateImageResponse> responses; ExponentialBackOff backoff = new ExponentialBackOff.Builder() .setInitialIntervalMillis(10 * 1000 /* 10 seconds */) .setMaxElapsedTimeMillis(10 * 60 * 1000 /* 10 minutes */) .setMaxIntervalMillis(90 * 1000 /* 90 seconds */) .setMultiplier(1.5) .setRandomizationFactor(0.5) .build(); while (true) { try { VisionAnalyticsPipeline.numberOfRequests.inc(); responses = visionApiClient.batchAnnotateImages(requests).getResponsesList(); break; } catch (ResourceExhaustedException e) { handleQuotaReachedException(backoff, e); } } int index = 0; for (AnnotateImageResponse response : responses) { String imageUri = requests.get(index++).getImage().getSource().getImageUri(); out.output(KV.of(imageUri, response)); } } /** * Attempts to backoff unless reaches the max elapsed time. * * @param backoff * @param e */ void handleQuotaReachedException(ExponentialBackOff backoff, ResourceExhaustedException e) { VisionAnalyticsPipeline.numberOfQuotaExceededRequests.inc(); long waitInMillis = 0; try { waitInMillis = backoff.nextBackOffMillis(); } catch (IOException ioException) { // Will not occur with this implementation of Backoff. } if (waitInMillis == ExponentialBackOff.STOP) { LOG.warn("Reached the limit of backoff retries. Throwing the exception to the pipeline"); throw e; } LOG.info("Received {}. Will retry in {} seconds.", e.getClass().getName(), waitInMillis / 1000); try { TimeUnit.MILLISECONDS.sleep(waitInMillis); } catch (InterruptedException interruptedException) { // Do nothing } } }
34.455128
99
0.694512
bd57a6d8722732ba58069c5bb8416fcfd9dfae7e
23,977
/* * 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.ignite.internal.util.tostring; import com.sun.management.ThreadMXBean; import java.lang.management.ManagementFactory; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.locks.ReadWriteLock; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.cache.KeyCacheObjectImpl; import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.testframework.junits.common.GridCommonTest; import org.junit.Test; import static org.apache.ignite.IgniteSystemProperties.IGNITE_TO_STRING_COLLECTION_LIMIT; import static org.apache.ignite.IgniteSystemProperties.IGNITE_TO_STRING_MAX_LENGTH; import static org.apache.ignite.internal.util.tostring.GridToStringBuilder.identity; /** * Tests for {@link GridToStringBuilder}. */ @GridCommonTest(group = "Utils") public class GridToStringBuilderSelfTest extends GridCommonAbstractTest { /** * @throws Exception If failed. */ @Test public void testToString() throws Exception { TestClass1 obj = new TestClass1(); IgniteLogger log = log(); log.info(obj.toStringManual()); log.info(obj.toStringAutomatic()); assertEquals (obj.toStringManual(), obj.toStringAutomatic()); } /** * @throws Exception If failed. */ @Test public void testToStringWithAdditions() throws Exception { TestClass1 obj = new TestClass1(); IgniteLogger log = log(); String manual = obj.toStringWithAdditionalManual(); log.info(manual); String automatic = obj.toStringWithAdditionalAutomatic(); log.info(automatic); assertEquals(manual, automatic); } /** * @throws Exception If failed. */ @Test public void testToStringCheckSimpleListRecursionPrevention() throws Exception { ArrayList<Object> list1 = new ArrayList<>(); ArrayList<Object> list2 = new ArrayList<>(); list2.add(list1); list1.add(list2); info(GridToStringBuilder.toString(ArrayList.class, list1)); info(GridToStringBuilder.toString(ArrayList.class, list2)); } /** * @throws Exception If failed. */ @Test public void testToStringCheckSimpleMapRecursionPrevention() throws Exception { HashMap<Object, Object> map1 = new HashMap<>(); HashMap<Object, Object> map2 = new HashMap<>(); map1.put("2", map2); map2.put("1", map1); info(GridToStringBuilder.toString(HashMap.class, map1)); info(GridToStringBuilder.toString(HashMap.class, map2)); } /** * @throws Exception If failed. */ @Test public void testToStringCheckListAdvancedRecursionPrevention() throws Exception { ArrayList<Object> list1 = new ArrayList<>(); ArrayList<Object> list2 = new ArrayList<>(); list2.add(list1); list1.add(list2); info(GridToStringBuilder.toString(ArrayList.class, list1, "name", list2)); info(GridToStringBuilder.toString(ArrayList.class, list2, "name", list1)); } /** * @throws Exception If failed. */ @Test public void testToStringCheckMapAdvancedRecursionPrevention() throws Exception { HashMap<Object, Object> map1 = new HashMap<>(); HashMap<Object, Object> map2 = new HashMap<>(); map1.put("2", map2); map2.put("1", map1); info(GridToStringBuilder.toString(HashMap.class, map1, "name", map2)); info(GridToStringBuilder.toString(HashMap.class, map2, "name", map1)); } /** * @throws Exception If failed. */ @Test public void testToStringCheckObjectRecursionPrevention() throws Exception { Node n1 = new Node(); Node n2 = new Node(); Node n3 = new Node(); Node n4 = new Node(); n1.name = "n1"; n2.name = "n2"; n3.name = "n3"; n4.name = "n4"; n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n3; n1.nodes = new Node[4]; n2.nodes = n1.nodes; n3.nodes = n1.nodes; n4.nodes = n1.nodes; n1.nodes[0] = n1; n1.nodes[1] = n2; n1.nodes[2] = n3; n1.nodes[3] = n4; String expN1 = n1.toString(); String expN2 = n2.toString(); String expN3 = n3.toString(); String expN4 = n4.toString(); info(expN1); info(expN2); info(expN3); info(expN4); info(GridToStringBuilder.toString("Test", "Appended vals", n1)); CyclicBarrier bar = new CyclicBarrier(4); IgniteInternalFuture<String> fut1 = GridTestUtils.runAsync(new BarrierCallable(bar, n1, expN1)); IgniteInternalFuture<String> fut2 = GridTestUtils.runAsync(new BarrierCallable(bar, n2, expN2)); IgniteInternalFuture<String> fut3 = GridTestUtils.runAsync(new BarrierCallable(bar, n3, expN3)); IgniteInternalFuture<String> fut4 = GridTestUtils.runAsync(new BarrierCallable(bar, n4, expN4)); fut1.get(3_000); fut2.get(3_000); fut3.get(3_000); fut4.get(3_000); } /** * Test class. */ private static class Node { /** */ @GridToStringInclude String name; /** */ @GridToStringInclude Node next; /** */ @GridToStringInclude Node[] nodes; /** {@inheritDoc} */ @Override public String toString() { return GridToStringBuilder.toString(Node.class, this); } } /** * Test class. */ private static class BarrierCallable implements Callable<String> { /** */ CyclicBarrier bar; /** */ Object obj; /** Expected value of {@code toString()} method. */ String exp; /** */ private BarrierCallable(CyclicBarrier bar, Object obj, String exp) { this.bar = bar; this.obj = obj; this.exp = exp; } /** {@inheritDoc} */ @Override public String call() throws Exception { for (int i = 0; i < 10; i++) { bar.await(); assertEquals(exp, obj.toString()); } return null; } } /** * JUnit. */ @Test public void testToStringPerformance() { TestClass1 obj = new TestClass1(); IgniteLogger log = log(); // Warm up. obj.toStringAutomatic(); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) obj.toStringManual(); log.info("Manual toString() took: " + (System.currentTimeMillis() - start) + "ms"); start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) obj.toStringAutomatic(); log.info("Automatic toString() took: " + (System.currentTimeMillis() - start) + "ms"); } /** * Test array print. * @param v value to get array class and fill array. * @param limit value of IGNITE_TO_STRING_COLLECTION_LIMIT. * @throws Exception if failed. */ private <T, V> void testArr(V v, int limit) throws Exception { T[] arrOf = (T[]) Array.newInstance(v.getClass(), limit + 1); Arrays.fill(arrOf, v); T[] arr = Arrays.copyOf(arrOf, limit); checkArrayOverflow(arrOf, arr, limit); } /** * Test array print. * * @throws Exception if failed. */ @Test public void testArrLimitWithRecursion() throws Exception { int limit = IgniteSystemProperties.getInteger(IGNITE_TO_STRING_COLLECTION_LIMIT, 100); ArrayList[] arrOf = new ArrayList[limit + 1]; Arrays.fill(arrOf, new ArrayList()); ArrayList[] arr = Arrays.copyOf(arrOf, limit); arrOf[0].add(arrOf); arr[0].add(arr); checkArrayOverflow(arrOf, arr, limit); } /** * @param arrOf Array. * @param arr Array copy. * @param limit Array limit. */ private void checkArrayOverflow(Object[] arrOf, Object[] arr, int limit) { String arrStr = GridToStringBuilder.arrayToString(arr); String arrOfStr = GridToStringBuilder.arrayToString(arrOf); // Simulate overflow StringBuilder resultSB = new StringBuilder(arrStr); resultSB.deleteCharAt(resultSB.length()-1); resultSB.append("... and ").append(arrOf.length - limit).append(" more]"); arrStr = resultSB.toString(); info(arrOfStr); info(arrStr); assertTrue("Collection limit error in array of type " + arrOf.getClass().getName() + " error, normal arr: <" + arrStr + ">, overflowed arr: <" + arrOfStr + ">", arrStr.equals(arrOfStr)); } /** * @throws Exception If failed. */ @Test public void testToStringCollectionLimits() throws Exception { int limit = IgniteSystemProperties.getInteger(IGNITE_TO_STRING_COLLECTION_LIMIT, 100); Object vals[] = new Object[] {Byte.MIN_VALUE, Boolean.TRUE, Short.MIN_VALUE, Integer.MIN_VALUE, Long.MIN_VALUE, Float.MIN_VALUE, Double.MIN_VALUE, Character.MIN_VALUE, new TestClass1()}; for (Object val : vals) testArr(val, limit); int[] intArr1 = new int[0]; assertEquals("[]", GridToStringBuilder.arrayToString(intArr1)); assertEquals("null", GridToStringBuilder.arrayToString(null)); int[] intArr2 = {1, 2, 3}; assertEquals("[1, 2, 3]", GridToStringBuilder.arrayToString(intArr2)); Object[] intArr3 = {2, 3, 4}; assertEquals("[2, 3, 4]", GridToStringBuilder.arrayToString(intArr3)); byte[] byteArr = new byte[1]; byteArr[0] = 1; assertEquals(Arrays.toString(byteArr), GridToStringBuilder.arrayToString(byteArr)); byteArr = Arrays.copyOf(byteArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(byteArr).contains("... and 1 more")); boolean[] boolArr = new boolean[1]; boolArr[0] = true; assertEquals(Arrays.toString(boolArr), GridToStringBuilder.arrayToString(boolArr)); boolArr = Arrays.copyOf(boolArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(boolArr).contains("... and 1 more")); short[] shortArr = new short[1]; shortArr[0] = 100; assertEquals(Arrays.toString(shortArr), GridToStringBuilder.arrayToString(shortArr)); shortArr = Arrays.copyOf(shortArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(shortArr).contains("... and 1 more")); int[] intArr = new int[1]; intArr[0] = 10000; assertEquals(Arrays.toString(intArr), GridToStringBuilder.arrayToString(intArr)); intArr = Arrays.copyOf(intArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(intArr).contains("... and 1 more")); long[] longArr = new long[1]; longArr[0] = 10000000; assertEquals(Arrays.toString(longArr), GridToStringBuilder.arrayToString(longArr)); longArr = Arrays.copyOf(longArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(longArr).contains("... and 1 more")); float[] floatArr = new float[1]; floatArr[0] = 1.f; assertEquals(Arrays.toString(floatArr), GridToStringBuilder.arrayToString(floatArr)); floatArr = Arrays.copyOf(floatArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(floatArr).contains("... and 1 more")); double[] doubleArr = new double[1]; doubleArr[0] = 1.; assertEquals(Arrays.toString(doubleArr), GridToStringBuilder.arrayToString(doubleArr)); doubleArr = Arrays.copyOf(doubleArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(doubleArr).contains("... and 1 more")); char[] cArr = new char[1]; cArr[0] = 'a'; assertEquals(Arrays.toString(cArr), GridToStringBuilder.arrayToString(cArr)); cArr = Arrays.copyOf(cArr, 101); assertTrue("Can't find \"... and 1 more\" in overflowed array string!", GridToStringBuilder.arrayToString(cArr).contains("... and 1 more")); Map<String, String> strMap = new TreeMap<>(); List<String> strList = new ArrayList<>(limit+1); TestClass1 testCls = new TestClass1(); testCls.strMap = strMap; testCls.strListIncl = strList; for (int i = 0; i < limit; i++) { strMap.put("k" + i, "v"); strList.add("e"); } checkColAndMap(testCls); } /** * @throws Exception If failed. */ @Test public void testToStringColAndMapLimitWithRecursion() throws Exception { int limit = IgniteSystemProperties.getInteger(IGNITE_TO_STRING_COLLECTION_LIMIT, 100); Map strMap = new TreeMap<>(); List strList = new ArrayList<>(limit+1); TestClass1 testClass = new TestClass1(); testClass.strMap = strMap; testClass.strListIncl = strList; Map m = new TreeMap(); m.put("m", strMap); List l = new ArrayList(); l.add(strList); strMap.put("k0", m); strList.add(l); for (int i = 1; i < limit; i++) { strMap.put("k" + i, "v"); strList.add("e"); } checkColAndMap(testClass); } /** * @param testCls Class with collection and map included in toString(). */ private void checkColAndMap(TestClass1 testCls) { String testClsStr = GridToStringBuilder.toString(TestClass1.class, testCls); testCls.strMap.put("kz", "v"); // important to add last element in TreeMap here testCls.strListIncl.add("e"); String testClsStrOf = GridToStringBuilder.toString(TestClass1.class, testCls); String testClsStrOfR = testClsStrOf.replaceAll("... and 1 more",""); info(testClsStr); info(testClsStrOf); info(testClsStrOfR); assertTrue("Collection limit error in Map or List, normal: <" + testClsStr + ">, overflowed: <" + testClsStrOf + ">", testClsStr.length() == testClsStrOfR.length()); } /** * @throws Exception If failed. */ @Test public void testToStringSizeLimits() throws Exception { int limit = IgniteSystemProperties.getInteger(IGNITE_TO_STRING_MAX_LENGTH, 10_000); int tailLen = limit / 10 * 2; StringBuilder sb = new StringBuilder(limit + 10); for (int i = 0; i < limit - 100; i++) sb.append('a'); String actual = GridToStringBuilder.toString(TestClass2.class, new TestClass2(sb.toString())); String exp = "TestClass2 [str=" + sb + ", nullArr=null]"; assertEquals(exp, actual); for (int i = 0; i < 110; i++) sb.append('b'); actual = GridToStringBuilder.toString(TestClass2.class, new TestClass2(sb.toString())); exp = "TestClass2 [str=" + sb + ", nullArr=null]"; assertEquals(exp.substring(0, limit - tailLen), actual.substring(0, limit - tailLen)); assertEquals(exp.substring(exp.length() - tailLen), actual.substring(actual.length() - tailLen)); assertTrue(actual.contains("... and")); assertTrue(actual.contains("skipped ...")); } /** * */ @Test public void testObjectPlusStringToString() { IgniteTxKey k = new IgniteTxKey(new KeyCacheObjectImpl(1, null, 1), 123); info(k.toString()); assertTrue("Wrong string: " + k, k.toString().startsWith("IgniteTxKey [")); } /** * */ @Test public void testHierarchy() { Wrapper w = new Wrapper(); Parent p = w.p; String hash = identity(p); checkHierarchy("Wrapper [p=Child [b=0, pb=Parent[] [null], super=Parent [a=0, pa=Parent[] [null]]]]", w); p.pa[0] = p; checkHierarchy("Wrapper [p=Child" + hash + " [b=0, pb=Parent[] [null], super=Parent [a=0, pa=Parent[] [Child" + hash + "]]]]", w); ((Child)p).pb[0] = p; checkHierarchy("Wrapper [p=Child" + hash + " [b=0, pb=Parent[] [Child" + hash + "], super=Parent [a=0, pa=Parent[] [Child" + hash + "]]]]", w); } /** * Test GridToStringBuilder memory consumption. */ @Test public void testMemoryConsumption() { int objCnt = 100; ThreadMXBean bean = (ThreadMXBean)ManagementFactory.getThreadMXBean(); TestClass2 obj = new TestClass2(new String(new char[1_000_000])); List<TestClass2> arr = new ArrayList<>(objCnt); for (int i = 1; i <= objCnt; i++) arr.add(new TestClass2(new String(new char[i]))); GridToStringBuilder.toString(TestClass2.class, obj); long allocated0 = bean.getThreadAllocatedBytes(Thread.currentThread().getId()); for (TestClass2 item : arr) GridToStringBuilder.toString(TestClass2.class, item); long allocated1 = bean.getThreadAllocatedBytes(Thread.currentThread().getId()); log.info("Memory allocated by GridToStringBuilder for " + objCnt + " objects: " + (allocated1 - allocated0)); assertTrue("Too much memory allocated by GridToStringBuilder: " + (allocated1 - allocated0), allocated1 - allocated0 < 1_000_000); } /** * @param exp Expected. * @param w Wrapper. */ private void checkHierarchy(String exp, Wrapper w) { String wS = w.toString(); info(wS); assertEquals(exp, wS); } /** * Test class. */ private static class TestClass1 { /** */ @SuppressWarnings("unused") @GridToStringOrder(0) private String id = "1234567890"; /** */ @SuppressWarnings("unused") private int intVar; /** */ @SuppressWarnings("unused") @GridToStringInclude(sensitive = true) private long longVar; /** */ @SuppressWarnings("unused") @GridToStringOrder(1) private final UUID uuidVar = UUID.randomUUID(); /** */ @SuppressWarnings("unused") private boolean boolVar; /** */ @SuppressWarnings("unused") private byte byteVar; /** */ @SuppressWarnings("unused") private String name = "qwertyuiopasdfghjklzxcvbnm"; /** */ @SuppressWarnings("unused") private final Integer finalInt = 2; /** */ @SuppressWarnings("unused") private List<String> strList; /** */ @SuppressWarnings("unused") @GridToStringInclude private Map<String, String> strMap; /** */ @SuppressWarnings("unused") @GridToStringInclude private List<String> strListIncl; /** */ @SuppressWarnings("unused") private final Object obj = new Object(); /** */ @SuppressWarnings("unused") private ReadWriteLock lock; /** * @return Manual string. */ String toStringManual() { StringBuilder buf = new StringBuilder(); buf.append(getClass().getSimpleName()).append(" ["); buf.append("id=").append(id).append(", "); buf.append("uuidVar=").append(uuidVar).append(", "); buf.append("intVar=").append(intVar).append(", "); if (S.includeSensitive()) buf.append("longVar=").append(longVar).append(", "); buf.append("boolVar=").append(boolVar).append(", "); buf.append("byteVar=").append(byteVar).append(", "); buf.append("name=").append(name).append(", "); buf.append("finalInt=").append(finalInt).append(", "); buf.append("strMap=").append(strMap).append(", "); buf.append("strListIncl=").append(strListIncl); buf.append("]"); return buf.toString(); } /** * @return Automatic string. */ String toStringAutomatic() { return S.toString(TestClass1.class, this); } /** * @return Automatic string with additional parameters. */ String toStringWithAdditionalAutomatic() { return S.toString(TestClass1.class, this, "newParam1", 1, false, "newParam2", 2, true); } /** * @return Manual string with additional parameters. */ String toStringWithAdditionalManual() { StringBuilder s = new StringBuilder(toStringManual()); s.setLength(s.length() - 1); s.append(", newParam1=").append(1); if (S.includeSensitive()) s.append(", newParam2=").append(2); s.append(']'); return s.toString(); } } /** * */ private static class TestClass2{ /** */ @SuppressWarnings("unused") @GridToStringInclude private String str; /** */ @GridToStringInclude private Object[] nullArr; /** * @param str String. */ TestClass2(String str) { this.str = str; } } /** * */ private static class Parent { /** */ private int a; /** */ @GridToStringInclude private Parent pa[] = new Parent[1]; /** {@inheritDoc} */ @Override public String toString() { return S.toString(Parent.class, this); } } /** * */ private static class Child extends Parent { /** */ private int b; /** */ @GridToStringInclude private Parent pb[] = new Parent[1]; /** {@inheritDoc} */ @Override public String toString() { return S.toString(Child.class, this, super.toString()); } } /** * */ private static class Wrapper { /** */ @GridToStringInclude Parent p = new Child(); /** {@inheritDoc} */ @Override public String toString() { return S.toString(Wrapper.class, this); } } }
30.543949
119
0.595904
218fd8afd0aa480154f9f3cc6b4aa4b1c460ca77
363
package br.com.zupacademy.vitor.casadocodigo.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import br.com.zupacademy.vitor.casadocodigo.modelo.Categoria; @Repository public interface CategoriaRepository extends JpaRepository<Categoria, Long>{ Categoria findByNome(String nome); }
25.928571
76
0.842975
60f6287078e1b3d48f54836e7bd2cab853b47e53
3,765
/* * 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.jclouds.abiquo.monitor.functions; import static org.testng.Assert.assertEquals; import org.easymock.EasyMock; import org.jclouds.abiquo.domain.cloud.VirtualAppliance; import org.jclouds.abiquo.monitor.MonitorStatus; import org.jclouds.rest.ApiContext; import org.testng.annotations.Test; import com.abiquo.server.core.cloud.VirtualApplianceDto; import com.abiquo.server.core.cloud.VirtualApplianceState; import com.google.common.base.Function; /** * Unit tests for the {@link VirtualApplianceDeployMonitor} function. * * @author Serafin Sedano */ @Test(groups = "unit", testName = "VirtualApplianceDeployMonitorTest") public class VirtualApplianceDeployMonitorTest { @Test(expectedExceptions = NullPointerException.class) public void testInvalidNullArgument() { Function<VirtualAppliance, MonitorStatus> function = new VirtualApplianceDeployMonitor(); function.apply(null); } public void testReturnDone() { VirtualApplianceState[] states = { VirtualApplianceState.DEPLOYED }; checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceDeployMonitor(), states, MonitorStatus.DONE); } public void testReturnFail() { VirtualApplianceState[] states = { VirtualApplianceState.NEEDS_SYNC, VirtualApplianceState.UNKNOWN, VirtualApplianceState.NOT_DEPLOYED }; checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceDeployMonitor(), states, MonitorStatus.FAILED); } public void testReturnContinue() { VirtualApplianceState[] states = { VirtualApplianceState.LOCKED }; checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceDeployMonitor(), states, MonitorStatus.CONTINUE); checkStatesReturn(new MockVirtualApplianceFailing(), new VirtualApplianceDeployMonitor(), states, MonitorStatus.CONTINUE); } private void checkStatesReturn(final MockVirtualAppliance vapp, final Function<VirtualAppliance, MonitorStatus> function, final VirtualApplianceState[] states, final MonitorStatus expectedStatus) { for (VirtualApplianceState state : states) { vapp.setState(state); assertEquals(function.apply(vapp), expectedStatus); } } private static class MockVirtualAppliance extends VirtualAppliance { private VirtualApplianceState state; @SuppressWarnings("unchecked") public MockVirtualAppliance() { super(EasyMock.createMock(ApiContext.class), new VirtualApplianceDto()); } @Override public VirtualApplianceState getState() { return state; } public void setState(final VirtualApplianceState state) { this.state = state; } } private static class MockVirtualApplianceFailing extends MockVirtualAppliance { @Override public VirtualApplianceState getState() { throw new RuntimeException("This mock class always fails to get the state"); } } }
36.911765
121
0.745817
a978f8631a8d1f4d721841017f7d5aff96b1349a
965
package com.alibaba.tesla.tkgone.server.services.sreworks; import com.alibaba.fastjson.JSONObject; import com.alibaba.tesla.tkgone.server.services.config.BaseConfigService; import lombok.extern.log4j.Log4j; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * @author yangjinghua */ @Log4j @Service public class SreworksSearchQueryService extends BaseConfigService { public List<JSONObject> getAllTypes(String category) { List<String> indexs = categoryConfigService.getCategoryIndexes(category).toJavaList(String.class); List<JSONObject> results = new ArrayList<>(); for (String index : indexs) { String alias = categoryConfigService.getCategoryTypeAlias(category, index); JSONObject result = new JSONObject(); result.put("index", index); result.put("alias", alias); results.add(result); } return results; } }
29.242424
105
0.716062
bd5a407aae5edaa19f1626ea42233b8ba313e60a
1,295
//给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 // // // // 示例: // // 输入:"Let's take LeetCode contest" //输出:"s'teL ekat edoCteeL tsetnoc" // // // // // 提示: // // // 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 // // Related Topics 字符串 // 👍 268 👎 0 package me.bob.leetcode.editor.cn; /** * 557 反转字符串中的单词 III * 2021-01-29 17:15:55 * 思路:双指针 */ public class ReverseWordsInAStringIii { public static void main(String[] args) { Solution solution = new ReverseWordsInAStringIii().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public String reverseWords(String s) { StringBuilder sb = new StringBuilder(); char[] chars = s.toCharArray(); int i = 0, j = 0; while (j < chars.length) { while (j < chars.length && chars[j] != ' ') { j++; } for (int k = j - 1; k >= i; k--) { sb.append(chars[k]); } if (j < chars.length) { sb.append(chars[j++]); i = j; } } return sb.toString(); } } //leetcode submit region end(Prohibit modification and deletion) }
21.949153
74
0.504247
68a60f92c6ec4a7f6d2442116ab6497c366c3f5b
2,188
/** * */ package com.gfi.chequera.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * @author Rolando Castillo * @email [email protected] */ @Entity @Table(name="bancos") public class Bancos{ /** * */ @Id @GeneratedValue(strategy = GenerationType.AUTO) private int idBancos; private String bDireccion; private String bSucursal; private String bNombre; private String bTelefono; private boolean bStatus; @OneToMany(fetch=FetchType.EAGER, mappedBy="banco") private Set<Chequera> chequera = new HashSet<>(); public Bancos() { super(); // TODO Auto-generated constructor stub } public Bancos(int idBancos, String bDireccion, String bSucursal, String bNombre, String bTelefono, boolean bStatus, Set<Chequera> chequera) { super(); this.idBancos = idBancos; this.bDireccion = bDireccion; this.bSucursal = bSucursal; this.bNombre = bNombre; this.bTelefono = bTelefono; this.bStatus = bStatus; this.chequera = chequera; } public int getIdBancos() { return idBancos; } public void setIdBancos(int idBancos) { this.idBancos = idBancos; } public String getbDireccion() { return bDireccion; } public void setbDireccion(String bDireccion) { this.bDireccion = bDireccion; } public String getbSucursal() { return bSucursal; } public void setbSucursal(String bSucursal) { this.bSucursal = bSucursal; } public String getbNombre() { return bNombre; } public void setbNombre(String bNombre) { this.bNombre = bNombre; } public String getbTelefono() { return bTelefono; } public void setbTelefono(String bTelefono) { this.bTelefono = bTelefono; } public boolean isbStatus() { return bStatus; } public void setbStatus(boolean bStatus) { this.bStatus = bStatus; } public Set<Chequera> getChequera() { return chequera; } public void setChequera(Set<Chequera> chequera) { this.chequera = chequera; } }
17.09375
116
0.723492
6b935a0cf4ff537e098c6cf158e0dcef1a65de24
9,605
/* * 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.geode.internal.cache; import static org.apache.geode.cache.EvictionAction.OVERFLOW_TO_DISK; import static org.apache.geode.cache.EvictionAttributes.createLRUEntryAttributes; import static org.apache.geode.test.dunit.Host.getHost; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.geode.cache.Cache; import org.apache.geode.cache.DiskStore; import org.apache.geode.cache.DiskStoreFactory; import org.apache.geode.cache.PartitionAttributesFactory; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionFactory; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.cache.CacheTestCase; import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder; /** * This test verifies the size API for 100 thousand put operations (done synch/asynch) on * PartitionedRegions with different combinations of Scope and Redundancy (Scope DIST_ACK, * Redundancy 1 AND Scope DIST_NO_ACK, Redundancy 0). */ public class PartitionedRegionSizeDUnitTest extends CacheTestCase { private static final String DISK_STORE_NAME = "DISKSTORE"; private static final String REGION_NAME = "PR"; private static final int CNT = 100; private static final int TOTAL_NUMBER_OF_BUCKETS = 5; private File overflowDirectory; private VM vm0; private VM vm1; private VM vm2; private VM vm3; @Rule public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder(); @Before public void setUp() throws Exception { vm0 = getHost(0).getVM(0); vm1 = getHost(0).getVM(1); vm2 = getHost(0).getVM(2); vm3 = getHost(0).getVM(3); overflowDirectory = temporaryFolder.newFolder("overflowDir"); } /** * This test method invokes methods doing size validation on PRs. */ @Test public void testSize() throws Exception { // Create PRs with dataStore on 3 VMs vm0.invoke(() -> createPartitionedRegion(200, 1)); vm1.invoke(() -> createPartitionedRegion(200, 1)); vm2.invoke(() -> createPartitionedRegion(200, 1)); // Create only accessor on 4th VM vm3.invoke(() -> createPartitionedRegion(0, 1)); // Do put operations on PR synchronously. vm3.invoke(() -> { Region<Integer, Integer> region = getRegion(REGION_NAME); for (int k = 0; k < CNT; k++) { region.put(k, k); } }); // Validate the size against the total put operations vm3.invoke(() -> { Region region = getRegion(REGION_NAME); assertThat(region.size()).isEqualTo(CNT); }); } /** * Regression test for TRAC #39868 * * <p> * TRAC #39868: PartitionMemberDetails.getSize() reports negative PR sizes when redundancy is 0 */ @Test public void testBug39868() throws Exception { vm0.invoke(() -> createPartitionedRegion(200, 1)); vm0.invoke(() -> { Region<Integer, byte[]> region = getRegion(REGION_NAME); for (int i = 0; i < 100; i++) { region.put(i * TOTAL_NUMBER_OF_BUCKETS, new byte[100]); } }); vm1.invoke(() -> createPartitionedRegion(200, 1)); vm0.invoke(() -> { Region<Integer, byte[]> region = getRegion(REGION_NAME); for (int i = 0; i < 100; i++) { region.destroy(i * TOTAL_NUMBER_OF_BUCKETS); } }); vm1.invoke(() -> { PartitionedRegion partitionedRegion = getPartitionedRegion(REGION_NAME); long bytes = partitionedRegion.getDataStore().currentAllocatedMemory(); assertThat(bytes).isEqualTo(0); }); } @Test public void testByteSize() throws Exception { vm0.invoke(() -> createPartitionedRegion(200, 1)); vm1.invoke(() -> createPartitionedRegion(200, 1)); long bucketSizeWithOneEntry = vm0.invoke(() -> { Region<Integer, byte[]> region = getRegion(REGION_NAME); region.put(0, new byte[100]); PartitionedRegion partitionedRegion = (PartitionedRegion) region; PartitionedRegionDataStore dataStore = partitionedRegion.getDataStore(); long size = dataStore.getBucketSize(0); for (int i = 1; i < 100; i++) { region.put(i * TOTAL_NUMBER_OF_BUCKETS, new byte[100]); } assertThat(dataStore.getBucketsManaged()).isEqualTo((short) 1); // make sure the size is proportional to the amount of data assertThat(dataStore.getBucketSize(0)).isEqualTo(100 * size); // destroy and invalidate entries and make sure the size goes down for (int i = 0; i < 25; i++) { region.destroy(i * TOTAL_NUMBER_OF_BUCKETS); } for (int i = 25; i < 50; i++) { region.invalidate(i * TOTAL_NUMBER_OF_BUCKETS); } assertThat(dataStore.getBucketSize(0)).isEqualTo(50 * size); // put some larger values in and make sure the size goes up for (int i = 50; i < 75; i++) { region.put(i * TOTAL_NUMBER_OF_BUCKETS, new byte[150]); } // Now put in some smaller values and see if the size balances out for (int i = 75; i < 100; i++) { region.put(i * TOTAL_NUMBER_OF_BUCKETS, new byte[50]); } assertThat(dataStore.getBucketSize(0)).isEqualTo(50 * size); return size; }); vm1.invoke(() -> { PartitionedRegion partitionedRegion = getPartitionedRegion(REGION_NAME); long bucketSize = partitionedRegion.getDataStore().getBucketSize(0); assertThat(bucketSize).isEqualTo(50 * bucketSizeWithOneEntry); }); vm1.invoke(() -> { PartitionedRegion partitionedRegion = getPartitionedRegion(REGION_NAME); PartitionedRegionDataStore dataStore = partitionedRegion.getDataStore(); assertThat(dataStore.currentAllocatedMemory()).isEqualTo(50 * bucketSizeWithOneEntry); }); } @Test public void testByteSizeWithEviction() throws Exception { vm0.invoke(() -> createPartitionedRegionWithOverflow(200, 1)); long bucketSizeWithOneEntry = vm0.invoke(() -> { Region<Integer, byte[]> region = getRegion(REGION_NAME); region.put(0, new byte[100]); PartitionedRegion partitionedRegion = (PartitionedRegion) region; PartitionedRegionDataStore dataStore = partitionedRegion.getDataStore(); long size = dataStore.getBucketSize(0); for (int i = 1; i < 100; i++) { region.put(i * TOTAL_NUMBER_OF_BUCKETS, new byte[100]); } assertThat(dataStore.getBucketsManaged()).isEqualTo((short) 1); return size; }); vm0.invoke(() -> { Region<Integer, byte[]> region = getRegion(REGION_NAME); PartitionedRegion partitionedRegion = (PartitionedRegion) region; PartitionedRegionDataStore dataStore = partitionedRegion.getDataStore(); // there should only be 2 items in memory assertThat(dataStore.currentAllocatedMemory()).isEqualTo(2 * bucketSizeWithOneEntry); // fault something else into memory and check again. region.get(82 * TOTAL_NUMBER_OF_BUCKETS); assertThat(dataStore.currentAllocatedMemory()).isEqualTo(2 * bucketSizeWithOneEntry); }); } private void createPartitionedRegionWithOverflow(final int localMaxMemory, final int redundancy) { Cache cache = getCache(); File[] diskDirs = new File[] {overflowDirectory}; DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory(); diskStoreFactory.setDiskDirs(diskDirs); DiskStore diskStore = diskStoreFactory.create(DISK_STORE_NAME); PartitionAttributesFactory paf = new PartitionAttributesFactory(); paf.setRedundantCopies(redundancy); paf.setLocalMaxMemory(localMaxMemory); paf.setTotalNumBuckets(TOTAL_NUMBER_OF_BUCKETS); RegionFactory regionFactory = getCache().createRegionFactory(RegionShortcut.PARTITION); regionFactory.setDiskStoreName(diskStore.getName()); regionFactory.setDiskSynchronous(true); regionFactory.setEvictionAttributes(createLRUEntryAttributes(2, OVERFLOW_TO_DISK)); regionFactory.setPartitionAttributes(paf.create()); regionFactory.create(REGION_NAME); } private void createPartitionedRegion(final int localMaxMemory, final int redundancy) { PartitionAttributesFactory paf = new PartitionAttributesFactory(); paf.setRedundantCopies(redundancy); paf.setLocalMaxMemory(localMaxMemory); paf.setTotalNumBuckets(TOTAL_NUMBER_OF_BUCKETS); RegionFactory regionFactory = getCache().createRegionFactory(RegionShortcut.PARTITION); regionFactory.setPartitionAttributes(paf.create()); regionFactory.create(REGION_NAME); } private Region getRegion(String regionName) { return getCache().getRegion(regionName); } private PartitionedRegion getPartitionedRegion(String regionName) { return (PartitionedRegion) getCache().getRegion(regionName); } }
35.574074
100
0.710984
e68f145df513dce6e423c79c8a3303310402e54e
864
package edu.rice.cs.hpcviewer.ui.experiment; import java.io.File; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import edu.rice.cs.hpcbase.map.ProcedureAliasMap; import edu.rice.cs.hpcdata.experiment.Experiment; public class ExperimentJob extends Job { final private String filename; private Exception e; public ExperimentJob(String name, String filename) { super(name); this.filename = filename; } @Override protected IStatus run(IProgressMonitor monitor) { Experiment experiment = new Experiment(); try { experiment.open( new File(filename), new ProcedureAliasMap(), true ); } catch (Exception e) { this.e = e; } return Status.OK_STATUS; } public Exception getException() { return e; } }
20.093023
72
0.746528
4013049dfe3cf7f59a544b2c31f0dec1b7fa7239
970
package se.mickelus.tetra.effect.potion; import net.minecraft.entity.LivingEntity; import net.minecraft.potion.Effect; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.EffectType; import net.minecraft.util.DamageSource; public class BleedingPotionEffect extends Effect { public static BleedingPotionEffect instance; public BleedingPotionEffect() { super(EffectType.HARMFUL, 0x880000); setRegistryName("bleeding"); instance = this; } @Override public void performEffect(LivingEntity entity, int amplifier) { entity.attackEntityFrom(DamageSource.GENERIC, amplifier); } @Override public boolean isReady(int duration, int amplifier) { return duration % 10 == 0; } @Override public boolean shouldRender(EffectInstance effect) { return false; } @Override public boolean shouldRenderHUD(EffectInstance effect) { return false; } }
24.871795
67
0.712371
a9867e3b06ebc8c2405b9fb00d46c1fd1b63a679
2,002
package org.python.core; import org.python.annotations.ExposedMethod; import org.python.annotations.ExposedSlot; import org.python.annotations.ExposedType; import org.python.annotations.SlotFunc; @ExposedType(name = "callable_iterator") public class PyCallIter extends PyIterator { //note: Already implements Traverseproc, inheriting it from PyIterator private PyObject callable; private PyObject sentinel; public PyCallIter(PyObject callable, PyObject sentinel) { if (!callable.isCallable()) { throw Py.TypeError("iter(v, w): v must be callable"); } this.callable = callable; this.sentinel = sentinel; } @ExposedSlot(SlotFunc.ITER) public static PyObject __iter__(PyObject self) { return self; } @ExposedSlot(SlotFunc.ITER_NEXT) public static PyObject callable_iterator___next__(PyObject obj) { PyCallIter self = (PyCallIter) obj; if (self.callable == null) { throw Py.StopIteration(); } PyObject result; result = Abstract.PyObject_Call(Py.getThreadState(), self.callable, Py.EmptyObjects, Py.NoKeywords); if (result == null || self.sentinel.richCompare(result, CompareOp.EQ).isTrue()) { self.callable = null; throw Py.StopIteration(); } return result; } /* Traverseproc implementation */ @Override public int traverse(Visitproc visit, Object arg) { int retValue = super.traverse(visit, arg); if (retValue != 0) { return retValue; } if (callable != null) { retValue = visit.visit(callable, arg); if (retValue != 0) { return retValue; } } return sentinel != null ? visit.visit(sentinel, arg) : 0; } @Override public boolean refersDirectlyTo(PyObject ob) { return ob != null && (ob == callable || ob == sentinel || super.refersDirectlyTo(ob)); } }
29.880597
108
0.625375
bc7a66b5066270514f8a7d3260e816e709c1bac4
6,598
package org.evomaster.client.java.instrumentation.coverage.methodreplacement.classes; import org.evomaster.client.java.instrumentation.coverage.methodreplacement.DateTimeParsingUtils; import org.evomaster.client.java.instrumentation.coverage.methodreplacement.DistanceHelper; import org.evomaster.client.java.instrumentation.coverage.methodreplacement.MethodReplacementClass; import org.evomaster.client.java.instrumentation.coverage.methodreplacement.Replacement; import org.evomaster.client.java.instrumentation.heuristic.Truthness; import org.evomaster.client.java.instrumentation.heuristic.TruthnessUtils; import org.evomaster.client.java.instrumentation.shared.ReplacementType; import org.evomaster.client.java.instrumentation.shared.StringSpecialization; import org.evomaster.client.java.instrumentation.shared.StringSpecializationInfo; import org.evomaster.client.java.instrumentation.staticstate.ExecutionTracer; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.chrono.ChronoLocalDateTime; import java.time.format.DateTimeParseException; import java.util.Objects; public class LocalDateTimeClassReplacement implements MethodReplacementClass { private static long getMillis(ChronoLocalDateTime<?> chronoLocalDateTime) { return chronoLocalDateTime.atZone(ZoneOffset.UTC).toInstant().toEpochMilli(); } private static Truthness getIsBeforeTruthness(ChronoLocalDateTime<?> caller, ChronoLocalDateTime<?> when) { Objects.requireNonNull(caller); Objects.requireNonNull(when); final long a = getMillis(caller); final long b = getMillis(when); /** * We use the same gradient that HeuristicsForJumps.getForValueComparison() * used for IF_ICMPLT, ie, a < b */ return TruthnessUtils.getLessThanTruthness(a, b); } @Override public Class<?> getTargetClass() { return LocalDateTime.class; } /** * Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30. * The string must represent a valid date-time and is parsed using DateTimeFormatter.ISO_LOCAL_DATE_TIME. * * @param text * @param idTemplate * @return */ @Replacement(type = ReplacementType.EXCEPTION, replacingStatic = true) public static LocalDateTime parse(CharSequence text, String idTemplate) { if (text != null && ExecutionTracer.isTaintInput(text.toString())) { ExecutionTracer.addStringSpecialization(text.toString(), new StringSpecializationInfo(StringSpecialization.ISO_LOCAL_DATE_TIME, null)); } if (idTemplate == null) { return LocalDateTime.parse(text); } try { LocalDateTime res = LocalDateTime.parse(text); ExecutionTracer.executedReplacedMethod(idTemplate, ReplacementType.EXCEPTION, new Truthness(1, 0)); return res; } catch (DateTimeParseException | NullPointerException ex) { double h = DateTimeParsingUtils.getHeuristicToISOLocalDateTimeParsing(text); ExecutionTracer.executedReplacedMethod(idTemplate, ReplacementType.EXCEPTION, new Truthness(h, 1)); throw ex; } } @Replacement(type = ReplacementType.BOOLEAN) public static boolean equals(LocalDateTime caller, Object anObject, String idTemplate) { Objects.requireNonNull(caller); if (idTemplate == null) { return caller.equals(anObject); } final Truthness t; if (anObject == null || !(anObject instanceof LocalDateTime)) { t = new Truthness(DistanceHelper.H_REACHED_BUT_NULL, 1d); } else { LocalDateTime anotherLocalDateTime = (LocalDateTime) anObject; if (caller.equals(anotherLocalDateTime)) { t = new Truthness(1d, 0d); } else { double base = DistanceHelper.H_NOT_NULL; double distance = DistanceHelper.getDistanceToEquality(caller, anotherLocalDateTime); double h = base + (1 - base) / (1 + distance); t = new Truthness(h, 1d); } } ExecutionTracer.executedReplacedMethod(idTemplate, ReplacementType.BOOLEAN, t); return caller.equals(anObject); } @Replacement(type = ReplacementType.BOOLEAN) public static boolean isBefore(LocalDateTime caller, ChronoLocalDateTime<?> other, String idTemplate) { Objects.requireNonNull(caller); // might throw NPE if when is null if (idTemplate == null) { return caller.isBefore(other); } final Truthness t; if (other == null) { t = new Truthness(DistanceHelper.H_REACHED_BUT_NULL, 1d); } else { t = getIsBeforeTruthness(caller, other); } ExecutionTracer.executedReplacedMethod(idTemplate, ReplacementType.BOOLEAN, t); return caller.isBefore(other); } @Replacement(type = ReplacementType.BOOLEAN) public static boolean isAfter(LocalDateTime caller, ChronoLocalDateTime<?> other, String idTemplate) { Objects.requireNonNull(caller); // might throw NPE if when is null if (idTemplate == null) { return caller.isAfter(other); } final Truthness t; if (other == null) { t = new Truthness(DistanceHelper.H_REACHED_BUT_NULL, 1d); } else { t = getIsBeforeTruthness(other, caller); } ExecutionTracer.executedReplacedMethod(idTemplate, ReplacementType.BOOLEAN, t); return caller.isAfter(other); } @Replacement(type = ReplacementType.BOOLEAN) public static boolean isEqual(LocalDateTime caller, ChronoLocalDateTime<?> other, String idTemplate) { Objects.requireNonNull(caller); if (idTemplate == null) { return caller.isEqual(other); } final Truthness t; if (other == null) { t = new Truthness(DistanceHelper.H_REACHED_BUT_NULL, 1d); } else { if (caller.isEqual(other)) { t = new Truthness(1d, 0d); } else { double base = DistanceHelper.H_NOT_NULL; double distance = DistanceHelper.getDistanceToEquality(caller, other); double h = base + (1 - base) / (1 + distance); t = new Truthness(h, 1d); } } ExecutionTracer.executedReplacedMethod(idTemplate, ReplacementType.BOOLEAN, t); return caller.isEqual(other); } }
38.811765
111
0.670658
02ef6d1bd76f2fdda79ee1b3cdf5fcb1036e0f5c
4,369
package salesTaxes.impl; import salesTaxes.exc.UnclosedBasketException; public class Basket { private int basketNumber; private StringBuilder basketItems; private double total; private double basketSalesTaxes; // LinkedList<Item> itemBasketList; private boolean closed; /** * Create a Basket instance without set his basket sequence number. */ public Basket() { basketItems = new StringBuilder(); total = 0.0; basketSalesTaxes = 0.0; // itemBasketList=new LinkedList<Item>(); closed = false; } /** * Create a Basket instance setting the basket sequence number for this * object. * @param i the basket sequence number. */ public Basket(int i) { // TODO Auto-generated constructor stub basketItems = new StringBuilder(); total = 0.0; basketSalesTaxes = 0.0; // itemBasketList=new LinkedList<Item>(); closed = false; this.setBasketNumber(i); } /** * This method finalize the basket adding his total items costs and Sales * Taxes. */ public void closeBasket() { this.basketItems.append("Sales Taxes: " + formatDecimals(getBasketSalesTaxes()) + "\r\n" + "Total: " + formatDecimals(getBasketTotal()) + "\r\n\r\n"); closed = true; } //update total basket cost adding a the cost of an item taxs included private void addItemToTotal(double itemTotal) { this.total += itemTotal; this.total=(Math.round((this.total)*100)/ 100.0); } /** * Set the basket serial number for the instance that call it. * @param basketNumber an integer representing his sequence number*/ public void setBasketNumber(int basketNumber) { this.basketNumber = basketNumber; } /* * Add an item Sale Tax to the basket total Ssale Tax. * param basketItemSaleTax: a double representing the Sale Tax amount to add*/ private void addBasketItemSaleTax(double basketItemSaleTax) { this.basketSalesTaxes += basketItemSaleTax; this.basketSalesTaxes=(Math.round((this.basketSalesTaxes)*100)/ 100.0); } /** * Add an Item object to the basket and update the total basket costs an taxes with focus on Sales Taxes for items in the basket * @param item a fully configured item to add to the basket * */ public void addItem(Item item) { // TODO Auto-generated method stub double itemTotalCost = (Math.round((item.getTotalTaxAmount() + item.getGoodValue())*100)/ 100.0) ; // itemBasketList.add(item); addBasketItemSaleTax(Math.round(item.getTotalTaxAmount()*100)/ 100.0); addItemToTotal(itemTotalCost); this.basketItems.append("1 " + item.getName() + ": " + formatDecimals(itemTotalCost) + "\r\n"); } /** * @return a double representing the basket total cost taxes included. * */ public double getBasketTotal() { // TODO Auto-generated method stub return this.total; } /** * @return a String representation of all the items in the basket in the following form:<br> * [quantity] [Item name]: [full item cost tax included] * */ public String getBasketItems() { // TODO Auto-generated method stub return basketItems.toString(); } /** * @return a double representing the total of Sales Taxes for the basket. * */ public double getBasketSalesTaxes() { // TODO Auto-generated method stub return basketSalesTaxes; } /** * @return an integer representing the sequence number of the basket. * */ public int getBasketNumber() { // TODO Auto-generated method stub return this.basketNumber; } /** * @return a human readable String representing the sequence number of the basket. * */ public String getBasketNumberString() { // TODO Auto-generated method stub return "Output " + this.getBasketNumber() + ":\r\n"; } /** * @param d a double to be formatted with two decimal digits. * @return a String representing a double formatted to have two decimal digits. * */ public String formatDecimals(double d) { String num = "" + d; num = (num.substring(num.indexOf(".") + 1, num.length())).length() == 1 ? num + "0" : num; return num; } /** * @return a human readable String representing all the basket items and costs with focus on total and Sale Taxes. * @throws UnclosedBasketException if basket was not closed by method closeBasket() * */ public String toStringValue() throws UnclosedBasketException { if (closed) return getBasketNumberString() + getBasketItems(); else throw new UnclosedBasketException(); } }
30.131034
129
0.706798
e15a6b11fecfcf37ff57f529b71e915de1f7d2bb
2,897
class IndeksertListe <T> extends Lenkeliste<T> { //Setter inn x i listen i posisjon pos der 0<=pos<=stoerrelse(). public void leggTil (int pos, T x) { if (pos < 0 || pos > antiBruk) //hvis gitt pos er større enn 0 eller større enn antiBruk throw new UgyldigListeindeks(pos); Node nodeTo = new Node(x); //lager ny node Node tmp = forste; //oppretter temporary som utgangspunkt. if(pos == 0){ nodeTo.neste = forste; forste = nodeTo; } else { // går videre i lenken hvis "tmp" peker på en node for(int i = 0; i < pos-1; i++){ tmp = tmp.neste; } nodeTo.neste = tmp.neste; // Peker til objekt etter gitt posisjon tmp.neste = nodeTo; // lagre temp-noden som neste-peker for den nye noden i gitt posisjonen } antiBruk++; //Øker ant noder i lenken return; } //Kaller på Ugyldighetsklassen fra oppgaveteksten, lovlig pos er 0<=pos<stoerrelse(). public void sett (int pos, T x) { if (pos < 0 || pos >= storrelse()|| forste == null) throw new UgyldigListeindeks(pos); Node a = forste; for(int i = 0; i < pos; i++) { a = a.neste; } a.data = x; return; } // erstatter elementet i pos med x. //Skal hente elementet i gitt posisjon der 0<=pos<stoerrelse() public T hent (int pos) { if (pos < 0 || pos >= storrelse() || forste == null) throw new UgyldigListeindeks(pos); Node tmp = forste; for(int i = 0; i < pos; i++){ tmp = tmp.neste; } return tmp.data; } //fjerner elementet i pos der 0<=pos<stoerrelse(), og returnere det. public T fjern(int pos){ if (pos < 0 || pos >= storrelse() || forste == null) throw new UgyldigListeindeks(pos); Node tmp = forste; Node forrige = forste; // dersom første node skal fjernes if(pos == 0){ forste = tmp.neste; } else { //stopper på pos før den pos som fjernes for(int i = 0; i < pos-1; i++){ tmp = tmp.neste; } forrige = tmp.neste; // lagrer noden som fjernes if(forrige.neste != null){ // forrige node må peke til den neste tmp.neste = forrige.neste; } else{ tmp.neste = null; } tmp = forrige; // noden som er fjernet er nå tmp } antiBruk--; //reduserer antalliBruk da vi har fjernet en. return tmp.data; //returner data til tmp som vi fjernet. } } // E2: Sjekk klassen med testene i TestIndeksertListe.java. // - Ja, den kjører feilfritt :-)
24.760684
103
0.512599
f8ba834aaed79092cce873127b955689e1fd3e44
297
package com.car.modules.car.dao; import com.car.modules.car.entity.CategoryEntity; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * * * @author lzp * @email [email protected] * @date 2019-01-23 00:54:45 */ public interface CategoryDao extends BaseMapper<CategoryEntity> { }
18.5625
65
0.737374
4cb713c99f4eeca8ec7a4d3f8fa8ab769727fb0f
2,107
package com.hoster.data; import java.util.LinkedHashMap; import java.util.Map; public class Directory { private String path; private String require; private String allowOverride; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getRequire() { return require; } public void setRequire(String require) { this.require = require; } public String getAllowOverride() { return allowOverride; } public void setAllowOverride(String allowOverride) { this.allowOverride = allowOverride; } public boolean isValid() { return (getRequire() != null && !getRequire().isEmpty()) || (getAllowOverride() != null && !getAllowOverride().isEmpty()); } public String parseToXML() { return parseToXML(false); } public String parseToXML(boolean extraTab) { if (isValid()) { StringBuilder out = new StringBuilder(); Map<String, String> data = new LinkedHashMap<>(); data.put("AllowOverride", getAllowOverride()); data.put("Require", getRequire()); if (extraTab) { out.append("\t"); } out.append("<Directory \"").append(getPath()).append("\">\n"); insertTagsToXML(out, data, extraTab); if (extraTab) { out.append("\t"); } out.append("</Directory>"); return out.toString(); } return ""; } private void insertTagsToXML(StringBuilder out, Map<String, String> data, boolean extraTab) { for (Map.Entry<String, String> entry : data.entrySet()) { if (entry.getValue() != null && !entry.getValue().isEmpty()) { if (extraTab) { out.append("\t"); } out.append("\t").append(entry.getKey()).append(" ").append(entry.getValue()).append("\n"); } } } }
22.655914
106
0.532511
46d9f61a9b48a9fdbb8649e779dddb8ba9149d41
241
package com.hss01248.net.util; import com.hss01248.net.wrapper.MyNetListener; /** * Created by Administrator on 2017/4/10 0010. */ public abstract class LoginManager { public abstract void autoLogin(MyNetListener listener); }
13.388889
59
0.742739
c84d3845bf23ddeb6667bf0a6ea8d6a694972cc0
14,028
package de.gurkenlabs.litiengine.attributes; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * The Class AttributeTests. */ public class AttributeTests { @Test public void testAddModification() { final Attribute<Byte> testAttributeByte = new Attribute<>((byte) 10); final Attribute<Short> testAttributeShort = new Attribute<>((short) 10); final Attribute<Integer> testAttributeInt = new Attribute<>(10); final Attribute<Long> testAttributeLong = new Attribute<>(10L); final Attribute<Float> testAttributeFloat = new Attribute<>(10.0f); final Attribute<Double> testAttributeDouble = new Attribute<>(10.0); testAttributeByte.modifyBaseValue(new AttributeModifier<Byte>(Modification.ADD, (byte) 100)); testAttributeShort.modifyBaseValue(new AttributeModifier<Short>(Modification.ADD, (short) 100)); testAttributeInt.modifyBaseValue(new AttributeModifier<Integer>(Modification.ADD, 100)); testAttributeLong.modifyBaseValue(new AttributeModifier<Long>(Modification.ADD, 1000L)); testAttributeFloat.modifyBaseValue(new AttributeModifier<Float>(Modification.ADD, 101.1f)); testAttributeDouble.modifyBaseValue(new AttributeModifier<Double>(Modification.ADD, 101.1)); assertEquals((byte) 110, testAttributeByte.getCurrentValue().byteValue()); assertEquals((short) 110, testAttributeByte.getCurrentValue().byteValue()); assertEquals(110, testAttributeInt.getCurrentValue().intValue()); assertEquals(1010L, testAttributeLong.getCurrentValue().longValue()); assertEquals(111.1f, testAttributeFloat.getCurrentValue().floatValue(), 0.0001f); assertEquals(111.1, testAttributeDouble.getCurrentValue().doubleValue(), 0.0000001); } @Test public void testAddPercentModification() { final Attribute<Byte> testAttributeByte = new Attribute<>((byte) 10); final Attribute<Short> testAttributeShort = new Attribute<>((short) 10); final Attribute<Integer> testAttributeInt = new Attribute<>(10); final Attribute<Long> testAttributeLong = new Attribute<>(10L); final Attribute<Float> testAttributeFloat = new Attribute<>(10.0f); final Attribute<Double> testAttributeDouble = new Attribute<>(10.0); testAttributeByte.modifyBaseValue(new AttributeModifier<Byte>(Modification.ADDPERCENT, 10)); testAttributeShort.modifyBaseValue(new AttributeModifier<Short>(Modification.ADDPERCENT, 10)); testAttributeInt.modifyBaseValue(new AttributeModifier<Integer>(Modification.ADDPERCENT, 10)); testAttributeLong.modifyBaseValue(new AttributeModifier<Long>(Modification.ADDPERCENT, 10)); testAttributeFloat.modifyBaseValue(new AttributeModifier<Float>(Modification.ADDPERCENT, 11)); testAttributeDouble.modifyBaseValue(new AttributeModifier<Double>(Modification.ADDPERCENT, 11)); assertEquals((byte) 11, testAttributeByte.getCurrentValue().byteValue()); assertEquals((short) 11, testAttributeByte.getCurrentValue().byteValue()); assertEquals(11, testAttributeInt.getCurrentValue().intValue()); assertEquals(11L, testAttributeLong.getCurrentValue().longValue()); assertEquals(11.1f, testAttributeFloat.getCurrentValue().floatValue(), 0.0001f); assertEquals(11.1, testAttributeDouble.getCurrentValue().doubleValue(), 0.0000001); } @Test public void testAttributeInitialization() { final Attribute<Integer> testAttribute = new Attribute<>(10); assertEquals(10, testAttribute.getCurrentValue().intValue()); } @Test public void testDivideModification() { final Attribute<Byte> testAttributeByte = new Attribute<>((byte) 10); final Attribute<Short> testAttributeShort = new Attribute<>((short) 10); final Attribute<Integer> testAttributeInt = new Attribute<>(10); final Attribute<Long> testAttributeLong = new Attribute<>(10L); final Attribute<Float> testAttributeFloat = new Attribute<>(10.0f); final Attribute<Double> testAttributeDouble = new Attribute<>(10.0); testAttributeByte.modifyBaseValue(new AttributeModifier<Byte>(Modification.DIVIDE, 2)); testAttributeShort.modifyBaseValue(new AttributeModifier<Short>(Modification.DIVIDE, 2)); testAttributeInt.modifyBaseValue(new AttributeModifier<Integer>(Modification.DIVIDE, 2)); testAttributeLong.modifyBaseValue(new AttributeModifier<Long>(Modification.DIVIDE, 2)); testAttributeFloat.modifyBaseValue(new AttributeModifier<Float>(Modification.DIVIDE, 3)); testAttributeDouble.modifyBaseValue(new AttributeModifier<Double>(Modification.DIVIDE, 3)); assertEquals((byte) 5, testAttributeByte.getCurrentValue().byteValue()); assertEquals((short) 5, testAttributeByte.getCurrentValue().byteValue()); assertEquals(5, testAttributeInt.getCurrentValue().intValue()); assertEquals(5L, testAttributeLong.getCurrentValue().longValue()); assertEquals(3.333333333333f, testAttributeFloat.getCurrentValue().floatValue(), 0.0001f); assertEquals(3.333333333333, testAttributeDouble.getCurrentValue().doubleValue(), 0.0000001); } @Test public void testMultiplyModification() { final Attribute<Byte> testAttributeByte = new Attribute<>((byte) 10); final Attribute<Short> testAttributeShort = new Attribute<>((short) 10); final Attribute<Integer> testAttributeInt = new Attribute<>(10); final Attribute<Long> testAttributeLong = new Attribute<>(10L); final Attribute<Float> testAttributeFloat = new Attribute<>(10.0f); final Attribute<Double> testAttributeDouble = new Attribute<>(10.0); testAttributeByte.modifyBaseValue(new AttributeModifier<Byte>(Modification.MULTIPLY, 2)); testAttributeShort.modifyBaseValue(new AttributeModifier<Short>(Modification.MULTIPLY, 2)); testAttributeInt.modifyBaseValue(new AttributeModifier<Integer>(Modification.MULTIPLY, 2)); testAttributeLong.modifyBaseValue(new AttributeModifier<Long>(Modification.MULTIPLY, 2)); testAttributeFloat.modifyBaseValue(new AttributeModifier<Float>(Modification.MULTIPLY, 2.1)); testAttributeDouble.modifyBaseValue(new AttributeModifier<Double>(Modification.MULTIPLY, 2.1)); assertEquals((byte) 20, testAttributeByte.getCurrentValue().byteValue()); assertEquals((short) 20, testAttributeByte.getCurrentValue().byteValue()); assertEquals(20, testAttributeInt.getCurrentValue().intValue()); assertEquals(20L, testAttributeLong.getCurrentValue().longValue()); assertEquals(21f, testAttributeFloat.getCurrentValue().floatValue(), 0.0001f); assertEquals(21, testAttributeDouble.getCurrentValue().doubleValue(), 0.0000001); } @Test public void testSetModification() { final Attribute<Byte> testAttributeByte = new Attribute<>((byte) 10); final Attribute<Short> testAttributeShort = new Attribute<>((short) 10); final Attribute<Integer> testAttributeInt = new Attribute<>(10); final Attribute<Long> testAttributeLong = new Attribute<>(10L); final Attribute<Float> testAttributeFloat = new Attribute<>(10.0f); final Attribute<Double> testAttributeDouble = new Attribute<>(10.0); testAttributeByte.modifyBaseValue(new AttributeModifier<Byte>(Modification.SET, 20)); testAttributeShort.modifyBaseValue(new AttributeModifier<Short>(Modification.SET, 20)); testAttributeInt.modifyBaseValue(new AttributeModifier<Integer>(Modification.SET, 20)); testAttributeLong.modifyBaseValue(new AttributeModifier<Long>(Modification.SET, 20)); testAttributeFloat.modifyBaseValue(new AttributeModifier<Float>(Modification.SET, 21)); testAttributeDouble.modifyBaseValue(new AttributeModifier<Double>(Modification.SET, 21)); assertEquals((byte) 20, testAttributeByte.getCurrentValue().byteValue()); assertEquals((short) 20, testAttributeByte.getCurrentValue().byteValue()); assertEquals(20, testAttributeInt.getCurrentValue().intValue()); assertEquals(20L, testAttributeLong.getCurrentValue().longValue()); assertEquals(21f, testAttributeFloat.getCurrentValue().floatValue(), 0.0001f); assertEquals(21, testAttributeDouble.getCurrentValue().doubleValue(), 0.0000001); } @Test public void testSubstractModification() { final Attribute<Byte> testAttributeByte = new Attribute<>((byte) 10); final Attribute<Short> testAttributeShort = new Attribute<>((short) 10); final Attribute<Integer> testAttributeInt = new Attribute<>(10); final Attribute<Long> testAttributeLong = new Attribute<>(10L); final Attribute<Float> testAttributeFloat = new Attribute<>(10.0f); final Attribute<Double> testAttributeDouble = new Attribute<>(10.0); testAttributeByte.modifyBaseValue(new AttributeModifier<Byte>(Modification.SUBSTRACT, (byte) 1)); testAttributeShort.modifyBaseValue(new AttributeModifier<Short>(Modification.SUBSTRACT, (short) 1)); testAttributeInt.modifyBaseValue(new AttributeModifier<Integer>(Modification.SUBSTRACT, 1)); testAttributeLong.modifyBaseValue(new AttributeModifier<Long>(Modification.SUBSTRACT, 1)); testAttributeFloat.modifyBaseValue(new AttributeModifier<Float>(Modification.SUBSTRACT, 0.9f)); testAttributeDouble.modifyBaseValue(new AttributeModifier<Double>(Modification.SUBSTRACT, 0.9)); assertEquals((byte) 9, testAttributeByte.getCurrentValue().byteValue()); assertEquals((short) 9, testAttributeByte.getCurrentValue().byteValue()); assertEquals(9, testAttributeInt.getCurrentValue().intValue()); assertEquals(9L, testAttributeLong.getCurrentValue().longValue()); assertEquals(9.1f, testAttributeFloat.getCurrentValue().floatValue(), 0.0001f); assertEquals(9.1, testAttributeDouble.getCurrentValue().doubleValue(), 0.0000001); } @Test public void testSubstractPercentModification() { final Attribute<Byte> testAttributeByte = new Attribute<>((byte) 10); final Attribute<Short> testAttributeShort = new Attribute<>((short) 10); final Attribute<Integer> testAttributeInt = new Attribute<>(10); final Attribute<Long> testAttributeLong = new Attribute<>(10L); final Attribute<Float> testAttributeFloat = new Attribute<>(10.0f); final Attribute<Double> testAttributeDouble = new Attribute<>(10.0); testAttributeByte.modifyBaseValue(new AttributeModifier<Byte>(Modification.SUBSTRACTPERCENT, 10)); testAttributeShort.modifyBaseValue(new AttributeModifier<Short>(Modification.SUBSTRACTPERCENT, 10)); testAttributeInt.modifyBaseValue(new AttributeModifier<Integer>(Modification.SUBSTRACTPERCENT, 10)); testAttributeLong.modifyBaseValue(new AttributeModifier<Long>(Modification.SUBSTRACTPERCENT, 10)); testAttributeFloat.modifyBaseValue(new AttributeModifier<Float>(Modification.SUBSTRACTPERCENT, 9)); testAttributeDouble.modifyBaseValue(new AttributeModifier<Double>(Modification.SUBSTRACTPERCENT, 9)); assertEquals((byte) 9, testAttributeByte.getCurrentValue().byteValue()); assertEquals((short) 9, testAttributeByte.getCurrentValue().byteValue()); assertEquals(9, testAttributeInt.getCurrentValue().intValue()); assertEquals(9L, testAttributeLong.getCurrentValue().longValue()); assertEquals(9.1f, testAttributeFloat.getCurrentValue().floatValue(), 0.0001f); assertEquals(9.1, testAttributeDouble.getCurrentValue().doubleValue(), 0.0000001); } @Test public void testRangeAttributeMaxModification() { final RangeAttribute<Byte> testAttributeByte = new RangeAttribute<>((byte) 10, (byte) 0, (byte) 10); final RangeAttribute<Short> testAttributeShort = new RangeAttribute<>((short) 10, (short) 0, (short) 10); final RangeAttribute<Integer> testAttributeInt = new RangeAttribute<>(10, 0, 10); final RangeAttribute<Long> testAttributeLong = new RangeAttribute<>(10L, 0L, 10L); final RangeAttribute<Float> testAttributeFloat = new RangeAttribute<>(10F, 0F, 10F); final RangeAttribute<Double> testAttributeDouble = new RangeAttribute<>(10.0, 0.0, 10.0); testAttributeByte.modifyMaxBaseValue(new AttributeModifier<Byte>(Modification.SUBSTRACTPERCENT, 10)); testAttributeShort.modifyMaxBaseValue(new AttributeModifier<Short>(Modification.SUBSTRACTPERCENT, 10)); testAttributeInt.modifyMaxBaseValue(new AttributeModifier<Integer>(Modification.SUBSTRACTPERCENT, 10)); testAttributeLong.modifyMaxBaseValue(new AttributeModifier<Long>(Modification.SUBSTRACTPERCENT, 10)); testAttributeFloat.modifyMaxBaseValue(new AttributeModifier<Float>(Modification.SUBSTRACTPERCENT, 9)); testAttributeDouble.modifyMaxBaseValue(new AttributeModifier<Double>(Modification.SUBSTRACTPERCENT, 9)); assertEquals((byte) 9, testAttributeByte.getMaxValue().byteValue()); assertEquals((short) 9, testAttributeByte.getMaxValue().byteValue()); assertEquals(9, testAttributeInt.getMaxValue().intValue()); assertEquals(9L, testAttributeLong.getMaxValue().longValue()); assertEquals(9.1f, testAttributeFloat.getMaxValue().floatValue(), 0.0001f); assertEquals(9.1, testAttributeDouble.getMaxValue().doubleValue(), 0.0000001); testAttributeByte.addMaxModifier(new AttributeModifier<Byte>(Modification.ADDPERCENT, 50)); testAttributeShort.addMaxModifier(new AttributeModifier<Short>(Modification.ADDPERCENT, 50)); testAttributeInt.addMaxModifier(new AttributeModifier<Integer>(Modification.ADDPERCENT, 50)); testAttributeLong.addMaxModifier(new AttributeModifier<Long>(Modification.ADDPERCENT, 50)); testAttributeFloat.addMaxModifier(new AttributeModifier<Float>(Modification.ADDPERCENT, 50)); testAttributeDouble.addMaxModifier(new AttributeModifier<Double>(Modification.ADDPERCENT, 50)); assertEquals((byte) 13, testAttributeByte.getMaxValue().byteValue()); assertEquals((short) 13, testAttributeByte.getMaxValue().byteValue()); assertEquals(13, testAttributeInt.getMaxValue().intValue()); assertEquals(13L, testAttributeLong.getMaxValue().longValue()); assertEquals(13.65f, testAttributeFloat.getMaxValue().floatValue(), 0.0001f); assertEquals(13.65, testAttributeDouble.getMaxValue().doubleValue(), 0.0000001); } }
56.112
109
0.772598
3ea3cf50aff95ba9ce8167dba62de9cb5172231b
747
package cmc.ps.dao; import org.springframework.stereotype.Repository; import cmc.ps.model.PhysicalPerson; /* * This is the implementation of the PhysicalPerson DAO. You can see that we don't * actually have to implement anything, it is all inherited from GenericDAOImpl * through BaseDAO. We just specify the entity type (PhysicalPerson) and its identifier * type (Integer). * * The @Repository allows Spring to recognize this as a managed component (so we * don't need to specify it in XML) and also tells spring to do DAO exception * translation to the Spring exception hierarchy. */ @Repository public class PhysicalPersonDAOImpl extends BaseDAO<PhysicalPerson, Integer> implements PhysicalPersonDAO { }
31.125
107
0.75502
7855b5d7877461711639fd3ebb49e2a1d5b5f280
5,011
/* * Copyright (c) 2020-2030 Leryn * * 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.leryn.vfs.provide.aliyun; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.leryn.common.io.resource.Resource; import com.leryn.logger.Logger; import com.leryn.logger.LoggerFactory; import com.aliyun.oss.OSS; import com.aliyun.oss.model.Bucket; import com.aliyun.oss.model.BucketInfo; import com.aliyun.oss.model.BucketList; import com.aliyun.oss.model.CreateBucketRequest; import com.aliyun.oss.model.ListBucketsRequest; import com.aliyun.oss.model.OSSObjectSummary; import com.aliyun.oss.model.ObjectListing; import com.aliyun.oss.model.PutObjectRequest; /** * Though Aliyun OSS implements Amazon S3 protocol, Aliyun provides a completely * new SDK on Aliyun OSS. The file operations are mainly dependent on this SDK. * * @author Leryn * @see <a href="https://help.aliyun.com/document_detail/32007.html">Aliyun OSS - Java SDK Offical Manual</a> * @since Leryn 1.0.0 */ public abstract class AliyunOssOperation { private static final Logger log = LoggerFactory.getLogger(AliyunOssOperation.class); /** * CRUD on buckets. */ public static abstract class Buckets { public static void createBucket(AliyunOssConnection connection, String bucketName) { CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName); connection.getClient().createBucket(createBucketRequest); } public static List<Bucket> listAllBuckets(AliyunOssConnection connection) { return connection.getClient().listBuckets(); } private static List<Bucket> listBucketsByRequest(AliyunOssConnection connection) { ListBucketsRequest listBucketsRequest = new ListBucketsRequest(); BucketList bucketList = connection.getClient().listBuckets(listBucketsRequest); return bucketList.getBucketList(); } public static BucketInfo getBucketInfo(OSS oss, String bucketName) { return oss.getBucketInfo(bucketName); } } /** * CRUD on Aliyun OSS objects. */ public static abstract class Objects { public static void putObject(AliyunOssConnection ossConnection, String bucketName, String key, Resource resource) { try(InputStream inputStream = resource.getInputStream()) { PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream); ossConnection.getClient().putObject(putObjectRequest); } catch (IOException e) { // May never reached. log.info("Fail to upload the resource to the bucket", e); } } public static String getObjectUrl( AliyunOssConnection connection, String bucketName, String key) { Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 180); URL url = connection.getClient().generatePresignedUrl(bucketName, key, expiration); return url.toString(); } public static List<AliyunOssFileObject> listObjects( AliyunOssConnection connection, String bucketName) { List<AliyunOssFileObject> fileItems = new ArrayList<>(); ObjectListing objectListing = connection.getClient().listObjects(bucketName); List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries(); for (OSSObjectSummary ossObjectSummary : objectSummaries) { AliyunOssFileObject aliyunOssFileObject = new AliyunOssFileObject(); aliyunOssFileObject.setOssObjectSummary(ossObjectSummary); aliyunOssFileObject.setDownloadUrl(getObjectUrl(connection, bucketName, ossObjectSummary.getKey())); fileItems.add(aliyunOssFileObject); } return fileItems; } public static void deleteObject(AliyunOssConnection oss, String bucketName, String key) { oss.getClient().deleteObject(bucketName, key); } } private AliyunOssOperation() { } }
38.844961
109
0.743963
814aca1018581ccdbb21e2844872031c51526f9b
9,969
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random; /** * The main driver of the Connect4Game, as well as the visualization of it. * * You should not modify this class, and your agent should not need to access the methods within * it directly. */ public class Connect4Frame extends JFrame { Connect4Panel myPanel; // the panel storing the visual of the game itself Connect4Game myGame; // the game itself Agent redPlayer, yellowPlayer; // the two players playing the game boolean redPlayerturn, gameActive; // booleans controlling whose turn it is and whether a game is ongoing JButton newGameButton, nextMoveButton, playToEndButton; // the buttons controlling the game JLabel updateLabel; // the status label describing the events of the game Random r; // a random number generator to randomly decide who plays first /** * Creates a new Connect4Frame with a given game and pair of players. * * Your agent will not need to use this method. * * @param game the game itself. * @param redPlayer the agent playing as the red tokens. * @param yellowPlayer the agent playing as the yellow tokens. */ public Connect4Frame(Connect4Game game, Agent redPlayer, Agent yellowPlayer) { super(); this.myGame = game; // stores the game itself this.redPlayer = redPlayer; // stores the red player this.yellowPlayer = yellowPlayer; //stores the yellow player gameActive = false; // initially sets that no game is active r = new Random(); // creates the random number generator myPanel = new Connect4Panel(game); // creates the panel for displaying the game newGameButton = new JButton("Start a New Game"); // creates the button for starting a new game newGameButton.setAlignmentX(Component.CENTER_ALIGNMENT); // center-aligns the new game button newGameButton.addActionListener(new ActionListener() { // connects the new game button to its buttonPressed method public void actionPerformed(ActionEvent e) { newGameButtonPressed(); } }); nextMoveButton = new JButton("Play Next Move"); // creates the button for playing the next move nextMoveButton.setEnabled(false); // disables the button until a game is started nextMoveButton.setAlignmentX(Component.CENTER_ALIGNMENT); // centers the button nextMoveButton.addActionListener(new ActionListener() { // connects the play next move button to its buttonPressed method public void actionPerformed(ActionEvent e) { nextMoveButtonPressed(); } }); playToEndButton = new JButton("Play to End"); // creates the button for finishing the game playToEndButton.setEnabled(false); // disables the button until a game is started playToEndButton.setAlignmentX(Component.CENTER_ALIGNMENT); // centers the button playToEndButton.addActionListener(new ActionListener() { //connects the play to end button to its buttonPressed method public void actionPerformed(ActionEvent e) { playToEndButtonPressed(); } }); updateLabel = new JLabel(redPlayer.toString() + " vs. " + yellowPlayer.toString()); // creates the status label updateLabel.setAlignmentX(Component.CENTER_ALIGNMENT); // centers the status label JPanel buttonPane = new JPanel(); // creates a pane for the buttons buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); // sets the button pane to be horizontally oriented // adding and spacing out the buttons buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(newGameButton); buttonPane.add(Box.createRigidArea(new Dimension(10,0))); buttonPane.add(nextMoveButton); buttonPane.add(Box.createRigidArea(new Dimension(10,0))); buttonPane.add(playToEndButton); buttonPane.add(Box.createHorizontalGlue()); setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS)); // sets the overall pane to be vertically oriented this.add(buttonPane); // adds the pane containing the buttons this.add(updateLabel); // adds the update label this.add(myPanel); // adds the visual of the game board this.pack(); // shrinks the window to the appropriate size this.setResizable(false); // makes the window not resizable this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close the application when the window is closed this.setVisible(true); // show the window } /** * Changes the text of the update label. * * Your agent will not need to use this method. * * @param text the next text for the update label. */ public void alert(String text) { updateLabel.setText(text); this.repaint(); } /** * Runs the next move of the game. * * Your agent will not need to use this method. */ private void nextMove() { Connect4Game oldBoard = new Connect4Game(myGame); // store the old board for validation if(redPlayerturn) // if it's the red player's turn, run their move { redPlayer.move(); alert(yellowPlayer.toString() + " plays next..."); } else // if it's the yellow player's turn, run their move { yellowPlayer.move(); alert(redPlayer.toString() + " plays next..."); } String validateResult = oldBoard.validate(myGame); // check and make sure this is a valid next move for this board if(validateResult.length() > 0) // if there was a validation error, show it and cancel the game { alert(validateResult); // show the error disableButtons(); // stop the game gameActive = false; } redPlayerturn = !redPlayerturn; // switch whose turn it is char won = myGame.gameWon(); // check if the game has been won if (won != 'N') // if the game has been won... { disableButtons(); // disable the buttons gameActive = false; if (myGame.gameWon() == 'R') // if red won, say so { alert(redPlayer.toString() + " wins!"); } else if (myGame.gameWon() == 'Y') // if yellow won, say so { alert(yellowPlayer.toString() + " wins!"); } } else if (myGame.boardFull()) // if the board is full... { disableButtons(); // disable the buttons alert("The game ended in a draw!"); // announce the draw gameActive = false; } this.repaint(); } /** * Clear the board and start a new game. * * Your agent will not need to use this method. */ // private void newGame() public void newGame() { myGame.clearBoard(); enableButtons(); gameActive = true; redPlayerturn = r.nextBoolean(); if (redPlayerturn) { alert(redPlayer.toString() + " plays first!"); myGame.setRedPlayedFirst(true); } else { alert(yellowPlayer.toString() + " plays first!"); myGame.setRedPlayedFirst(false); } this.repaint(); } /** * Runs the game until it's over. * * Your agent will not need to use this method. */ // private void playToEnd() public void playToEnd() { while (gameActive) // keep playing the next move until the game ends { nextMove(); } char won = myGame.gameWon(); if (won != 'N') // when it ends, announce how it ended: win or draw { disableButtons(); if (myGame.gameWon() == 'R') { alert(redPlayer.toString() + " wins!"); } else if (myGame.gameWon() == 'Y') { alert(yellowPlayer.toString() + " wins!"); } } else if (myGame.boardFull()) { disableButtons(); alert("The game ended in a draw!"); } else // if it didn't end in a win or draw, leave the error message u { disableButtons(); } } /** * Reacts to the new game button being pressed. * * Your agent will not need to use this method. */ public void newGameButtonPressed() { newGame(); } /** * Reacts to the next move button being pressed. * * Your agent will not need to use this method. */ public void nextMoveButtonPressed() { nextMove(); } /** * Reacts to the play to end button being pressed. * * Your agent will not need to use this method. */ public void playToEndButtonPressed() { playToEnd(); } /** * Disables the buttons. * * Your agent will not need to use this method. */ private void disableButtons() { nextMoveButton.setEnabled(false); playToEndButton.setEnabled(false); } /** * Enables the buttons. * * Your agent will not need to use this method. */ private void enableButtons() { nextMoveButton.setEnabled(true); playToEndButton.setEnabled(true); } }
36.650735
130
0.576487
dc97bcc95100c924d8c4bc131a1d8edf7f0fff55
3,606
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2019 Adobe Systems Incorporated and others ~ ~ 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.adobe.cq.commerce.demandware.replication.content.attributemapping; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import static org.apache.commons.lang.StringUtils.isBlank; import static org.apache.commons.lang.StringUtils.trimToEmpty; /** * Holds values of attribute mapping so target name/converter id do not have * to be joined and split over and over again. */ public class AttributeDescriptor { private final String targetName; private final String converterId; private final String sourceName; private final String defaultValue; public AttributeDescriptor(final String sourceName, final String targetName) { this(sourceName, targetName, null); } public AttributeDescriptor(final String sourceName, final String targetName, final String converterId) { this(sourceName, targetName, converterId, null); } public AttributeDescriptor(final String sourceName, final String targetName, final String converterId, final String defaultValue) { if(isBlank(sourceName)) { throw new IllegalArgumentException("sourceName must not be blank."); } if(isBlank(targetName)) { throw new IllegalArgumentException("targetName must not be blank."); } this.sourceName = sourceName; this.targetName = targetName; this.converterId = converterId; this.defaultValue = defaultValue; } public String getSourceName() { return sourceName; } public String getTargetName() { return targetName; } public String getConverterId() { return converterId; } public String getDefaultValue() { return defaultValue; } @Override // Generated. Don't edit. public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AttributeDescriptor)) return false; AttributeDescriptor that = (AttributeDescriptor) o; return new EqualsBuilder() .append(targetName, that.targetName) .append(sourceName, that.sourceName) .isEquals(); } @Override // Generated. Don't edit. public int hashCode() { return new HashCodeBuilder(17, 37) .append(targetName) .append(sourceName) .toHashCode(); } @Override public String toString() { return new StringBuilder("AttributeDescriptor[") .append("sourceName:").append(sourceName) .append(",targetName:").append(targetName) .append(",converterId:").append(converterId) .append(",defaultValue:").append(defaultValue) .append(']') .toString(); } }
33.388889
135
0.638103
88673c9ac470ce0354e7ff947e2dab501077ccee
35,959
package com.ref.parser.activityDiagram; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ref.exceptions.ParsingException; import com.ref.interfaces.activityDiagram.IAction; import com.ref.interfaces.activityDiagram.IActivity; import com.ref.interfaces.activityDiagram.IActivityDiagram; import com.ref.interfaces.activityDiagram.IActivityNode; import com.ref.interfaces.activityDiagram.IActivityParameterNode; import com.ref.interfaces.activityDiagram.IControlFlow; import com.ref.interfaces.activityDiagram.IFlow; import com.ref.interfaces.activityDiagram.IInputPin; import com.ref.interfaces.activityDiagram.IObjectFlow; import com.ref.interfaces.activityDiagram.IOutputPin; public class ADUtils { private IActivity ad; private IActivityDiagram adDiagram; public HashMap<String, Integer> countCall; private List<String> eventChannel; private List<String> lockChannel; private HashMap<String, String> parameterNodesOutputObject; private List<Pair<String, Integer>> callBehaviourNumber; private Map<Pair<String, String>,String> memoryLocal; private List<Pair<String, String>> memoryLocalChannel; private HashMap<String, List<String>> callBehaviourInputs; private HashMap<String, List<String>> callBehaviourOutputs; private List<Pair<String, Integer>> countSignal; private List<Pair<String, Integer>> countAccept; private HashMap<String, List<IActivity>> signalChannels; private HashMap<String, List<String>> signalPins; private List<String> signalChannelsLocal; private List<String> localSignalChannelsSync; private HashMap<String,Integer> allGuards; public HashMap<Pair<IActivity,String>, String> syncChannelsEdge; public HashMap<Pair<IActivity,String>, String> syncObjectsEdge; private HashMap<String, String> objectEdges; private ADParser adParser; private HashMap<String, Pair<String,String>> parameterSignal; public ADUtils(IActivity ad, IActivityDiagram adDiagram, HashMap<String, Integer> countCall, List<String> eventChannel, List<String> lockChannel, HashMap<String, String> parameterNodesOutputObject, List<Pair<String, Integer>> callBehaviourNumber, Map<Pair<String, String>,String> memoryLocal, List<Pair<String, String>> memoryLocalChannel, HashMap<String, List<String>> callBehaviourInputs, HashMap<String, List<String>> callBehaviourOutputs, List<Pair<String, Integer>> countSignal, List<Pair<String, Integer>> countAccept, HashMap<String, List<IActivity>> signalChannels2, HashMap<String, List<String>> signalPins2, List<String> localSignalChannelsSync, HashMap<String, Integer> allGuards, List<String> createdSignal, List<String> createdAccept, HashMap<Pair<IActivity, String>, String> syncChannelsEdge2, HashMap<Pair<IActivity, String>, String> syncObjectsEdge2, HashMap<String, String> objectEdges2, List<String> signalChannelsLocal, HashMap<String, Pair<String, String>> parameterSignal, ADParser adParser) { this.ad = ad; this.adDiagram = adDiagram; this.countCall = countCall; this.eventChannel = eventChannel; this.lockChannel = lockChannel; this.parameterNodesOutputObject = parameterNodesOutputObject; this.callBehaviourNumber = callBehaviourNumber; this.memoryLocal = memoryLocal; this.memoryLocalChannel = memoryLocalChannel; this.callBehaviourInputs = callBehaviourInputs; this.callBehaviourOutputs = callBehaviourOutputs; this.countSignal = countSignal; this.countAccept = countAccept; this.signalChannels = signalChannels2; this.signalPins = signalPins2; this.localSignalChannelsSync = localSignalChannelsSync; this.allGuards = allGuards; this.syncChannelsEdge = syncChannelsEdge2; this.syncObjectsEdge = syncObjectsEdge2; this.signalChannelsLocal = signalChannelsLocal; this.objectEdges = objectEdges2; this.parameterSignal = parameterSignal; this.adParser = adParser; } public String createCE() { return "ce_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countCe_ad++; } public String createOE() { return "oe_" + adParser.countOe_ad++ + "_" + nameDiagramResolver(ad.getName()) + ".id" ; } public int startActivity(ArrayList<String> alphabetNode, StringBuilder action, String nameAD, List<String> inputPins) { int count = 0; count = addCountCall(nameDiagramResolver(nameAD)); String startActivity = "startActivity_" + nameDiagramResolver(nameAD) + "." + count; alphabetNode.add(startActivity); callBehaviourNumber.add(new Pair<>(nameDiagramResolver(nameAD), count)); List<String> outputPinsUsed = callBehaviourInputs.get(nameDiagramResolver(nameAD)); if (outputPinsUsed == null) { outputPinsUsed = inputPins; callBehaviourInputs.put(nameAD, inputPins); } for (String pin : outputPinsUsed) { startActivity += "!" + pin; } action.append(startActivity + " -> "); return count; } public void endActivity(ArrayList<String> alphabetNode, StringBuilder action, String nameAD, List<String> outputPins, int count) { String endActivity = "endActivity_" + nameDiagramResolver(nameAD) + "." + count; alphabetNode.add(endActivity); List<String> outputPinsUsed = callBehaviourOutputs.get(nameDiagramResolver(nameAD)); if (outputPinsUsed == null) { outputPinsUsed = outputPins; callBehaviourOutputs.put(nameAD, outputPins); } for (String pin : outputPinsUsed) { endActivity += "?" + pin; } action.append(endActivity + " -> "); } public void get(ArrayList<String> alphabetNode, StringBuilder action, String nameObject) { String get = "get_" + nameObject + "_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countGet_ad++; alphabetNode.add(get); action.append(get + "?" + nameObject + " -> "); } public void set(ArrayList<String> alphabetNode, StringBuilder action, String nameMemory, String nameObject) { String set = "set_" + nameMemory + "_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countSet_ad++; alphabetNode.add(set); action.append(set +"!" + nameObject + " -> "); parameterNodesOutputObject.put(nameMemory, nameObject); } public void setLocal(ArrayList<String> alphabetNode, StringBuilder action, String nameObject, String nameNode, String data, String datatype) { String set = "set_" + nameObject + "_" + nameNode + "_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countSet_ad++; alphabetNode.add(set); action.append(set + "!" + data + " -> "); Pair<String, String> memoryLocalPair = new Pair<String, String>(nameNode, nameObject); if (!memoryLocal.keySet().contains(memoryLocalPair)) { memoryLocal.put(memoryLocalPair,datatype); } } public void getLocal(ArrayList<String> alphabetNode, StringBuilder action, String nameObject, String nameNode, String data, String datatype) { String get = "get_" + nameObject + "_" + nameNode + "_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countGet_ad++; alphabetNode.add(get); action.append(get + "?" + data + " -> "); Pair<String, String> memoryLocalPair = new Pair<String, String>(nameNode, nameObject); if (!memoryLocal.keySet().contains(memoryLocalPair)) { memoryLocal.put(memoryLocalPair,datatype); } } public void setLocalInput(ArrayList<String> alphabetNode, StringBuilder action, String nameObject, String nameNode, String data, String oeIn, String datatype) { String set = "set_" + nameObject + "_" + nameNode + "_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countSet_ad++; alphabetNode.add(set); action.append(set + "!" + data + " -> "); Pair<String, String> memoryLocalPair = new Pair<String, String>(nameNode, nameObject); memoryLocalChannel.add(new Pair<String, String>(oeIn, nameObject)); if (!memoryLocal.keySet().contains(memoryLocalPair)) { memoryLocal.put(memoryLocalPair,datatype); } } public void lock(ArrayList<String> alphabetNode, StringBuilder action, int inOut, String nameNode) { if (ADParser.containsCallBehavior) { if (inOut == 0) { String lock = "lock_" + nameNode; alphabetNode.add(lock); lockChannel.add(nameNode); action.append(lock + ".id.lock -> "); } else { String lock = "lock_" + nameNode; action.append(lock + ".id.unlock -> "); } } } public void event(ArrayList<String> alphabet, String nameAction, StringBuilder action) { alphabet.add("event_" + nameAction+".id"); eventChannel.add("event_" + nameAction); action.append("event_" + nameAction + ".id -> "); } public void ce(ArrayList<String> alphabetNode, StringBuilder action, String ce, String posCe) { alphabetNode.add(ce); action.append(ce + posCe); } public void oe(ArrayList<String> alphabetNode, StringBuilder action, String oe, String data, String posOe) { alphabetNode.add(oe); action.append(oe + data + posOe); } public void update(ArrayList<String> alphabetNode, StringBuilder action, int countInFlows, int countOutFlows, boolean canBeNegative) { int result = countOutFlows - countInFlows; if (result != 0) { if (countOutFlows == 0 && canBeNegative || countOutFlows > 0) { String update = "update_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countUpdate_ad++; alphabetNode.add(update); action.append(update + "!(" + countOutFlows + "-" + countInFlows + ") -> "); if (result < adParser.limiteInf) { adParser.limiteInf = result; if (adParser.limiteSup == -99) { adParser.limiteSup = result; } } if (result > adParser.limiteSup) { adParser.limiteSup = result; if (adParser.limiteInf == 99) { adParser.limiteInf = result; } } } } } public void clear(ArrayList<String> alphabetNode, StringBuilder action) { String clear = "clear_" + nameDiagramResolver(ad.getName()) + ".id." + adParser.countClear_ad++; alphabetNode.add(clear); action.append(clear + " -> "); } public List<String> replaceExpression(String expression) { String value = ""; char[] expChar = expression.toCharArray(); List<String> expReplaced = new ArrayList<>(); for (int i = 0; i < expChar.length; i++) { if (expChar[i] == '+' || expChar[i] == '-' || expChar[i] == '*' || expChar[i] == '/') { expReplaced.add(value); value = ""; } else { value += expChar[i]; } } if (!value.equals("")) { //add last value expReplaced.add(value); } return expReplaced; } public List<String> getObjects(IFlow flow, List<String> nodes) { List<String> objects = new ArrayList<>(); if (!nodes.contains(flow.getSource().getId())) { nodes.add(flow.getSource().getId()); if (flow.getSource() instanceof IActivityParameterNode) { objects.add(flow.getSource().getName()); } else if (flow.getSource() instanceof IOutputPin) { IInputPin[] inPins = ((IAction) ((IOutputPin)flow.getSource()).getOwner()).getInputs(); for (int x = 0; x < inPins.length; x++) { for (IFlow flowNode : inPins[x].getIncomings()) { objects.addAll(getObjects(flowNode, nodes)); } } } else { for (IFlow flowNode : flow.getSource().getIncomings()) { objects.addAll(getObjects(flowNode, nodes)); } } } return objects; } public void signal(ArrayList<String> alphabet, String nameSignal, StringBuilder signal, IActivityNode activityNode, List<String> namesMemoryLocal, HashMap<String, String> typeMemoryLocal) { if (!localSignalChannelsSync.contains("signal_" + nameSignal)) { localSignalChannelsSync.add("signal_" + nameSignal); } if (!signalChannels.containsKey(nameSignal)) { List<IActivity> list = new ArrayList<>(); list.add(ad); signalChannels.put(nameSignal,list ); if(((IAction)activityNode).getInputs().length>0) { List<String> types = new ArrayList<>(); for(IInputPin inputPin :((IAction)activityNode).getInputs()) { types.add(inputPin.getBase().getName()); } signalPins.put(nameSignal, types); } } if (!signalChannelsLocal.contains(nameSignal)) { signalChannelsLocal.add(nameSignal); } int idSignal = 1; int index = -1; for (int i = 0; i < countSignal.size(); i++) { if (countSignal.get(i).getKey().equals(nameSignal)) { idSignal = countSignal.get(i).getValue(); index = i; break; } } alphabet.add("signal_" + nameSignal + ".id." + idSignal); if (namesMemoryLocal.size() > 0) { signal.append("signal_" + nameSignal + ".id!" + idSignal + "!" + namesMemoryLocal.get(0) + " -> "); Pair<String, String> newPair = new Pair<String, String>(namesMemoryLocal.get(0), typeMemoryLocal.get(namesMemoryLocal.get(0))); //parameterSignal.put(nameSignal, namesMemoryLocal.get(0)); parameterSignal.put(nameSignal, newPair); } else { signal.append("signal_" + nameSignal + ".id!" + idSignal + " -> "); } if (index >= 0) { countSignal.set(index, new Pair<String, Integer>(nameSignal, idSignal + 1)); ADParser.IdSignals.put(activityNode.getId(),idSignal); } else { countSignal.add(new Pair<String, Integer>(nameSignal, idSignal + 1)); ADParser.IdSignals.put(activityNode.getId(),idSignal); } } public void accept(ArrayList<String> alphabet, String nameAccept, StringBuilder accept, IActivityNode activityNode, String nodeName, IOutputPin[] outPins) { if (!localSignalChannelsSync.contains("signal_" + nameAccept)) { localSignalChannelsSync.add("signal_" + nameAccept); } if (!signalChannels.containsKey(nameAccept)) { List<IActivity> list = new ArrayList<>(); list.add(ad); signalChannels.put(nameAccept,list ); if(((IAction)activityNode).getOutputs().length>0) { List<String> types = new ArrayList<>(); for(IOutputPin outputPin :((IAction)activityNode).getOutputs()) { types.add(outputPin.getBase().getName()); } signalPins.put(nameAccept, types); } } int idAccept = 1; int index = -1; for (int i = 0; i < countAccept.size(); i++) { if (countAccept.get(i).getKey().equals(nameAccept)) { idAccept = countAccept.get(i).getValue(); index = i; break; } } alphabet.add("accept_" + nameAccept + ".id." + idAccept); if (outPins.length > 0) { accept.append("accept_" + nameAccept + ".id." + idAccept + "?" + nodeName + "?" + nodeName + "_" + outPins[0].getName() + " -> "); } else { accept.append("accept_" + nameAccept + ".id." + idAccept + "?" + nodeName + " -> "); } if (index >= 0) { countAccept.set(index, new Pair<String, Integer>(nameAccept, idAccept + 1)); ADParser.IdSignals.put(activityNode.getId(),idAccept); } else { countAccept.add(new Pair<String, Integer>(nameAccept, idAccept + 1)); ADParser.IdSignals.put(activityNode.getId(),idAccept); } } public String nameDiagramResolver(String name) { return name.replace(" ", "").replace("!", "_").replace("@", "_") .replace("%", "_").replace("&", "_").replace("*", "_") .replace("(", "_").replace(")", "_").replace("+", "_") .replace("-", "_").replace("=", "_").replace("?", "_") .replace(":", "_").replace("/", "_").replace(";", "_") .replace(">", "_").replace("<", "_").replace(",", "_") .replace("{", "_").replace("}", "_").replace("|", "_") .replace("\\", "_").replace("\n", "_"); } public static String nameResolver(String name) { return name.replace(" ", "").replace("!", "_").replace("@", "_") .replace("%", "_").replace("&", "_").replace("*", "_") .replace("(", "_").replace(")", "_").replace("+", "_") .replace("-", "_").replace("=", "_").replace("?", "_") .replace(":", "_").replace("/", "_").replace(";", "_") .replace(">", "_").replace("<", "_").replace(",", "_") .replace("{", "_").replace("}", "_").replace("|", "_") .replace("\\", "_").replace("\n", "_"); } public int addCountCall(String name) { int i = 1; if (countCall.containsKey(name)) { i = countCall.get(name); countCall.put(name, ++i); } else { countCall.put(name, i); } return i; } public int addCountGuard(String guard) { int i = 1; if (allGuards.containsKey(guard)) { i = allGuards.get(guard); allGuards.put(guard, ++i); } else { allGuards.put(guard, i); } return i; } public String getDefaultValue(String type) { HashMap<String, String> typesParameter = getParameterValueDiagram(type); String defaultValue = typesParameter.get(type).replace("{", "").replace("}", "").replace("(", "") .replace(")", "").split(",")[0]; String defaultValueFinal = defaultValue.split("\\.\\.")[0]; /*if(defaultValueFinal.contains(":")) {//se for datatype String[] dtValues = defaultValueFinal.split(":"); defaultValueFinal = dtValues[0]; }*/ if(defaultValueFinal.contains(":")) { String defaultValueDT = type; if(defaultValueFinal.contains(";")) {//se tem mais de 1 atributo String[] atributes = defaultValueFinal.split(";"); for(String atribute :atributes) { String[] nameAndType = atribute.split(":"); if(ADParser.primitives.contains(nameAndType[1])) { defaultValueDT +="."+primitiveDefaultValue(nameAndType[1]); }else { defaultValueDT +="."+getDefaultValue(nameAndType[1]);//TODO testar futuramente quando existir tipos compostos } } }else { String[] nameAndType = defaultValueFinal.split(":"); if(ADParser.primitives.contains(nameAndType[1])) { defaultValueDT +="."+primitiveDefaultValue(nameAndType[1]); }else { defaultValueDT +="."+getDefaultValue(nameAndType[1]);//TODO testar futuramente quando existir tipos compostos } } defaultValueFinal = defaultValueDT; } return defaultValueFinal; } private String primitiveDefaultValue(String primitive) {//TODO ver se é pra ser assim mesmo if(primitive.equals("Bool")) { return "true"; }else { return "1"; } } public Pair<String, String> getInitialAndFinalParameterValue(String type) { Pair<String, String> initialAndFinalParameterValue; String[] allValues; String firstValue; String secondValue; HashMap<String, String> typesParameter = getParameterValueDiagram(type); String ListValue = typesParameter.get(type).replace("{", "").replace("}", "").replace("(", "") .replace(")", ""); if (ListValue.contains("..")) { allValues = ListValue.split("\\.\\."); firstValue = allValues[0]; secondValue = allValues[1]; } else { allValues = ListValue.split(","); firstValue = allValues[0]; secondValue = allValues[allValues.length - 1]; } initialAndFinalParameterValue = new Pair<>(firstValue, secondValue); return initialAndFinalParameterValue; } public HashMap<String, String> getParameterValueDiagram(String type) { HashMap<String, String> typesParameter = new HashMap<>(); //String[] definition = adDiagram.getDefinition().replace("\n", "").replace(" ", "").split(";"); //String[] definition = ADParser.GlobalDefinition.replace("\n", "").replace(" ", "").split(";"); String[] definition = ADParser.getDefinitionReplaced(); //TODO ajeitar para os casos de datatype pois tem ; na definição for (String def : definition) { String[] definitionAux = null; //teste pra enum e datatype if (def.startsWith("enum")) { definitionAux= def.split("enum"); } if (def.startsWith("datatype")) { definitionAux = def.split("datatype"); } if(definitionAux != null) { def = definitionAux[1]; } String[] keyValue = def.split("="); if (keyValue.length == 1) { typesParameter.put(keyValue[0], keyValue[0]); } else { typesParameter.put(keyValue[0], keyValue[1]); } } return typesParameter; } public int countAmount(IActivityNode activityNode) { int input = 0; if (activityNode != null) { input = 0; IFlow[] inFlow = activityNode.getIncomings(); for (int i = 0; i < inFlow.length; i++) { Pair<IActivity,String> key = new Pair<IActivity, String>(ad,inFlow[i].getId()); if (syncChannelsEdge.containsKey(key)) { input++; } } if (activityNode instanceof IAction) { IInputPin[] inPin = ((IAction) activityNode).getInputs(); for (int i = 0; i < inPin.length; i++) { IFlow[] inFlowPin = inPin[i].getIncomings(); for (int x = 0; x < inFlowPin.length; x++) { Pair<IActivity,String> key = new Pair<IActivity, String>(ad,inFlowPin[x].getId()); if (syncObjectsEdge.containsKey(key)) { input++; } } } } else { for (int i = 0; i < inFlow.length; i++) { Pair<IActivity,String> key = new Pair<IActivity, String>(ad,inFlow[i].getId()); if (syncObjectsEdge.containsKey(key)) { input++; } } } } return input; } public static boolean isInteger(String s) { return isInteger(s,10); } private static boolean isInteger(String s, int radix) { if(s.isEmpty()) return false; for(int i = 0; i < s.length(); i++) { if(i == 0 && s.charAt(i) == '-') { if(s.length() == 1) return false; else continue; } if(Character.digit(s.charAt(i),radix) < 0) return false; } return true; } public List<Pair<String, Integer>> getCallBehaviourNumber() { return callBehaviourNumber; } public void setCallBehaviourNumber(List<Pair<String, Integer>> callBehaviourNumber) { this.callBehaviourNumber = callBehaviourNumber; } public HashMap<String, List<String>> getCallBehaviourInputs() { return callBehaviourInputs; } public void setCallBehaviourInputs(HashMap<String, List<String>> callBehaviourInputs) { this.callBehaviourInputs = callBehaviourInputs; } public HashMap<String, List<String>> getCallBehaviourOutputs() { return callBehaviourOutputs; } public void setCallBehaviourOutputs(HashMap<String, List<String>> callBehaviourOutputs) { this.callBehaviourOutputs = callBehaviourOutputs; } public void incomingEdges(IActivityNode activityNode, StringBuilder action, ArrayList<String> alphabet, IFlow[] inFlows, IInputPin[] inPins, List<String> namesMemoryLocal, HashMap<String, String> typeMemoryLocal) throws ParsingException { if (inFlows.length > 0 || inPins.length > 0) { action.append("("); for (int i = 0; i < inFlows.length; i++) { // first control flows Pair<IActivity,String> key = new Pair<IActivity, String>(ad, inFlows[i].getId()); if (inFlows[i] instanceof IControlFlow) { String ceIn; if (syncChannelsEdge.containsKey(key)) { ceIn = syncChannelsEdge.get(key); } else { ceIn = createCE(); Pair<IActivity,String> pair = new Pair<IActivity, String>(ad, inFlows[i].getId()); syncChannelsEdge.put(pair, ceIn); } action.append("("); if (i < inFlows.length - 1 || inPins.length > 0) { ce(alphabet, action, ceIn, " -> SKIP) ||| "); } else { ce(alphabet, action, ceIn, " -> SKIP)"); } } else {// then object flows, which are discarded as they are not sent to pins String oeIn; String typeObject; try { typeObject = ((IObjectFlow)inFlows[i]).getBase().getName(); } catch (NullPointerException e) { throw new ParsingException("Object flow does not have a type."); } if (syncObjectsEdge.containsKey(key)) { oeIn = syncObjectsEdge.get(key); if (!objectEdges.containsKey(oeIn)) { objectEdges.put(oeIn, typeObject); } } else { oeIn = createOE(); Pair<IActivity,String> pair = new Pair<IActivity, String>(ad,inFlows[i].getId()); syncObjectsEdge.put(pair, oeIn); objectEdges.put(oeIn, typeObject); } action.append("("); if (i < inFlows.length - 1 || inPins.length > 0) { oe(alphabet, action, oeIn, "?x", " -> "); action.append("SKIP) ||| "); } else { oe(alphabet, action, oeIn, "?x" , " -> "); action.append("SKIP)"); } } } //then object flows for (int i = 0; i < inPins.length; i++) { IFlow[] inFlowPin = inPins[i].getIncomings(); for (int x = 0; x < inFlowPin.length; x++) { String type = ((IObjectFlow)inFlowPin[x]).getBase().getName(); String aux = inPins[i].getBase().getName(); if (!type.equals(inPins[i].getBase().getName())) { throw new ParsingException("Pin "+ inPins[i].getName() + " and object flow have incompatible types!"); } Pair<IActivity,String> key = new Pair<IActivity, String>(ad, inFlowPin[x].getId()); String nameObject = inPins[i].getName(); String oeIn; if (syncObjectsEdge.containsKey(key)) { oeIn = syncObjectsEdge.get(key); if (!objectEdges.containsKey(oeIn)) { objectEdges.put(oeIn, type); } } else { oeIn = createOE(); Pair<IActivity,String> pair = new Pair<IActivity, String>(ad,inFlowPin[x].getId()); syncObjectsEdge.put(pair, oeIn); objectEdges.put(oeIn, type); } action.append("("); if (i < inPins.length - 1 || x < inFlowPin.length - 1) { oe(alphabet, action, oeIn, "?" + nameObject, " -> "); try { setLocalInput(alphabet, action, inPins[i].getName(), nameDiagramResolver(activityNode.getName()), nameObject, oeIn,inPins[i].getBase().getName()); } catch (Exception e) { throw new ParsingException("InputPin node "+inPins[i].getName()+" without base type\n");//TODO fix the type of exception } action.append("SKIP) ||| "); } else { oe(alphabet, action, oeIn, "?" + nameObject, " -> "); try { setLocalInput(alphabet, action, inPins[i].getName(), nameDiagramResolver(activityNode.getName()), nameObject, oeIn,inPins[i].getBase().getName()); } catch (Exception e) { throw new ParsingException("Pin node "+inPins[i].getName()+" without base type\n");//TODO fix the type of exception } action.append("SKIP)"); } if (!namesMemoryLocal.contains(nameObject)) { namesMemoryLocal.add(nameObject); typeMemoryLocal.put(nameObject, inPins[i].getBase().getName()); } } } action.append("); "); } } public void outgoingEdges(StringBuilder action, ArrayList<String> alphabet, IFlow[] outFlows, IOutputPin[] outPins, String[] definitionFinal, String nodeFullName) throws ParsingException { // defining outgoing edges if (outFlows.length > 0 || outPins.length > 0) { action.append("("); } // creates the outgoing control edges events for (int i = 0; i < outFlows.length; i++) { Pair<IActivity,String> key = new Pair<IActivity, String>(ad, outFlows[i].getId()); String ceOut; if (syncChannelsEdge.containsKey(key)) { ceOut = syncChannelsEdge.get(key); } else { ceOut = createCE(); Pair<IActivity,String> pair = new Pair<IActivity, String>(ad, outFlows[i].getId()); syncChannelsEdge.put(pair, ceOut); } action.append("("); if (i >= 0 && (i < outFlows.length - 1 || outPins.length > 0)) { ce(alphabet, action, ceOut, " -> SKIP) ||| "); } else { ce(alphabet, action, ceOut, " -> SKIP)"); } } // creates the outgoing object edges events for (int i = 0; i < outPins.length; i++) { IFlow[] outFlowPin = outPins[i].getOutgoings(); for (int x = 0; x < outFlowPin.length; x++) { String nameObject; String type; try { nameObject = outPins[i].getBase().getName(); type = ((IObjectFlow)outFlowPin[x]).getBase().getName(); if (!type.equals(outPins[i].getBase().getName())) { throw new ParsingException("OutputPin "+ outPins[i].getName() + " and object flow have incompatible types!"); } } catch (NullPointerException e) { throw new ParsingException("Pin "+outPins[i].getName()+" without base class\n"); } Pair<IActivity,String> pair = new Pair<IActivity, String>(ad,outFlowPin[x].getId()); String oe; if (syncObjectsEdge.containsKey(pair)) { oe = syncObjectsEdge.get(pair); if (!objectEdges.containsKey(oe)) { objectEdges.put(oe, type); } } else { oe = createOE(); syncObjectsEdge.put(pair, oe); objectEdges.put(oe, type); } if (definitionFinal != null) {//not call behavior String value = ""; for (int j = 0; j < definitionFinal.length; j++) { String[] expression = definitionFinal[j].split("="); if (expression[0].equals(outPins[i].getName())) { value = expression[1]; } } String typeObj = nameObject; // defining bounds for model checking Pair<String, String> initialAndFinalParameterValue = getInitialAndFinalParameterValue(typeObj); if ((value != null && !value.equals("")) && ADUtils.isInteger(initialAndFinalParameterValue.getKey())) { action.append("(("); action.append("(" + value + ") >= " + initialAndFinalParameterValue.getKey() + " and (" + value + ") <= " + initialAndFinalParameterValue.getValue() + ") & "); } else { action.append("("); } if(value !=null && !value.equals("")) { if (i >= 0 && (i < outPins.length - 1 || x < outFlowPin.length - 1)) { oe(alphabet, action, oe, "!(" + value + ")", " -> SKIP) ||| "); } else { oe(alphabet, action, oe, "!(" + value + ")", " -> SKIP)"); } } else { if (nodeFullName != null) { if (i >= 0 && (i < outPins.length - 1 || x < outFlowPin.length - 1)) { oe(alphabet, action, oe, "!" + nodeFullName + "_" + outPins[i].getName(), " -> SKIP) ||| "); } else { oe(alphabet, action, oe, "!" + nodeFullName + "_" + outPins[i].getName(), " -> SKIP)"); } } else if (i >= 0 && (i < outPins.length - 1 || x < outFlowPin.length - 1)) { oe(alphabet, action, oe, "?unknown"+i, " -> SKIP) ||| "); } else { oe(alphabet, action, oe, "?unknown"+i, " -> SKIP)"); } } } else {// node is a call behavior action.append("("); if (i >= 0 && (i < outPins.length - 1 || x < outFlowPin.length - 1)) { getLocal(alphabet, action, nameResolver(outPins[i].getName()), nameResolver(outPins[i].getOwner().getName()), nameResolver(outPins[i].getName()),type); oe(alphabet, action, oe, "!(" + ((nodeFullName != null) ? nodeFullName : "") + outPins[i].getName() + ")", " -> SKIP) ||| "); } else { getLocal(alphabet, action, nameResolver(outPins[i].getName()), nameResolver(outPins[i].getOwner().getName()), nameResolver(outPins[i].getName()),type); oe(alphabet, action, oe, "!(" + ((nodeFullName != null) ? nodeFullName : "") + outPins[i].getName() + ")", " -> SKIP)"); } } } } if (outFlows.length > 0 || outPins.length > 0) { action.append("); "); } } }
41.764228
193
0.553325
068b5f36e15ece1bcd0bbd2f9586ab743b496b15
2,432
import java.util.HashSet; import java.util.Set; public class nextClosestTimePermutation { public Set<String> getAllPermutations(String s) { Set<String> permutations = new HashSet<String>(); if (s == null || s.length() == 0) { permutations.add(""); return permutations; } char firstChar = s.charAt(0); String remain = s.substring(1); Set<String> words = getAllPermutations(remain); for (String word : words) { for (int i = 0; i <= word.length(); i++) { String prefix = word.substring(0, i); String suffix = word.substring(i); permutations.add(prefix + firstChar + suffix); } } return permutations; } public int stringToTime(String s) { int hrs = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); int mins = (s.charAt(2) - '0') * 10 + (s.charAt(3) - '0'); return hrs * 60 + mins; } public boolean checkValid(String s) { int hrs = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); int mins = (s.charAt(2) - '0') * 10 + (s.charAt(3) - '0'); boolean valid = false; if (hrs < 24 && mins < 60) { valid = true; } return valid; } public String findClosestTime(String s) { String target = s.substring(0, 2) + s.substring(3); int curr = stringToTime(target); int minDiff = 24 * 60; int res = curr; Set<String> words = getAllPermutations(target); for (String word : words) { if (checkValid(word)) { int num = stringToTime(word); int diff = num - curr; if (diff < 0) { diff = 24 * 60 - curr + num; } if (diff < minDiff && diff > 0) { minDiff = diff; res = num; } } } return String.format("%02d:%02d", res / 60, res % 60); } public static void main(String[] args) { nextClosestTimePermutation test = new nextClosestTimePermutation(); System.out.println(test.findClosestTime("23:59")); System.out.println(test.findClosestTime("11:21")); System.out.println(test.findClosestTime("18:00")); System.out.println(test.findClosestTime("24:00")); System.out.println(test.findClosestTime("09:30")); System.out.println(test.findClosestTime("13:24")); System.out.println(test.findClosestTime("23:56")); System.out.println(test.findClosestTime("11:11")); System.out.println(test.findClosestTime("03:24")); System.out.println(test.findClosestTime("18:37")); System.out.println(test.findClosestTime("17:38")); System.out.println(test.findClosestTime("11:00")); } }
31.179487
69
0.629112
7c998769afef5f0ab00be361a668f38c9fbc2bb7
7,442
package nyla.solutions.core.patterns.workthread; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; /** * <b>Boss</b> work thread controls * <p> * Sample code * MemorizedQueue queue = new MemorizedQueue(); * Runnable task1 = new Runnable() * { * public void run() * { * try{ Thread.sleep(100); } catch(Exception e){} * <p> * System.out.println("I LOVE Queen Sheba task1"); * } * }; * <p> * <p> * Runnable task2 = new Runnable() * { * public void run() * { * try{ Thread.sleep(200); } catch(Exception e){} * System.out.println("I LOVE Queen Sheba task2"); * } * }; * <p> * <p> * Runnable task3 = new Runnable() * { * public void run() * { * try{ Thread.sleep(300); } catch(Exception e){} * System.out.println("I LOVE Queen Sheba task3"); * } * }; * <p> * queue.add(task1); * queue.add(task2); * queue.add(task3); * <p> * <p> * Boss boss = new Boss(queue); * <p> * WorkerThread worker1 = new WorkerThread(boss); * WorkerThread worker2 = new WorkerThread(boss); * WorkerThread worker3 = new WorkerThread(boss); * <p> * boss.manage(worker1); * boss.manage(worker2); * boss.manage(worker3); * <p> * StartState startState = new StartState(); * boss.setWorkState(startState); * * @author Gregory Green */ public class Boss implements Supervisor { private WorkState workState = null; private WorkQueue workQueue = null; private String name = getClass().getName(); private Collection<SupervisedWorker> workers = new HashSet<SupervisedWorker>(); /** * Constructor for Boss initializes internal * data settings. */ public Boss() { }// -------------------------------------------- /** * @param workQueue */ public Boss(WorkQueue workQueue) { this.setWorkQueue(workQueue); }// -------------------------------------------- /** * @see nyla.solutions.core.patterns.workthread.Supervisor#getWorkers() */ public Collection<SupervisedWorker> getWorkers() { return new ArrayList<SupervisedWorker>(this.workers); }// -------------------------------------------- /** * Manage a number of default worker threads * * @param workersCount the worker count */ public void manage(int workersCount) { this.workers.clear(); WorkerThread worker = null; for (int i = 0; i < workersCount; i++) { worker = new WorkerThread(this); //TODO expensive use thread pool this.manage(worker); } }// -------------------------------------------- /** * Add thread to managed list * * @param workers the supervised workers */ public void manage(Collection<SupervisedWorker> workers) { if (workers == null) return; this.workers.clear(); SupervisedWorker worker = null; for (Iterator<SupervisedWorker> i = workers.iterator(); i.hasNext(); ) { worker = i.next(); this.manage(worker); } }// -------------------------------------------- /** * Start workers by setting the start to "StartState" * * @param workCount the work count */ public void startWorkers(int workCount) { manage(workCount); this.setWorkState(new StartState()); }// -------------------------------------------- /** * Start workers by setting the start to "StartState" */ public void startWorkers() { this.setWorkState(new StartState()); }// -------------------------------------------- /** * Stop workers by setting the state to "StopState" */ public void stopWorkers() { this.setWorkState(new StopState()); }// -------------------------------------------- /** * Add thread to managed list * * @param worker the supervised worker */ public void manage(SupervisedWorker worker) { if (worker == null) throw new IllegalArgumentException("worker required in Boss.manage"); worker.setSupervisor(this); this.workers.add(worker); }// -------------------------------------------- public WorkQueue getWorkQueue() { return this.workQueue; }// -------------------------------------------- /** * call workstate.adverse(workers) * * @see nyla.solutions.core.patterns.workthread.Supervisor#setWorkState(nyla.solutions.core.patterns.workthread.WorkState) */ public void setWorkState(WorkState workState) { this.workState = workState; SupervisedWorker worker = null; for (Iterator<SupervisedWorker> i = workers.iterator(); i.hasNext(); ) { worker = (SupervisedWorker) i.next(); workState.advise(worker); } //threads Thread workerThread = null; for (Iterator<SupervisedWorker> i = workers.iterator(); i.hasNext(); ) { worker = i.next(); workerThread = worker.getThread(); if (workerThread != null) { try { workerThread.join(); } catch (Exception e) { } } } }// -------------------------------------------- /** * @see nyla.solutions.core.patterns.workthread.SupervisedWorker#setSupervisor(nyla.solutions.core.patterns.workthread.Supervisor) */ public void setSupervisor(Supervisor supervisor) { }// -------------------------------------------- /** * @see nyla.solutions.core.patterns.workthread.SupervisedWorker#getSupervisor() */ public Supervisor getSupervisor() { return null; }// -------------------------------------------- /** * @return the name */ public String getName() { return name; }// -------------------------------------------- /** * @param name the name to set */ public void setName(String name) { if (name == null) name = ""; this.name = name; }// -------------------------------------------- /** * @see nyla.solutions.core.patterns.workthread.SupervisedWorker#getThread() */ public Thread getThread() { return Thread.currentThread(); }// -------------------------------------------- /** * @param workQueue the workQueue to set */ public void setWorkQueue(WorkQueue workQueue) { if (workQueue == null) throw new IllegalArgumentException( "workQueue required in Boss.setWorkQueue"); this.workQueue = workQueue; }// -------------------------------------------- public void run() { }// -------------------------------------------- /** * @see nyla.solutions.core.patterns.workthread.SupervisedWorker#getWorkState() */ public WorkState getWorkState() { return workState; }// -------------------------------------------- }
25.662069
135
0.48401
0b6f15cf9c7f7af3e95fe06c0de60d5727a26971
359
package com.xkcoding.orm.mybatis.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author hwx * @date 2020/4/14 */ @Data @NoArgsConstructor @AllArgsConstructor public class Teacher implements Serializable { //主键 private Integer id; private String name ; }
15.608696
46
0.743733
221239f8882ba0e1a6d057bda9ea22b68fe04290
2,364
/* * The WhiteText project * * Copyright (c) 2012 University of British Columbia * * 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 ubic.pubmedgate.resolve.mentionEditors; import static ch.epfl.bbp.io.LineReader.linesFrom; import static ch.epfl.bbp.uima.BrainRegionsHelper.LEXICON_HOME; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class OfTheRemoverMentionEditor implements MentionEditor { protected static Log log = LogFactory .getLog(OfTheRemoverMentionEditor.class); List<String> toRemove; public OfTheRemoverMentionEditor() throws Exception { toRemove = new LinkedList<String>(); for (String word : linesFrom(LEXICON_HOME + "PartsOfTheWords.txt")) { // look for "of the" before "of" toRemove.add(word + " of the "); toRemove.add(word + " of "); } } public Set<String> editMention(String mention) { Set<String> result = new HashSet<String>(); // include the original // result.add( mention ); for (String remove : toRemove) { if (mention.contains(remove)) { mention = mention.replace(remove, ""); result.add(mention); } } if (mention.contains("of the ")) { mention = mention.replace("of the ", ""); result.add(mention); } return result; } public String getName() { return "Remover of \"of the\" type phrases"; } public static void main(String args[]) throws Exception { OfTheRemoverMentionEditor f = new OfTheRemoverMentionEditor(); log.info(f.editMention("middle part of the tectum")); } }
30.701299
77
0.655668
4683c153027382970e4a458147a9da8fc814c1c5
8,701
package com.atlassian.db.replica.internal.state; import com.atlassian.db.replica.api.DualConnection; import com.atlassian.db.replica.api.mocks.CircularConsistency; import com.atlassian.db.replica.api.mocks.ConnectionProviderMock; import com.atlassian.db.replica.spi.state.StateListener; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import java.sql.Connection; import java.sql.SQLException; import static com.atlassian.db.replica.api.Queries.SELECT_FOR_UPDATE; import static com.atlassian.db.replica.api.Queries.SIMPLE_QUERY; import static com.atlassian.db.replica.api.mocks.CircularConsistency.permanentConsistency; import static com.atlassian.db.replica.api.mocks.CircularConsistency.permanentInconsistency; import static com.atlassian.db.replica.api.state.State.CLOSED; import static com.atlassian.db.replica.api.state.State.MAIN; import static com.atlassian.db.replica.api.state.State.NOT_INITIALISED; import static com.atlassian.db.replica.api.state.State.COMMITED_MAIN; import static com.atlassian.db.replica.api.state.State.REPLICA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class ConnectionStateTest { private ConnectionProviderMock connectionProvider; private StateListener stateListener; @Before public void before() { this.stateListener = mock(StateListener.class); this.connectionProvider = new ConnectionProviderMock(); } @Test public void shouldChangeStateFromNotInitialisedToReplicaForExecuteQuery() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentConsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); verify(stateListener).transition(NOT_INITIALISED, REPLICA); } @Test public void shouldChangeStateFromNotInitialisedToMainForExecuteUpdate() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentConsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeUpdate(); verify(stateListener).transition(NOT_INITIALISED, MAIN); } @Test public void shouldChangeStateFromNotInitialisedToMainWhenInconsistent() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentInconsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeUpdate(); verify(stateListener).transition(NOT_INITIALISED, MAIN); } @Test public void shouldChangeStateFromNotInitialisedToMainForSelectForUpdate() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentInconsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SELECT_FOR_UPDATE).executeQuery(); verify(stateListener).transition(NOT_INITIALISED, MAIN); } @Test public void shouldChangeStateFromNotInitialisedToReplicaAndFromReplicaToMain() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentConsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); verify(stateListener).transition(NOT_INITIALISED, REPLICA); Mockito.reset(stateListener); connection.prepareStatement(SIMPLE_QUERY).executeUpdate(); verify(stateListener).transition(REPLICA, MAIN); } @Test public void shouldChangeStateOnce() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentConsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); verify(stateListener).transition(NOT_INITIALISED, REPLICA); } @Test public void shouldChangeStateFromNotInitialisedToClosed() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentConsistency().build() ).stateListener(stateListener) .build(); connection.close(); verify(stateListener).transition(NOT_INITIALISED, CLOSED); } @Test public void shouldChangeStateFromReplicaToClosed() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentConsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); Mockito.reset(stateListener); connection.close(); verify(stateListener).transition(REPLICA, CLOSED); } @Test public void shouldChangeStateFromMainToClosed() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentConsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); Mockito.reset(stateListener); connection.close(); verify(stateListener).transition(REPLICA, CLOSED); } @Test public void shouldAvoidReplicaDueToInconsistency() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentInconsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); verify(stateListener).transition(NOT_INITIALISED, COMMITED_MAIN); } @Test public void shouldAvoidReplicaEvenIfAlreadyAcquiredDueToPossibleTransactions() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, new CircularConsistency.Builder(ImmutableList.of(true, false)).build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); Mockito.reset(stateListener); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); verify(stateListener).transition(REPLICA, COMMITED_MAIN); } @Test public void shouldForgiveReplicaIfItCatchesUpOnReads() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, new CircularConsistency.Builder(ImmutableList.of(false, true)).build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); Mockito.reset(stateListener); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); verify(stateListener).transition(COMMITED_MAIN, REPLICA); } @Test public void shouldAvoidReplicaWhenMainAlreadyAcquiredDueToPossibleTransactions() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentInconsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); Mockito.reset(stateListener); connection.prepareStatement(SIMPLE_QUERY).executeUpdate(); verify(stateListener).transition(COMMITED_MAIN, MAIN); } @Test public void shouldReUseReadFromMainConnectionState() throws SQLException { final Connection connection = DualConnection.builder( connectionProvider, permanentInconsistency().build() ).stateListener(stateListener) .build(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); connection.prepareStatement(SIMPLE_QUERY).executeQuery(); verify(stateListener).transition(NOT_INITIALISED, COMMITED_MAIN); } }
36.558824
106
0.711642
e80ea47bed7d66615e0a6ad269f2f71e2f9a4cb3
491
package com.virjar.thanos.api.test.defaultbean; import com.virjar.thanos.api.GrabLogger; import com.virjar.thanos.api.bean.Seed; import com.virjar.thanos.api.services.TaskPushService; import com.virjar.thanos.api.test.TestBean; @TestBean public class TestTaskPushService implements TaskPushService { @Override public void pushNewSeed(String crawlerId, Seed seed) { //do nothing on test environment GrabLogger.info("ignore push task on test environment "); } }
28.882353
65
0.763747
2fa0b4a51112736f993f6d0083e9ea45d0c5ce4e
10,557
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.erd.ui.editor; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.Separator; import org.eclipse.swt.widgets.Composite; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.erd.model.ERDUtils; import org.jkiss.dbeaver.erd.ui.ERDUIConstants; import org.jkiss.dbeaver.erd.ui.action.DiagramTogglePersistAction; import org.jkiss.dbeaver.erd.ui.internal.ERDUIActivator; import org.jkiss.dbeaver.erd.ui.model.DiagramLoader; import org.jkiss.dbeaver.erd.ui.model.EntityDiagram; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.load.DatabaseLoadService; import org.jkiss.dbeaver.model.struct.DBSEntity; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.virtual.DBVObject; import org.jkiss.dbeaver.model.virtual.DBVUtils; import org.jkiss.dbeaver.ui.ActionUtils; import org.jkiss.dbeaver.ui.IActiveWorkbenchPart; import org.jkiss.dbeaver.ui.LoadingJob; import org.jkiss.dbeaver.ui.editors.DatabaseEditorUtils; import org.jkiss.dbeaver.ui.editors.IDatabaseEditor; import org.jkiss.dbeaver.ui.editors.IDatabaseEditorInput; import org.jkiss.dbeaver.ui.editors.entity.IEntityStructureEditor; import org.jkiss.dbeaver.erd.ui.action.DiagramExportAction; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.xml.XMLUtils; import org.w3c.dom.Document; import java.io.StringReader; import java.util.LinkedHashMap; import java.util.Map; /** * Embedded ERD editor */ public class ERDEditorEmbedded extends ERDEditorPart implements IDatabaseEditor, IEntityStructureEditor, IActiveWorkbenchPart { private static final Log log = Log.getLog(ERDEditorEmbedded.class); private static final String PROP_DIAGRAM_STATE = "erd.diagram.state"; private static final String PROPS_DIAGRAM_SERIALIZED = "serialized"; private static final String GROUP_SAVE = "save"; private Composite parent; /** * No-arg constructor */ public ERDEditorEmbedded() { } @Override public IDatabaseEditorInput getEditorInput() { return (IDatabaseEditorInput)super.getEditorInput(); } @Override public void recreateEditorControl() { // Not implemented } @Override public boolean isReadOnly() { return false; } @Override protected void fillDefaultEditorContributions(IContributionManager toolBarManager) { super.fillDefaultEditorContributions(toolBarManager); DiagramExportAction saveDiagram = new DiagramExportAction(this, parent.getShell()); toolBarManager.add(saveDiagram); toolBarManager.add(ActionUtils.makeActionContribution(new DiagramTogglePersistAction(this), true)); toolBarManager.add(new Separator(GROUP_SAVE)); DatabaseEditorUtils.contributeStandardEditorActions(getSite(), toolBarManager); } @Override public void activatePart() { if (progressControl == null) { super.createPartControl(parent); parent.layout(); } if (isLoaded()) { return; } loadDiagram(false); } @Override public void deactivatePart() { } @Override public void createPartControl(Composite parent) { // Do not create controls here - do it on part activation this.parent = parent; //super.createEditorControl(parent); } @Override public void setFocus() { if (progressControl != null) { super.setFocus(); } } private DBSObject getRootObject() { DBSObject object = getEditorInput().getDatabaseObject(); if (object == null) { return null; } if (object instanceof DBPDataSourceContainer && object.getDataSource() != null) { object = object.getDataSource(); } return object; } @Override protected synchronized void loadDiagram(final boolean refreshMetadata) { final DBSObject object = getRootObject(); if (object == null) { return; } if (diagramLoadingJob != null) { // Do not start new one while old is running return; } diagramLoadingJob = LoadingJob.createService( new DatabaseLoadService<EntityDiagram>("Load diagram '" + object.getName() + "'", object.getDataSource()) { @Override public EntityDiagram evaluate(DBRProgressMonitor monitor) { try { return loadFromDatabase(monitor); } catch (DBException e) { log.error("Error loading ER diagram", e); } return null; } }, progressControl.createLoadVisualizer()); diagramLoadingJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { diagramLoadingJob = null; } }); diagramLoadingJob.schedule(); } @Override public DBCExecutionContext getExecutionContext() { return getEditorInput().getExecutionContext(); } private EntityDiagram loadFromDatabase(DBRProgressMonitor monitor) throws DBException { DBSObject dbObject = getRootObject(); if (dbObject == null) { log.error("Database object must be entity container to render ERD diagram"); return null; } EntityDiagram diagram; if (!dbObject.isPersisted()) { diagram = new EntityDiagram(dbObject, "New Object", getContentProvider(), getDecorator()); } else { diagram = new EntityDiagram(dbObject, dbObject.getName(), getContentProvider(), getDecorator()); // Fill from database even if we loaded from state (something could change since last view) diagram.fillEntities( monitor, ERDUtils.collectDatabaseTables( monitor, dbObject, diagram, ERDUIActivator.getDefault().getPreferenceStore().getBoolean(ERDUIConstants.PREF_DIAGRAM_SHOW_VIEWS), ERDUIActivator.getDefault().getPreferenceStore().getBoolean(ERDUIConstants.PREF_DIAGRAM_SHOW_PARTITIONS)), dbObject); boolean hasPersistedState = false; try { // Load persisted state DBVObject vObject = this.getVirtualObject(); if (vObject != null) { Map<String, Object> diagramState = vObject.getProperty(PROP_DIAGRAM_STATE); if (diagramState != null) { String serializedDiagram = (String) diagramState.get(PROPS_DIAGRAM_SERIALIZED); if (!CommonUtils.isEmpty(serializedDiagram)) { Document xmlDocument = XMLUtils.parseDocument(new StringReader(serializedDiagram)); DiagramLoader.loadDiagram(monitor, xmlDocument, dbObject.getDataSource().getContainer().getProject(), diagram); hasPersistedState = true; } } } } catch (Exception e) { log.error("Error loading ER diagram from saved state", e); } diagram.setLayoutManualAllowed(true); diagram.setNeedsAutoLayout(!hasPersistedState); } return diagram; } @Override public void doSave(IProgressMonitor monitor) { try { // Save in virtual model as entity property. DBVObject vObject = this.getVirtualObject(); if (vObject == null) { return; } Map<String, Object> diagramStateMap = new LinkedHashMap<>(); vObject.setProperty(PROP_DIAGRAM_STATE, diagramStateMap); String diagramState = DiagramLoader.serializeDiagram(RuntimeUtils.makeMonitor(monitor), getDiagramPart(), getDiagram(), false, true); diagramStateMap.put(PROPS_DIAGRAM_SERIALIZED, diagramState); vObject.persistConfiguration(); getCommandStack().markSaveLocation(); } catch (Exception e) { log.error("Error saving diagram", e); } updateToolbarActions(); } public boolean isStateSaved() { DBVObject vObject = this.getVirtualObject(); return (vObject != null && vObject.getProperty(PROP_DIAGRAM_STATE) != null); } public void resetSavedState(boolean refreshDiagram) { try { DBVObject vObject = this.getVirtualObject(); if (vObject != null && vObject.getProperty(PROP_DIAGRAM_STATE) != null) { vObject.setProperty(PROP_DIAGRAM_STATE, null); vObject.persistConfiguration(); } } catch (Exception e) { log.error("Error resetting diagram state", e); } if (refreshDiagram) { refreshDiagram(true, true); } } @Nullable private DBVObject getVirtualObject() { DBSObject rootObject = getRootObject(); if (rootObject instanceof DBSEntity) { return DBVUtils.getVirtualEntity((DBSEntity) rootObject, true); } else { return DBVUtils.getVirtualObject(rootObject, true); } } }
35.19
145
0.645259
745f3b363793e75f7cccc2828b1b2fb77a20c2b7
3,611
package assets; import com.google.gson.Gson; import java.util.Random; public class Company { /** * Company's name. */ private final String name; /** * All possible values this share's companies can assume. */ private final int[] values; /** * Possible flutuation values that can be applied between rounds. */ private final int[] diceValues; /** * Current company's value index. */ private int currIndex; public Company(String name, int[] values, int[] diceValues){ this.name = name; this.values = values; this.diceValues = diceValues; currIndex = 3; } int getCurrentValue() { return values[currIndex]; } int maxValue(){ int maxIndexValue; int maxDiceValue = this.diceValues[diceValues.length - 1]; if(this.currIndex + maxDiceValue > this.values.length){ maxIndexValue = this.values.length - 1; } else if (this.currIndex + maxDiceValue < 0){ maxIndexValue = 0; } else{ maxIndexValue = this.currIndex + maxDiceValue; } return this.values[maxIndexValue]; } int minValue(){ int minIndexValue; int minDiceValue = this.diceValues[0]; if(this.currIndex + minDiceValue > this.values.length){ minIndexValue = this.values.length - 1; } else if (this.currIndex + minDiceValue < 0){ minIndexValue = 0; } else{ minIndexValue = this.currIndex + minDiceValue; } return this.values[minIndexValue]; } /** * Calculates the average value that will come out when the dices are rolled. * @return average of the next value after dice roll. */ float getAverageNextValue() { int averageValue = 0; for (int diceVal : diceValues) { int index = currIndex + diceVal; if (index < 0) { index = 0; } else if (index >= values.length) { index = values.length - 1; } averageValue += values[index]; } return (float)(averageValue/6); } public int risk() { int riskLevel; if (this.diceValues[0] == -1) { riskLevel = 0; } else if (this.diceValues[0] == -2) { riskLevel = 1; } else if (this.diceValues[0] == -3) { riskLevel = 2; } else riskLevel = 3; return riskLevel; } ; /** * Rolls the dice for this company, making its value change. * @return new value for this company's shares. */ public int rollDice() { // roll the dice Random r = new Random(); int diceIndex = r.nextInt(diceValues.length); int diceRollValue = diceValues[diceIndex]; // apply dice offset to determine company's new value currIndex += diceRollValue; if(currIndex<0) currIndex = 0; else if(currIndex >= values.length) currIndex = values.length-1; return values[currIndex]; } public String getName() { return name; } @Override public String toString() { return "{"+name+"("+values[currIndex]+")}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Company company = (Company) o; return name.equals(company.name); } public String toJsonStr(){ return new Gson().toJson(this); } }
23.756579
81
0.55414
e2a135684fa80aab29a9d9acd29a0a097d6b783c
102
package be.stip.soundboard.services; public enum AssetServiceResultCodes { CannotGetAsset }
17
38
0.764706