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
dd58ef630041bc232f4e8a8404e5f6f1477ffaad
70
package com.studentmgr.common.messages; public class InfoMessage { }
14
39
0.8
256984870eba81edcff8896f60b32aeb147a4ba9
1,943
package com.bitdubai.fermat_cbp_api.layer.business_transaction.customer_broke_bank_sale.interfaces; import com.bitdubai.fermat_cbp_api.all_definition.enums.BankCurrencyType; import com.bitdubai.fermat_cbp_api.all_definition.enums.BankOperationType; import com.bitdubai.fermat_cbp_api.all_definition.enums.BusinessTransactionStatus; import com.bitdubai.fermat_cbp_api.all_definition.enums.CurrencyType; import com.bitdubai.fermat_cbp_api.layer.business_transaction.customer_broke_bank_sale.exceptions.CantGetCustomerBrokerBankSaleException; import java.util.List; import java.util.UUID; /** * Created by Yordin Alayn on 23.09.15. */ public interface CustomerBrokerBankSaleManager { List<com.bitdubai.fermat_cbp_api.layer.business_transaction.customer_broke_bank_sale.interfaces.CustomerBrokerBankSale> getAllCustomerBrokerBankSaleFromCurrentDeviceUser() throws CantGetCustomerBrokerBankSaleException; com.bitdubai.fermat_cbp_api.layer.business_transaction.customer_broke_bank_sale.interfaces.CustomerBrokerBankSale createCustomerBrokerBankSale( final UUID contractId ,final String publicKeyBroker ,final String publicKeyCustomer ,final UUID paymentTransactionId ,final CurrencyType paymentCurrency ,final CurrencyType merchandiseCurrency ,final float merchandiseAmount ,final UUID executionTransactionId ,final BankCurrencyType bankCurrencyType ,final BankOperationType bankOperationType ) throws com.bitdubai.fermat_cbp_api.layer.business_transaction.customer_broke_bank_sale.exceptions.CantCreateCustomerBrokerBankSaleException; void updateStatusCustomerBrokerBankSale(final UUID transactionId,final BusinessTransactionStatus transactionStatus) throws com.bitdubai.fermat_cbp_api.layer.business_transaction.customer_broke_bank_sale.exceptions.CantUpdateStatusCustomerBrokerBankSaleException; }
52.513514
266
0.83016
547b413950925aa839e8f5ef0828258f4b8a8fb0
302
package eu.qualimaster.common.signal; /** * A listener for Curator signals. * * @author Cui Qin */ public interface SignalListener { /** * Is called upon signal reception. * * @param data the payload data */ public void onSignal(byte[] data); }
17.764706
40
0.57947
a24f163a7125055544b5c52f5f4a3f3a0c252dd3
1,245
package co.enoobong.billablehours.util; import co.enoobong.billablehours.backend.data.CompanyInvoice; import co.enoobong.billablehours.backend.data.Invoice; import co.enoobong.billablehours.backend.data.InvoiceResponse; import java.util.Collections; public final class TestUtil { public static final String CSV_ERROR_MESSAGE = "An error occurred at line 17 when processing timesheet. Please " + "verify that {employeeId=Yes, billableRate=No, project=Happy, date=20, startTime=10, endTime=5, =2}, is in the accepted format"; private TestUtil() { } public static InvoiceResponse invoiceResponse() { final InvoiceResponse invoiceResponse = new InvoiceResponse(); invoiceResponse.setErrors(Collections.singletonList(CSV_ERROR_MESSAGE)); invoiceResponse.addCompanyInvoice(companyInvoice()); return invoiceResponse; } public static CompanyInvoice companyInvoice() { final CompanyInvoice companyInvoice = new CompanyInvoice(); companyInvoice.setCompanyName("Google"); companyInvoice.setTotalCost(1024.00D); companyInvoice.setInvoices(Collections.singletonList(invoice())); return companyInvoice; } private static Invoice invoice() { return new Invoice(1L, 8L, 300D, 50D); } }
34.583333
138
0.767871
9b30d010b9599d9ddd387813c866e55af4ba66b9
415
package com.kirilanastasoff.ars.customer.service; import java.io.File; import java.io.IOException; import org.thymeleaf.context.Context; import com.lowagie.text.DocumentException; public interface PdfService { File generatePdf()throws IOException,DocumentException; File renderPdf(String html)throws IOException,DocumentException; Context getContext(); String loadAndFillTemplate(Context context); }
20.75
65
0.814458
b69035a8f19b219bbdad8edf62ac6990363a2d2c
476
package com.buschmais.xo.api.annotation; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Declares a type as abstract, i.e. it is only allowed to createa an instance * from a non-abstract extending type or as a composite with at least * non-abstract type. */ @Target(TYPE) @Retention(RUNTIME) public @interface Abstract { }
26.444444
78
0.779412
1fe2a6441fb11a077f79b18e13ce1507b61fa1ca
510
package com.liuzhihang.doc.view.facade; import com.liuzhihang.doc.view.facade.dto.ShowDocUpdateRequest; import com.liuzhihang.doc.view.facade.dto.ShowDocUpdateResponse; /** * ShowDoc 文档对接 * <p> * <p> * https://www.showdoc.com.cn/page/102098 * * @author liuzhihang * @date 2021/7/27 12:43 */ public interface ShowDocFacadeService { /** * 上传到 ShowDoc * * @param request * @return */ ShowDocUpdateResponse updateByApi(ShowDocUpdateRequest request) throws Exception; }
19.615385
85
0.696078
c86d0b4420e333e0efd8746355824c728c5f69e7
4,457
package com.twu.biblioteca.models; import com.twu.biblioteca.repository.BookRepository; import com.twu.biblioteca.repository.LoginRepository; import com.twu.biblioteca.repository.MovieRepository; import com.twu.biblioteca.repository.RentRepository; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class CatalogTest { @Before public void before(){ BookRepository.books = new ArrayList<Asset>(Arrays.asList(new Book("To kill a Mockingbird", "Harper Lee", "1960", 1))); } @Test public void shouldCheckoutAnAssetWithTitle(){ Catalog catalog = new Catalog(new BookRepository()); String bookToCheckout = "To kill a Mockingbird"; int availableBooks = catalog.getAvailableAssets().size(); int rentedAssets = new RentRepository().rents.size(); // When boolean successfulCheckout = catalog.checkoutAsset(bookToCheckout); int currentAvailableBooks = catalog.getAvailableAssets().size(); int currentRentedAssets = new RentRepository().rents.size(); assertTrue(currentAvailableBooks < availableBooks); assertTrue(currentRentedAssets > rentedAssets); assertThat(successfulCheckout, is(true)); } @Test public void shouldNotCheckoutAnAssetWithInvalidTitle(){ Catalog catalog = new Catalog(new BookRepository()); String invalidBookToCheckout = "To kill a Mockingbirdo"; int availableBooks = catalog.getAvailableAssets().size(); int rentedAssets = new RentRepository().rents.size(); // When boolean successfulCheckout = catalog.checkoutAsset(invalidBookToCheckout); int currentAvailableBooks = catalog.getAvailableAssets().size(); int currentRentedAssets = new RentRepository().rents.size(); assertTrue(currentAvailableBooks == availableBooks && !successfulCheckout); assertThat(currentRentedAssets, is(rentedAssets)); } @Test public void shouldNotCheckoutAUnavailableAsset(){ Catalog catalog = new Catalog(new BookRepository()); String bookToCheckout = "To kill a Mockingbird"; catalog.checkoutAsset(bookToCheckout); int availableBooks = catalog.getAvailableAssets().size(); int rentedAssets = new RentRepository().rents.size(); // When boolean successfulCheckout = catalog.checkoutAsset(bookToCheckout); int currentAvailableBooks = catalog.getAvailableAssets().size(); int currentRentedAssets = new RentRepository().rents.size(); assertTrue(currentAvailableBooks == availableBooks && !successfulCheckout); assertThat(currentRentedAssets, is(rentedAssets)); } @Test public void shouldCheckInAValidAssetByTitle(){ LoginRepository.loggedInUser = new User("123-1234", "123", "Name", "[email protected]", "11 1234-5678" ); String bookTitle = "To kill a Mockingbird"; Catalog catalog = new Catalog(new BookRepository()); catalog.checkoutAsset(bookTitle); int rentedAssets = new RentRepository().rents.size(); // When boolean successfulCheckIn = catalog.checkInAsset(bookTitle); int currentRentedAssets = new RentRepository().rents.size(); assertTrue(successfulCheckIn); assertTrue(rentedAssets > currentRentedAssets); } @Test public void shouldNotCheckInAInvalidAsset(){ String invalidBookTitle = "invalid"; Catalog catalog = new Catalog(new MovieRepository()); int rentedAssets = new RentRepository().rents.size(); // When boolean successfulCheckIn = catalog.checkInAsset(invalidBookTitle); int currentRentedAssets = new RentRepository().rents.size(); assertFalse(successfulCheckIn); assertThat(rentedAssets, is(currentRentedAssets)); } @Test public void shouldNotCheckInAAvailableAsset(){ String invalidBookTitle = "To kill a Mockingbird"; Catalog catalog = new Catalog(new BookRepository()); int rentedAssets = new RentRepository().rents.size(); // When boolean successfulCheckIn = catalog.checkInAsset(invalidBookTitle); int currentRentedAssets = new RentRepository().rents.size(); assertFalse(successfulCheckIn); assertThat(rentedAssets, is(currentRentedAssets)); } }
39.794643
127
0.699574
b3d01df2b752b7b113f7aca198d1af04ddd5d686
3,392
package headfront.guiwidgets; import headfront.services.ProcessService; import javafx.beans.property.SimpleStringProperty; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.VBoxBuilder; import javafx.scene.paint.Color; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.Callback; import org.springframework.beans.factory.annotation.Autowired; import java.util.function.BiConsumer; /** * Created by Deepak on 03/04/2016. */ public class ConfirmHandler implements Callback<String, Boolean> { private Stage parent; @Autowired private ProcessService processService; public ConfirmHandler(final Stage parent) { this.parent = parent; } @Override public Boolean call(String msg) { final SimpleStringProperty confirmationResult = new SimpleStringProperty(); // initialize the confirmation dialog final Stage dialog = new Stage(StageStyle.TRANSPARENT); dialog.initOwner(parent); dialog.initModality(Modality.WINDOW_MODAL); Label ampsAdminPageLabel = createOption("Amps Admin Page", msg, dialog, this::openWebLink); Label dataViewer = createOption("DataViewer", msg, dialog, this::startJavaProcess); Label closeLabel = createOption("Cancel", msg, dialog, (name, mmsg) -> dialog.close()); dialog.setScene( new Scene( VBoxBuilder.create().children(ampsAdminPageLabel, dataViewer, closeLabel ).build() , Color.TRANSPARENT ) ); String[] split = msg.split(","); dialog.setX(Integer.parseInt(split[2])); dialog.setY(Integer.parseInt(split[3]) + 50); dialog.showAndWait(); confirmationResult.get(); return true; } private Label createOption(String optionName, String fullCommand, Stage dialog, BiConsumer<String, String> consumer) { Label label = new Label(optionName); label.setOnMouseClicked(e -> { dialog.close(); consumer.accept(fullCommand, optionName); }); label.setOnMouseEntered(e -> { label.setBackground(new Background(new BackgroundFill(Color.LIGHTBLUE, CornerRadii.EMPTY, Insets.EMPTY))); }); label.setOnMouseExited(e -> { label.setBackground(null); }); return label; } private void openWebLink(String fullCommand, String optionName) { String[] split = fullCommand.split(","); Stage stage = new Stage(); String url = split[1]; WebView browser = new WebView(); WebEngine webEngine = browser.getEngine(); webEngine.load(url); stage.setScene(new Scene(browser)); stage.setTitle(split[0] + " " + split[1]); stage.setX(100); stage.setY(100); stage.setWidth(1000); stage.setHeight(700); stage.show(); stage.toFront(); } private void startJavaProcess(String fullCommand, String optionName) { processService.launchJavaProcess(optionName); } }
32.932039
122
0.660672
7d5a7bfe1e2639b1998a342815b0f880a037e9ff
1,412
/* * Copyright 2015-2017 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.client.test.inventory; import org.hawkular.client.core.ClientResponse; import org.hawkular.client.test.BaseTest; import org.testng.Assert; import org.testng.annotations.Test; @Test(groups = {"inventory"}, dependsOnGroups = "inventory-bulkcreate", enabled = false) public class GraphTest extends BaseTest { @Test(enabled = false) public void getGraph() { //TODO: https://gist.github.com/garethahealy/0a7d7403f329d8768ab4cab4dcf2c409 ClientResponse<String> response = client() .inventory() .graph() .getGraph(); Assert.assertTrue(response.isSuccess(), response.getErrorMsg()); Assert.assertNotNull(response.getEntity()); } }
35.3
88
0.71813
a16f80f4a425d6a97feeeaae0b161e8376933109
842
package section_17_lendo_txt; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class ProgramaLerTXT { public static void main(String[] args) { File file = new File("src\\section_17_lendo_txt\\herois.txt"); Scanner scanner = null; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } } catch (FileNotFoundException e) { System.out.println("Arquivo não encontrado " + e); } catch (IOException e) { System.out.println("Erro ao ler arquivo " + e); } finally { if (scanner != null) { scanner.close(); } } } }
29.034483
71
0.551069
8eac9cc6e9add2d578427a66fb26d8bcf7a75261
8,142
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|activemq package|; end_package begin_import import|import name|javax operator|. name|jms operator|. name|Connection import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|DeliveryMode import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Destination import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|JMSException import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|MessageConsumer import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Session import|; end_import begin_comment comment|/** * @version */ end_comment begin_class specifier|public class|class name|JmsTopicSendReceiveWithTwoConnectionsTest extends|extends name|JmsSendReceiveTestSupport block|{ specifier|private specifier|static specifier|final name|org operator|. name|apache operator|. name|commons operator|. name|logging operator|. name|Log name|LOG init|= name|org operator|. name|apache operator|. name|commons operator|. name|logging operator|. name|LogFactory operator|. name|getLog argument_list|( name|JmsTopicSendReceiveWithTwoConnectionsTest operator|. name|class argument_list|) decl_stmt|; specifier|protected name|Connection name|sendConnection decl_stmt|; specifier|protected name|Connection name|receiveConnection decl_stmt|; specifier|protected name|Session name|receiveSession decl_stmt|; specifier|protected name|void name|setUp parameter_list|() throws|throws name|Exception block|{ name|super operator|. name|setUp argument_list|() expr_stmt|; name|connectionFactory operator|= name|createConnectionFactory argument_list|() expr_stmt|; name|sendConnection operator|= name|createSendConnection argument_list|() expr_stmt|; name|sendConnection operator|. name|start argument_list|() expr_stmt|; name|receiveConnection operator|= name|createReceiveConnection argument_list|() expr_stmt|; name|receiveConnection operator|. name|start argument_list|() expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Created sendConnection: " operator|+ name|sendConnection argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Created receiveConnection: " operator|+ name|receiveConnection argument_list|) expr_stmt|; name|session operator|= name|createSendSession argument_list|( name|sendConnection argument_list|) expr_stmt|; name|receiveSession operator|= name|createReceiveSession argument_list|( name|receiveConnection argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Created sendSession: " operator|+ name|session argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Created receiveSession: " operator|+ name|receiveSession argument_list|) expr_stmt|; name|producer operator|= name|session operator|. name|createProducer argument_list|( literal|null argument_list|) expr_stmt|; name|producer operator|. name|setDeliveryMode argument_list|( name|deliveryMode argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Created producer: " operator|+ name|producer operator|+ literal|" delivery mode = " operator|+ operator|( name|deliveryMode operator|== name|DeliveryMode operator|. name|PERSISTENT condition|? literal|"PERSISTENT" else|: literal|"NON_PERSISTENT" operator|) argument_list|) expr_stmt|; if|if condition|( name|topic condition|) block|{ name|consumerDestination operator|= name|session operator|. name|createTopic argument_list|( name|getConsumerSubject argument_list|() argument_list|) expr_stmt|; name|producerDestination operator|= name|session operator|. name|createTopic argument_list|( name|getProducerSubject argument_list|() argument_list|) expr_stmt|; block|} else|else block|{ name|consumerDestination operator|= name|session operator|. name|createQueue argument_list|( name|getConsumerSubject argument_list|() argument_list|) expr_stmt|; name|producerDestination operator|= name|session operator|. name|createQueue argument_list|( name|getProducerSubject argument_list|() argument_list|) expr_stmt|; block|} name|LOG operator|. name|info argument_list|( literal|"Created consumer destination: " operator|+ name|consumerDestination operator|+ literal|" of type: " operator|+ name|consumerDestination operator|. name|getClass argument_list|() argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Created producer destination: " operator|+ name|producerDestination operator|+ literal|" of type: " operator|+ name|producerDestination operator|. name|getClass argument_list|() argument_list|) expr_stmt|; name|consumer operator|= name|createConsumer argument_list|( name|receiveSession argument_list|, name|consumerDestination argument_list|) expr_stmt|; name|consumer operator|. name|setMessageListener argument_list|( name|this argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"Started connections" argument_list|) expr_stmt|; block|} specifier|protected name|Session name|createReceiveSession parameter_list|( name|Connection name|receiveConnection parameter_list|) throws|throws name|Exception block|{ return|return name|receiveConnection operator|. name|createSession argument_list|( literal|false argument_list|, name|Session operator|. name|AUTO_ACKNOWLEDGE argument_list|) return|; block|} specifier|protected name|Session name|createSendSession parameter_list|( name|Connection name|sendConnection parameter_list|) throws|throws name|Exception block|{ return|return name|sendConnection operator|. name|createSession argument_list|( literal|false argument_list|, name|Session operator|. name|AUTO_ACKNOWLEDGE argument_list|) return|; block|} specifier|protected name|Connection name|createReceiveConnection parameter_list|() throws|throws name|Exception block|{ return|return name|createConnection argument_list|() return|; block|} specifier|protected name|Connection name|createSendConnection parameter_list|() throws|throws name|Exception block|{ return|return name|createConnection argument_list|() return|; block|} specifier|protected name|MessageConsumer name|createConsumer parameter_list|( name|Session name|session parameter_list|, name|Destination name|dest parameter_list|) throws|throws name|JMSException block|{ return|return name|session operator|. name|createConsumer argument_list|( name|dest argument_list|) return|; block|} specifier|protected name|ActiveMQConnectionFactory name|createConnectionFactory parameter_list|() throws|throws name|Exception block|{ return|return operator|new name|ActiveMQConnectionFactory argument_list|( literal|"vm://localhost?broker.persistent=false" argument_list|) return|; block|} specifier|protected name|void name|tearDown parameter_list|() throws|throws name|Exception block|{ name|session operator|. name|close argument_list|() expr_stmt|; name|receiveSession operator|. name|close argument_list|() expr_stmt|; name|sendConnection operator|. name|close argument_list|() expr_stmt|; name|receiveConnection operator|. name|close argument_list|() expr_stmt|; block|} block|} end_class end_unit
16.251497
811
0.813928
63ee361ec13ab9162c179933b67d4b233430d000
586
package lk.ijse.dep.web.library.business.custom; import lk.ijse.dep.web.library.business.SuperBO; import lk.ijse.dep.web.library.dto.MemberDTO; import java.util.List; /** * @author : Lucky Prabath <[email protected]> * @since : 2021-02-05 **/ public interface MemberBO extends SuperBO { void saveMember(MemberDTO dto) throws Exception; void updateMember(MemberDTO dto) throws Exception; void deleteMember(String memberId) throws Exception; List<MemberDTO> getAllMembers() throws Exception; MemberDTO getMember(String memberId) throws Exception; }
24.416667
58
0.754266
a7a11839e4e73d7608694e78783490aa5012f172
4,510
package com.codingmore.service.impl; import cn.hutool.core.collection.CollectionUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.codingmore.dto.PostsPageQueryParam; import com.codingmore.mapper.RoleResourceRelationMapper; import com.codingmore.model.Menu; import com.codingmore.model.Resource; import com.codingmore.model.Role; import com.codingmore.dto.RolePageQueryParam; import com.codingmore.mapper.RoleMapper; import com.codingmore.model.RoleMenuRelation; import com.codingmore.model.RoleResourceRelation; import com.codingmore.service.IRoleMenuRelationService; import com.codingmore.service.IRoleResourceRelationService; import com.codingmore.service.IRoleService; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.codingmore.service.IUsersCacheService; import com.codingmore.vo.RoleVo; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * <p> * 后台用户角色表 服务实现类 * </p> * * @author 石磊 * @since 2022-03-03 */ @Service public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService { @Autowired private RoleMapper roleMapper; @Autowired private IRoleMenuRelationService roleMenuRelationService; @Autowired private IRoleResourceRelationService roleResourceRelationService; @Autowired private IUsersCacheService usersCacheService; @Override public List<Menu> getMenuList(Long userId) { return roleMapper.getMenuList(userId); } @Override public List<Menu> listMenu(Long roleId) { return roleMapper.getMenuListByRoleId(roleId); } @Override public List<Resource> listResource(Long roleId) { return roleMapper.getResourceListByRoleId(roleId); } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public int allocMenu(Long roleId, List<Long> menuIds) { //先删除原有关系 QueryWrapper<RoleMenuRelation> queryWrapper = new QueryWrapper<RoleMenuRelation>(); queryWrapper.eq("role_id",roleId); roleMenuRelationService.remove(queryWrapper); List<RoleMenuRelation> relationList = new ArrayList<RoleMenuRelation>(); //批量插入新关系 for (Long menuId : menuIds) { RoleMenuRelation relation = new RoleMenuRelation(); relation.setRoleId(roleId); relation.setMenuId(menuId); relationList.add(relation); } roleMenuRelationService.saveBatch(relationList); return menuIds.size(); } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public int allocResource(Long roleId, List<Long> resourceIds) { //先删除原有关系 QueryWrapper<RoleResourceRelation> queryWrapper = new QueryWrapper<RoleResourceRelation>(); queryWrapper.eq("role_id",roleId); roleResourceRelationService.remove(queryWrapper); List<RoleResourceRelation> relationList = new ArrayList<RoleResourceRelation>(); //批量插入新关系 for (Long resourceId : resourceIds) { RoleResourceRelation relation = new RoleResourceRelation(); relation.setRoleId(roleId); relation.setResourceId(resourceId); relationList.add(relation); } roleResourceRelationService.saveBatch(relationList); usersCacheService.delResourceListByRole(roleId); return resourceIds.size(); } @Override public IPage<RoleVo> findByPage(RolePageQueryParam param) { QueryWrapper<RolePageQueryParam> queryWrapper = new QueryWrapper<>(); if(StringUtils.isNotBlank(param.getKeyword())){ queryWrapper.like("name",param.getKeyword()); } Page<RoleVo> postsPage = new Page<>(param.getPage(), param.getPageSize()); return roleMapper.findByPage(postsPage,queryWrapper); } @Override public boolean batchRemove(List<Long> roleIds) { usersCacheService.delResourceListByRoleIds(roleIds); return this.removeByIds(roleIds); } }
36.08
102
0.730377
bc422a917b3bb57999810668733b409f7bfa3e42
900
package pt.up.fc.dcc.asura.snake.models; import pt.up.fc.dcc.asura.builder.base.movie.GameMovieBuilder; import pt.up.fc.dcc.asura.snake.utils.Sprite; import pt.up.fc.dcc.asura.snake.utils.SpriteManager; import pt.up.fc.dcc.asura.snake.utils.Vector; import static pt.up.fc.dcc.asura.snake.SnakeState.TILE_LENGTH; /** * Block of a barrier in Snake map * * @author José Carlos Paiva <code>[email protected]</code> */ public class Block extends Actor { private Sprite sprite; public Block(Vector position) { super(position, new Vector(0, 0)); this.sprite = SpriteManager.getSpriteFor(this); } @Override public void onUpdate() { } @Override public void draw(GameMovieBuilder builder) { builder.addItem(sprite.getName(), TILE_LENGTH * getPosition().getX(), TILE_LENGTH * getPosition().getY()); } }
25
63
0.676667
e6dc247149bf44e3f44134a1b6d8b23f7486fb0d
918
package com.zte.iui.layoutit.bean.vm.visibility; import java.util.ArrayList; import java.util.List; public class OrganizeVisibility { private List<Visibility> visibilityList; public OrganizeVisibility(String visibility) { if (visibility != null && !visibility.isEmpty()) { String[] arr = visibility.split("@"); visibilityList = new ArrayList<Visibility>(); for (String param : arr) { visibilityList.add(new Visibility(param)); } } } /** * 获取组件可显示属性js代码 * * @return */ public String getComponentVisibilityJSCode() { StringBuffer buffer = new StringBuffer(); if(this.visibilityList != null){ for(Visibility item:visibilityList){ if(item.isHided()){ buffer.append("\t$(\"#"+item.getId()+"\").hide();\n"); }else{ buffer.append("\t$(\"#"+item.getId()+"\").show();\n"); } } } return buffer.toString(); } }
23.538462
60
0.618736
0885ea7daf807f136b926f41f795637a676a10d4
3,360
/* * Copyright (c) 2022 Mark S. Kolich * https://mark.koli.ch * * 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 onyx.components.search; import onyx.entities.storage.aws.dynamodb.Resource; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutorService; public interface SearchManager { String INDEX_FIELD_PATH = "path"; String INDEX_FIELD_PATH_LOWER = "pathLower"; String INDEX_FIELD_PARENT = "parent"; String INDEX_FIELD_DESCRIPTION = "description"; String INDEX_FIELD_DESCRIPTION_LOWER = "descriptionLower"; String INDEX_FIELD_SIZE = "size"; String INDEX_FIELD_TYPE = "type"; String INDEX_FIELD_VISIBILITY = "visibility"; String INDEX_FIELD_OWNER = "owner"; String INDEX_FIELD_CREATED = "created"; String INDEX_FIELD_FAVORITE = "favorite"; // Derived fields String INDEX_FIELD_NAME = "name"; String INDEX_FIELD_NAME_LOWER = "nameLower"; // Query fields String QUERY_FIELD_SCORE = "score"; void addResourceToIndex( final Resource resource); default void addResourceToIndexAsync( final Resource resource, final ExecutorService executorService) { executorService.submit(() -> addResourceToIndex(resource)); } void addResourcesToIndex( final Collection<Resource> resources); default void addResourcesToIndexAsync( final Collection<Resource> resources, final ExecutorService executorService) { executorService.submit(() -> addResourcesToIndex(resources)); } void deleteResourceFromIndex( final Resource resource); default void deleteResourceFromIndexAsync( final Resource resource, final ExecutorService executorService) { executorService.submit(() -> deleteResourceFromIndex(resource)); } void deleteResourcesFromIndex( final Collection<Resource> resources); default void deleteResourcesFromIndexAsync( final Collection<Resource> resources, final ExecutorService executorService) { executorService.submit(() -> deleteResourcesFromIndex(resources)); } void deleteIndex(); List<Resource> searchIndex( final String owner, final String query); }
33.267327
74
0.714583
f8789d8870bb7f4ac2954da2cce13a195d30132b
264
/** * Package contains implementation * of {@link info.smart_tools.smartactors.base.interfaces.iresolve_dependency_strategy.IResolveDependencyStrategy} */ package info.smart_tools.smartactors.ioc_strategy_pack.resolve_by_composite_name_ioc_with_lambda_strategy;
52.8
114
0.867424
784791303d49d7b1135d7abe368ef1e86b1138e2
1,344
/** * Copyright 2017 SPeCS. * * 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. under the License. */ package pt.up.fe.specs.lara.doc.aspectir; import java.util.stream.Stream; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactoryConfigurationError; import pt.up.fe.specs.lara.aspectir.Base; import tdrc.utils.StringUtils; public class BaseNodes { public static String toXml(Base base) { try { return StringUtils.xmlToStringBuffer(base.getXmlDocument(), 3).toString(); } catch (TransformerFactoryConfigurationError | TransformerException e) { throw new RuntimeException("Could not convert aspect IR node to XML: ", e); } } public static Stream<Base> toStream(Base base) { return BaseVisitor.getBaseToStream().apply(base); } }
34.461538
118
0.730655
22c737289123d39561e64b9bd1e8a97db7dddad1
583
package com.rest.car.bean; import org.codehaus.jackson.annotate.JsonProperty; public class InListDetail { @JsonProperty("cmd") private String cmd; @JsonProperty("name") private String name; @JsonProperty("pri") private int pri; public String getCmd() { return cmd; } public void setCmd(String cmd) { this.cmd = cmd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPri() { return pri; } public void setPri(int pri) { this.pri = pri; } }
14.219512
51
0.627787
29d815aac1ce258d39f8d91d92079680949f0dfb
1,457
package de.m4lik.burningseries.ui.listitems; /** * Created by Malik on 12.06.2016. */ public class ShowListItem { public Boolean loaded = false; private Integer id; private String title; private String genre; private boolean fav; public ShowListItem(String title, Integer id, String genre, boolean fav) { this.id = id; this.title = title; this.genre = genre; this.fav = fav; } public int compareTo(ShowListItem item) { return this.getTitle().compareTo(item.getTitle()); } public Integer getId() { return id; } public String getTitle() { return title; } public String getGenre() { return genre; } public boolean isFav() { return fav; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShowListItem that = (ShowListItem) o; if (fav != that.fav) return false; if (title != null ? !title.equals(that.title) : that.title != null) return false; return genre != null ? genre.equals(that.genre) : that.genre == null; } @Override public int hashCode() { int result = title != null ? title.hashCode() : 0; result = 31 * result + (genre != null ? genre.hashCode() : 0); result = 31 * result + (fav ? 1 : 0); return result; } }
23.5
89
0.574468
8c98098f37071f83e523ece48e2504e07e7f8799
1,122
package com.gwtjs.icustom.springsecurity.service; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.gwtjs.icustom.springsecurity.entity.SysUserVO; /** * http://localhost:8080/api/application.wadl * * http://localhost:8080/security/core/api/user/findAllUserList * * @author aGuang * */ @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/user") @Component @Service public interface IUserRestService { /** * 用户登陆会用到 */ @GET @Path("/findByUsername/{username}") public SysUserVO findByUsername(String username); /** * 用户登陆会用到 */ @GET @Path("/findByAccount/{account}") public SysUserVO findByAccount(@PathParam("account") String account); /** * 批量插入用户数据 * * @param userList * @return */ @POST @Path("/saveOrUpdate") int saveOrUpdate(List<SysUserVO> userList); }
19.344828
70
0.731729
385d3649acb5034a75fad0c345ad3ac52032c80e
3,419
/* * Accounting API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.xero.models.accounting; import java.util.Objects; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Phone */ public class Phone { @JsonProperty("PhoneNumber") private String phoneNumber = null; @JsonProperty("PhoneAreaCode") private String phoneAreaCode = null; @JsonProperty("PhoneCountryCode") private String phoneCountryCode = null; public Phone phoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; return this; } /** * max length &#x3D; 50 * @return phoneNumber **/ @ApiModelProperty(value = "max length = 50") public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Phone phoneAreaCode(String phoneAreaCode) { this.phoneAreaCode = phoneAreaCode; return this; } /** * max length &#x3D; 10 * @return phoneAreaCode **/ @ApiModelProperty(value = "max length = 10") public String getPhoneAreaCode() { return phoneAreaCode; } public void setPhoneAreaCode(String phoneAreaCode) { this.phoneAreaCode = phoneAreaCode; } public Phone phoneCountryCode(String phoneCountryCode) { this.phoneCountryCode = phoneCountryCode; return this; } /** * max length &#x3D; 20 * @return phoneCountryCode **/ @ApiModelProperty(value = "max length = 20") public String getPhoneCountryCode() { return phoneCountryCode; } public void setPhoneCountryCode(String phoneCountryCode) { this.phoneCountryCode = phoneCountryCode; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Phone phone = (Phone) o; return Objects.equals(this.phoneNumber, phone.phoneNumber) && Objects.equals(this.phoneAreaCode, phone.phoneAreaCode) && Objects.equals(this.phoneCountryCode, phone.phoneCountryCode); } @Override public int hashCode() { return Objects.hash(phoneNumber, phoneAreaCode, phoneCountryCode); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Phone {\n"); sb.append(" phoneNumber: ").append(toIndentedString(phoneNumber)).append("\n"); sb.append(" phoneAreaCode: ").append(toIndentedString(phoneAreaCode)).append("\n"); sb.append(" phoneCountryCode: ").append(toIndentedString(phoneCountryCode)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
24.775362
109
0.688213
032225acbc3c76137744d87f89d809c6375447dc
195
package mounderfod.moundertweaks.impl; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class MounderTweaks { }
21.666667
43
0.820513
cfd8ef0f8655af9010da2246869d389e2bbcf164
3,899
// Copyright 2021 Goldman Sachs // // 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.finos.legend.depot.store.guice; import com.google.inject.Binder; import org.finos.legend.depot.artifacts.repository.api.ArtifactRepository; import org.finos.legend.depot.artifacts.repository.api.ArtifactRepositoryProviderConfiguration; import org.finos.legend.depot.artifacts.repository.api.VoidArtifactRepositoryProvider; import org.finos.legend.depot.core.http.guice.BaseModule; import org.finos.legend.depot.domain.project.IncludeProjectPropertiesConfiguration; import org.finos.legend.depot.store.notifications.domain.QueueManagerConfiguration; import org.finos.legend.depot.store.server.configuration.DepotStoreServerConfiguration; import org.slf4j.Logger; public class DepotStoreServerModule extends BaseModule<DepotStoreServerConfiguration> { private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(DepotStoreServerModule.class); private ArtifactRepository artifactRepository; @Override public void configure(Binder binder) { super.configure(binder); binder.bind(ArtifactRepository.class).toProvider(this::getArtifactRepository); binder.bind(ArtifactRepositoryProviderConfiguration.class).toProvider(this::getArtifactRepositoryConfiguration); binder.bind(IncludeProjectPropertiesConfiguration.class).toProvider(this::getIncludePropertiesConfiguration); binder.bind(QueueManagerConfiguration.class).toProvider(this::getQueueManagerConfiguration); } private QueueManagerConfiguration getQueueManagerConfiguration() { return getConfiguration().getQueueManagerConfiguration() != null ? getConfiguration().getQueueManagerConfiguration() : new QueueManagerConfiguration(); } private IncludeProjectPropertiesConfiguration getIncludePropertiesConfiguration() { return getConfiguration().getIncludeProjectPropertiesConfiguration(); } private ArtifactRepositoryProviderConfiguration getArtifactRepositoryConfiguration() { ArtifactRepositoryProviderConfiguration configuration = getConfiguration().getArtifactRepositoryProviderConfiguration(); return (configuration == null) ? ArtifactRepositoryProviderConfiguration.voidConfiguration() : configuration; } private ArtifactRepository getArtifactRepository() { if (artifactRepository == null) { LOGGER.info("resolving Artifact Repository provider"); artifactRepository = resolveArtifactRepositoryProvider(); } return artifactRepository; } private ArtifactRepository resolveArtifactRepositoryProvider() { ArtifactRepositoryProviderConfiguration configuration = getConfiguration().getArtifactRepositoryProviderConfiguration(); if (configuration != null) { ArtifactRepository configuredProvider = configuration.initialiseArtifactRepositoryProvider(); if (configuredProvider != null) { LOGGER.info("Artifact Repository from provider config [{}] : [{}]", configuration.getName(), configuration); return configuredProvider; } } LOGGER.error("Using void Artifact Repository provider, artifacts cant/wont be updated"); return new VoidArtifactRepositoryProvider(configuration); } }
44.816092
159
0.760708
7af4d01f818c717e29378abc3a8b0c058b21070a
729
package com.jbd.saop.around; import com.jbd.saop.around.dao.UserRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @SpringJUnitConfig(ApplicationConfig.class) public class TestAroundAdvice { @Autowired private UserRepository userRepository; @Test public void testNull(){ Assertions.assertNotNull(userRepository); } @Test public void testAddUser() throws InterruptedException { userRepository.add("sample_username"); } @Test public void testAddUserFailure() throws InterruptedException { userRepository.add(null); } }
25.137931
72
0.78738
52ddcf190e2b26f57982be7cd59a6cbd1a4eebe3
11,852
package com.paypal.core.nvp; import java.util.HashMap; import java.util.Map; import com.paypal.core.APICallPreHandler; import com.paypal.core.Constants; import com.paypal.core.CredentialManager; import com.paypal.core.credential.CertificateCredential; import com.paypal.core.credential.ICredential; import com.paypal.core.credential.SignatureCredential; import com.paypal.core.credential.ThirdPartyAuthorization; import com.paypal.core.credential.TokenAuthorization; import com.paypal.exception.ClientActionRequiredException; import com.paypal.exception.InvalidCredentialException; import com.paypal.exception.MissingCredentialException; import com.paypal.sdk.exceptions.OAuthException; import com.paypal.sdk.util.UserAgentHeader; /** * <code>PlatformAPICallPreHandler</code> is an implementation of * {@link APICallPreHandler} for NVP based API service * */ public class PlatformAPICallPreHandler implements APICallPreHandler { /** * Service Name */ private final String serviceName; /** * API method */ private final String method; /** * Raw payload from stubs */ private final String rawPayLoad; /** * API Username for authentication */ private String apiUserName; /** * {@link ICredential} for authentication */ private ICredential credential; /** * Access token if any for authorization */ private String accessToken; /** * TokenSecret if any for authorization */ private String tokenSecret; /** * SDK Name used in tracking */ private String sdkName; /** * SDK Version */ private String sdkVersion; /** * PortName to which a particular operation is bound; */ private String portName; /** * Internal variable to hold headers */ private Map<String, String> headers; /** * Map used for to override ConfigManager configurations */ private Map<String, String> configurationMap = null; /** * @deprecated Private Constructor */ private PlatformAPICallPreHandler(String rawPayLoad, String serviceName, String method) { super(); this.rawPayLoad = rawPayLoad; this.serviceName = serviceName; this.method = method; } /** * Private Constructor * * @param rawPayLoad * @param serviceName * @param method * @param configurationMap */ private PlatformAPICallPreHandler(String rawPayLoad, String serviceName, String method, Map<String, String> configurationMap) { super(); this.rawPayLoad = rawPayLoad; this.serviceName = serviceName; this.method = method; this.configurationMap = configurationMap; } /** * PlatformAPICallPreHandler * * @deprecated * @param serviceName * Service Name * @param rawPayLoad * Payload * @param method * API method * @param apiUserName * API Username * @param accessToken * Access Token * @param tokenSecret * Token Secret * @throws MissingCredentialException * @throws InvalidCredentialException */ public PlatformAPICallPreHandler(String rawPayLoad, String serviceName, String method, String apiUserName, String accessToken, String tokenSecret) throws InvalidCredentialException, MissingCredentialException { this(rawPayLoad, serviceName, method); this.apiUserName = apiUserName; this.accessToken = accessToken; this.tokenSecret = tokenSecret; initCredential(); } /** * PlatformAPICallPreHandler * * @deprecated * @param serviceName * Service Name * @param rawPayLoad * Payload * @param method * API method * @param credential * {@link ICredential} instance */ public PlatformAPICallPreHandler(String rawPayLoad, String serviceName, String method, ICredential credential) { this(rawPayLoad, serviceName, method); if (credential == null) { throw new IllegalArgumentException( "Credential is null in PlatformAPICallPreHandler"); } this.credential = credential; } /** * PlatformAPICallPreHandler * * @param serviceName * Service Name * @param rawPayLoad * Payload * @param method * API method * @param credential * {@link ICredential} instance * @param sdkName * SDK Name * @param sdkVersion * sdkVersion * @param portName * Port Name * @param configurationMap */ public PlatformAPICallPreHandler(String rawPayLoad, String serviceName, String method, ICredential credential, String sdkName, String sdkVersion, String portName, Map<String, String> configurationMap) { this(rawPayLoad, serviceName, method, configurationMap); if (credential == null) { throw new IllegalArgumentException( "Credential is null in PlatformAPICallPreHandler"); } this.credential = credential; this.sdkName = sdkName; this.sdkVersion = sdkVersion; this.portName = portName; } /** * PlatformAPICallPreHandler * * @param serviceName * Service Name * @param rawPayLoad * Payload * @param method * API method * @param apiUserName * API Username * @param accessToken * Access Token * @param tokenSecret * Token Secret * @param sdkName * SDK Name * @param sdkVersion * sdkVersion * @param portName * Port Name * @param configurationMap * @throws MissingCredentialException * @throws InvalidCredentialException */ public PlatformAPICallPreHandler(String rawPayLoad, String serviceName, String method, String apiUserName, String accessToken, String tokenSecret, String sdkName, String sdkVersion, String portName, Map<String, String> configurationMap) throws InvalidCredentialException, MissingCredentialException { this(rawPayLoad, serviceName, method, configurationMap); this.apiUserName = apiUserName; this.accessToken = accessToken; this.tokenSecret = tokenSecret; this.sdkName = sdkName; this.sdkVersion = sdkVersion; this.portName = portName; initCredential(); } /** * @return the sdkName */ public String getSdkName() { return sdkName; } /** * @deprecated * @param sdkName * the sdkName to set */ public void setSdkName(String sdkName) { this.sdkName = sdkName; } /** * @return the sdkVersion */ public String getSdkVersion() { return sdkVersion; } /** * @deprecated * @param sdkVersion * the sdkVersion to set */ public void setSdkVersion(String sdkVersion) { this.sdkVersion = sdkVersion; } /** * @return the portName */ public String getPortName() { return portName; } /** * @deprecated * @param portName * the portName to set */ public void setPortName(String portName) { this.portName = portName; } public Map<String, String> getHeaderMap() throws OAuthException { if (headers == null) { headers = new HashMap<String, String>(); if (credential instanceof SignatureCredential) { SignatureHttpHeaderAuthStrategy signatureHttpHeaderAuthStrategy = new SignatureHttpHeaderAuthStrategy( getEndPoint()); headers = signatureHttpHeaderAuthStrategy .generateHeaderStrategy((SignatureCredential) credential); } else if (credential instanceof CertificateCredential) { CertificateHttpHeaderAuthStrategy certificateHttpHeaderAuthStrategy = new CertificateHttpHeaderAuthStrategy( getEndPoint()); headers = certificateHttpHeaderAuthStrategy .generateHeaderStrategy((CertificateCredential) credential); } headers.putAll(getDefaultHttpHeadersNVP()); } return headers; } public String getPayLoad() { // No processing necessary for NVP return the raw payload return rawPayLoad; } public String getEndPoint() { String endPoint = searchEndpoint(); if (endPoint != null) { if (endPoint.endsWith("/")) { endPoint += serviceName + "/" + method; } else { endPoint += "/" + serviceName + "/" + method; } } else if ((Constants.SANDBOX.equalsIgnoreCase(this.configurationMap .get(Constants.MODE).trim()))) { endPoint = Constants.PLATFORM_SANDBOX_ENDPOINT + serviceName + "/" + method; } else if ((Constants.LIVE.equalsIgnoreCase(this.configurationMap.get( Constants.MODE).trim()))) { endPoint = Constants.PLATFORM_LIVE_ENDPOINT + serviceName + "/" + method; } return endPoint; } public ICredential getCredential() { return credential; } public void validate() throws ClientActionRequiredException { String mode = configurationMap.get(Constants.MODE); if (mode == null && searchEndpoint() == null) { // Mandatory Mode not specified. throw new ClientActionRequiredException( "mode[production/live] OR endpoint not specified"); } if ((mode != null) && (!mode.trim().equalsIgnoreCase(Constants.LIVE) && !mode .trim().equalsIgnoreCase(Constants.SANDBOX))) { // Mandatory Mode not specified. throw new ClientActionRequiredException( "mode[production/live] OR endpoint not specified"); } } /* * Search a valid endpoint in the configuration, returning null if not found */ private String searchEndpoint() { String endPoint = this.configurationMap.get(Constants.ENDPOINT + "." + getPortName()) != null ? this.configurationMap .get(Constants.ENDPOINT + "." + getPortName()) : (this.configurationMap.get(Constants.ENDPOINT) != null ? this.configurationMap .get(Constants.ENDPOINT) : null); if (endPoint != null && endPoint.trim().length() <= 0) { endPoint = null; } return endPoint; } private ICredential getCredentials() throws InvalidCredentialException, MissingCredentialException { ICredential returnCredential; CredentialManager credentialManager = new CredentialManager( this.configurationMap); returnCredential = credentialManager.getCredentialObject(apiUserName); if (accessToken != null && accessToken.length() != 0) { ThirdPartyAuthorization tokenAuth = new TokenAuthorization( accessToken, tokenSecret); if (returnCredential instanceof SignatureCredential) { SignatureCredential sigCred = (SignatureCredential) returnCredential; sigCred.setThirdPartyAuthorization(tokenAuth); } else if (returnCredential instanceof CertificateCredential) { CertificateCredential certCred = (CertificateCredential) returnCredential; certCred.setThirdPartyAuthorization(tokenAuth); } } return returnCredential; } private Map<String, String> getDefaultHttpHeadersNVP() { Map<String, String> returnMap = new HashMap<String, String>(); returnMap.put(Constants.PAYPAL_APPLICATION_ID_HEADER, getApplicationId()); returnMap.put(Constants.PAYPAL_REQUEST_DATA_FORMAT_HEADER, Constants.PAYLOAD_FORMAT_NVP); returnMap.put(Constants.PAYPAL_RESPONSE_DATA_FORMAT_HEADER, Constants.PAYLOAD_FORMAT_NVP); returnMap.put(Constants.PAYPAL_REQUEST_SOURCE_HEADER, sdkName + "-" + sdkVersion); // Add user-agent header UserAgentHeader uaHeader = new UserAgentHeader(sdkName, sdkVersion); returnMap.putAll(uaHeader.getHeader()); String sandboxEmailAddress = this.configurationMap .get(Constants.SANDBOX_EMAIL_ADDRESS); if (sandboxEmailAddress != null) { returnMap.put(Constants.PAYPAL_SANDBOX_EMAIL_ADDRESS_HEADER, sandboxEmailAddress); } return returnMap; } private String getApplicationId() { String applicationId = null; if (credential instanceof CertificateCredential) { applicationId = ((CertificateCredential) credential) .getApplicationId(); } else if (credential instanceof SignatureCredential) { applicationId = ((SignatureCredential) credential) .getApplicationId(); } return applicationId; } private void initCredential() throws InvalidCredentialException, MissingCredentialException { if (credential == null) { credential = getCredentials(); } } }
27.371824
112
0.710344
145c5a69fbabde4490d99cb216e28b1d65762399
2,579
package db; import Interfaces.Communicator; import javacard.security.PrivateKey; import javacard.security.PublicKey; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; /** * @author Matti Eisenlohr * @author Egidius Mysliwietz * @author Laura Philipse * @author Alessandra van Veen */ public class ConvertKey implements Communicator { protected KeyFactory factory; short offset; public ConvertKey() { try { factory = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public PrivateKey stringToPrivate(String string) { /*byte[] byte_privkey = Base64.getDecoder().decode(string); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(byte_privkey); try { return factory.generatePrivate(privKeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); return null; }*/ return bytesToPrivkey(fromHexString(string)); } public String privateToString(PrivateKey privkey) { /*byte[] byte_privkey = privkey.getEncoded(); String str_privkey = Base64.getEncoder().encodeToString(byte_privkey); return str_privkey;*/ return toHexString(privkToBytes(privkey)); } public PublicKey stringToPublic(String string) { /*byte[] byte_pubkey = Base64.getDecoder().decode(string); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(byte_pubkey); try { return factory.generatePublic(pubKeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); return null; }*/ return bytesToPubkey(fromHexString(string)); } public String publicToString(PublicKey pubkey) { return toHexString(pubkToBytes(pubkey)); /*byte[] byte_pubkey = pubkey.getEncoded(); String str_pubkey = Base64.getEncoder().encodeToString(byte_pubkey); return str_pubkey;*/ } public String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X ", b)); //Do not remove the space. } return sb.toString(); } public byte[] fromHexString(String str) { String[] str0 = str.split(" "); byte[] b = new byte[str0.length]; for (int i = 0; i < str0.length; i++) { b[i] = (byte) ((short) Short.valueOf(str0[i], 16)); } return b; } }
30.702381
80
0.630865
0e0c6e408899a3a5bef14390a65ad1f60dd4e504
21,907
/******************************************************************************* * Copyright (c) 2009, 2014 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * *******************************************************************************/ package org.eclipse.paho.client.mqttv3.test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Random; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.Matcher; import org.eclipse.paho.client.mqttv3.IMqttClient; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.test.client.MqttClientFactoryPaho; import org.eclipse.paho.client.mqttv3.test.logging.LoggingUtilities; import org.eclipse.paho.client.mqttv3.test.properties.TestProperties; import org.eclipse.paho.client.mqttv3.test.utilities.Utility; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Client test which rapidly tries random combinations of connect, * disconnect, publish and subscribe on a single thread with varying options * (retained, qos etc) and verifies the results. A log is produced * of the history of commands tried which can be fed back into the * test to re-produce a previous run (See run(String filename) */ public class ModelTestCase implements MqttCallback { private static final Class<?> cclass = ModelTestCase.class; private static final String className = cclass.getName(); private static final Logger log = Logger.getLogger(className); private static URI serverURI; private static MqttClientFactoryPaho clientFactory; public static final String LOGDIR = "./"; public static final String CLIENTID = "mqttv3.ModelTestCase"; public String logFilename = null; public File logDirectory = null; public PrintWriter logout = null; public HashMap<String, Integer> subscribedTopics; public Object lock; public ArrayList<MqttMessage> messages; public ArrayList<String> topics; public Random random; public IMqttClient client; public HashMap<String, MqttMessage> retainedPublishes; public HashMap<MqttDeliveryToken, String> currentTokens; public boolean cleanSession; private int numOfIterations = 500; /** * Constructor **/ public ModelTestCase() { logDirectory = new File(LOGDIR); if (logDirectory.exists()) { deleteLogFiles(); logFilename = "mqttv3.ModelTestCase." + System.currentTimeMillis() + ".log"; File logfile = new File(logDirectory, logFilename); try { logout = new PrintWriter(new FileWriter(logfile)); } catch (IOException e) { logout = null; } } } /** * @throws IOException */ private void deleteLogFiles() { log.info("Deleting log files"); File[] files = logDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.matches("mqttv3\\.ModelTestCase\\..*\\.log"); } }); for (File file : files) { boolean isDeleted = file.delete(); if (isDeleted == false) { log.info(" failed to delete: " + file.getAbsolutePath()); file.deleteOnExit(); } } } /** * Test definitions * @throws Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { try { String methodName = Utility.getMethodName(); LoggingUtilities.banner(log, cclass, methodName); serverURI = TestProperties.getServerURI(); clientFactory = new MqttClientFactoryPaho(); clientFactory.open(); } catch (Exception exception) { log.log(Level.SEVERE, "caught exception:", exception); throw exception; } } /** * @throws Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { String methodName = Utility.getMethodName(); LoggingUtilities.banner(log, cclass, methodName); try { if (clientFactory != null) { clientFactory.close(); clientFactory.disconnect(); } } catch (Exception exception) { log.log(Level.SEVERE, "caught exception:", exception); } } /** * @throws Exception */ @Test public void testRunModel() throws Exception { log.info("Test core operations and parameters by random selection"); log.info("See file: " + logFilename + " for details of selected test sequence"); initialise(); try { this.run(numOfIterations); } finally { finish(); } } /** * @param msg */ public void logToFile(String msg) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS"); Date d = new Date(); String tsMsg = df.format(d) + " " + msg; if (logout != null) { logout.println(tsMsg); } else { System.out.println(tsMsg); } } /** * @param e */ public void logToFile(Throwable e) { e.printStackTrace(System.out); if (logout != null) { e.printStackTrace(logout); } } /** * @throws Exception */ public void initialise() throws Exception { random = new Random(); subscribedTopics = new HashMap<String, Integer>(); messages = new ArrayList<MqttMessage>(); topics = new ArrayList<String>(); lock = new Object(); retainedPublishes = new HashMap<String, MqttMessage>(); currentTokens = new HashMap<MqttDeliveryToken, String>(); client = clientFactory.createMqttClient(serverURI, CLIENTID); client.setCallback(this); // Clean any hungover state MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); client.connect(connOpts); client.disconnect(); } /** * @throws Exception */ public void finish() throws Exception { if (logout != null) { logout.flush(); logout.close(); } client.close(); } private final double[] CONNECTED_TABLE = new double[]{0.05, // disconnect 0.2, // subscribe 0.2, // unsubscribe 0.5, // publish 0.05 // pendingDeliveryTokens }; private final double[] DISCONNECTED_TABLE = new double[]{0.5, // connect 0.2, // pendingDeliveryTokens 0.3, // disconnect }; /** * @param table */ private int getOption(double[] table) { double n = random.nextDouble(); double c = 0; for (int i = 0; i < table.length; i++) { c += table[i]; if (c > n) { return i; } } return -1; } /** * @param iterations * @throws Exception */ public void run(int iterations) throws Exception { try { for (int i = 0; i < iterations; i++) { if (client.isConnected()) { int o = getOption(CONNECTED_TABLE); switch (o) { case 0 : disconnect(true); break; case 1 : subscribe(); break; case 2 : unsubscribe(); break; case 3 : publish(); break; case 4 : pendingDeliveryTokens(); break; } } else { int o = getOption(DISCONNECTED_TABLE); switch (o) { case 0 : connect(); break; case 1 : pendingDeliveryTokens(); break; case 2 : disconnect(false); break; } } } } catch (Exception e) { logToFile(e); throw (e); } finally { try { if (client.isConnected()) { client.disconnect(); } client.close(); } catch (Exception e) { // ignore - cleanup for error cases, allow any previous exception to be seen } } } // TODO: /** * @param filename * @throws Exception */ public void run(String filename) throws Exception { /* 26/07/2010 16:28:46.972 connect [cleanSession:false] 26/07/2010 16:28:46.972 disconnect [cleanSession:false][isConnected:true] 26/07/2010 16:28:46.972 subscribe [topic:5f00344b-530a-414a-91e6-57f7d8662b80][qos:2][expectRetained:true] 26/07/2010 16:28:46.972 unsubscribe [topic:0c94dacd-71b0-4692-8b49-4cb225e5f505][existing:false] 26/07/2010 16:28:46.972 publish [topic:5f00344b-530a-414a-91e6-57f7d8662b80][payload:0dbc3ef9-85b3-4cf0-b1f3-e086289d8152][qos:2][retained:true][subscribed:false][waitForCompletion:false] 26/07/2010 16:28:46.972 pendingDeliveryTokens [count:0] */ Pattern pConnect = Pattern.compile("^.*? connect \\[cleanSession:(.+)\\]$"); Pattern pDisconnect = Pattern .compile("^.*? disconnect \\[cleanSession:(.+)\\]\\[isConnected:(.+)\\]$"); Pattern pSubscribe = Pattern .compile("^.*? subscribe \\[topic:(.+)\\]\\[qos:(.+)\\]\\[expectRetained:(.+)\\]$"); Pattern pUnsubscribe = Pattern.compile("^.*? unsubscribe \\[topic:(.+)\\]\\[existing:(.+)\\]$"); Pattern pPublish = Pattern .compile("^.*? publish \\[topic:(.+)\\]\\[payload:(.+)\\]\\[qos:(.+)\\]\\[retained:(.+)\\]\\[subscribed:(.+)\\]\\[waitForCompletion:(.+)\\]$"); Pattern pPendingDeliveryTokens = Pattern.compile("^.*? pendingDeliveryTokens \\[count:(.+)\\]$"); BufferedReader in = new BufferedReader(new FileReader(filename)); String line; try { while ((line = in.readLine()) != null) { Matcher m = pConnect.matcher(line); if (m.matches()) { connect(Boolean.parseBoolean(m.group(1))); } else if ((m = pDisconnect.matcher(line)).matches()) { disconnect(Boolean.parseBoolean(m.group(1)), Boolean.parseBoolean(m.group(2))); } else if ((m = pSubscribe.matcher(line)).matches()) { subscribe(m.group(1), Integer.parseInt(m.group(2)), Boolean.parseBoolean(m.group(3))); } else if ((m = pUnsubscribe.matcher(line)).matches()) { unsubscribe(m.group(1), Boolean.parseBoolean(m.group(2))); } else if ((m = pPublish.matcher(line)).matches()) { publish(m.group(1), m.group(2), Integer.parseInt(m.group(3)), Boolean.parseBoolean(m .group(4)), Boolean.parseBoolean(m.group(5)), Boolean.parseBoolean(m.group(6))); } else if ((m = pPendingDeliveryTokens.matcher(line)).matches()) { pendingDeliveryTokens(Integer.parseInt(m.group(1))); } } } catch (Exception e) { if (client.isConnected()) { client.disconnect(); } throw e; } } /** * @throws Exception */ public void connect() throws Exception { cleanSession = random.nextBoolean(); connect(cleanSession); } /** * Connects the client. * @param cleanSession1 whether to connect clean session. * @throws Exception */ public void connect(boolean cleanSession1) throws Exception { logToFile("connect [cleanSession:" + cleanSession1 + "]"); if (cleanSession1) { subscribedTopics.clear(); } MqttConnectOptions opts = new MqttConnectOptions(); opts.setCleanSession(cleanSession1); client.connect(opts); } /** * @param connected * @throws Exception */ public void disconnect(boolean connected) throws Exception { disconnect(cleanSession, connected); } /** * Disconnects the client * @param cleanSession1 whether this is a clean session being disconnected * @param isConnected whether we think the client is currently connected * @throws Exception */ public void disconnect(boolean cleanSession1, boolean isConnected) throws Exception { logToFile("disconnect [cleanSession:" + cleanSession1 + "][isConnected:" + client.isConnected() + "]"); if (isConnected != client.isConnected()) { throw new Exception("Client state mismatch [expected:" + isConnected + "][actual:" + client.isConnected() + "]"); } if (isConnected && cleanSession1) { subscribedTopics.clear(); } try { client.disconnect(); } catch (MqttException e) { if (((e.getReasonCode() != 6) && (e.getReasonCode() != 32101)) || isConnected) { throw e; } } } /** * @throws Exception */ public void subscribe() throws Exception { String topic; boolean expectRetained; if (!retainedPublishes.isEmpty() && (random.nextInt(5) == 0)) { Object[] topics1 = retainedPublishes.keySet().toArray(); topic = (String) topics1[random.nextInt(topics1.length)]; expectRetained = true; } else { topic = UUID.randomUUID().toString(); expectRetained = false; } int qos = random.nextInt(3); subscribe(topic, qos, expectRetained); } /** * Subscribes to a given topic at the given qos * @param topic the topic to subscribe to * @param qos the qos to subscribe at * @param expectRetained whether a retained message is expected to exist on this topic * @throws Exception */ public void subscribe(String topic, int qos, boolean expectRetained) throws Exception { logToFile("subscribe [topic:" + topic + "][qos:" + qos + "][expectRetained:" + expectRetained + "]"); subscribedTopics.put(topic, new Integer(qos)); client.subscribe(topic, qos); if (expectRetained) { waitForMessage(topic, retainedPublishes.get(topic), true); } } /** * @throws Exception */ public void unsubscribe() throws Exception { String topic; boolean existing = false; if (random.nextBoolean() && (subscribedTopics.size() > 0)) { Object[] topics1 = subscribedTopics.keySet().toArray(); topic = (String) topics1[random.nextInt(topics1.length)]; existing = true; } else { topic = UUID.randomUUID().toString(); } unsubscribe(topic, existing); } /** * Unsubscribes the given topic * @param topic the topic to unsubscribe from * @param existing whether we think we're currently subscribed to the topic * @throws Exception */ public void unsubscribe(String topic, boolean existing) throws Exception { logToFile("unsubscribe [topic:" + topic + "][existing:" + existing + "]"); client.unsubscribe(topic); Object o = subscribedTopics.remove(topic); if (existing == (o == null)) { throw new Exception("Subscription state mismatch [topic:" + topic + "][expected:" + existing + "]"); } } /** * @throws Exception */ public void publish() throws Exception { String topic; boolean subscribed = false; if (random.nextBoolean() && (subscribedTopics.size() > 0)) { Object[] topics1 = subscribedTopics.keySet().toArray(); topic = (String) topics1[random.nextInt(topics1.length)]; subscribed = true; } else { topic = UUID.randomUUID().toString(); } String payload = UUID.randomUUID().toString(); int qos = random.nextInt(3); boolean retained = random.nextInt(3) == 0; // If the message is retained then we should wait for completion. If this isn't done there // is a risk that a subsequent subscriber could be created to receive the message before it // has been fully delivered and hence would not see the retained flag. boolean waitForCompletion = (retained || (random.nextInt(1000) == 1)); publish(topic, payload, qos, retained, subscribed, waitForCompletion); // For QoS0 messages, wait for completion takes no effect as there is no feedback from // the server, and so even though not very deterministic, a small sleep is taken. if (waitForCompletion && retained && (qos == 0)) { Thread.sleep(50); } } /** * Publishes to the given topic * @param topic the topic to publish to * @param payload the payload to publish * @param qos the qos to publish at * @param retained whether to publish retained * @param subscribed whether we think we're currently subscribed to the topic * @param waitForCompletion whether we should wait for the message to complete delivery * @throws Exception */ public void publish(String topic, String payload, int qos, boolean retained, boolean subscribed, boolean waitForCompletion) throws Exception { logToFile("publish [topic:" + topic + "][payload:" + payload + "][qos:" + qos + "][retained:" + retained + "][subscribed:" + subscribed + "][waitForCompletion:" + waitForCompletion + "]"); if (subscribed != subscribedTopics.containsKey(topic)) { throw new Exception("Subscription state mismatch [topic:" + topic + "][expected:" + subscribed + "]"); } MqttMessage msg = new MqttMessage(payload.getBytes()); msg.setQos(qos); msg.setRetained(retained); if (retained) { retainedPublishes.put(topic, msg); } MqttDeliveryToken token = client.getTopic(topic).publish(msg); synchronized (currentTokens) { if (!token.isComplete()) { currentTokens.put(token, "[" + topic + "][" + msg.toString() + "]"); } } if (retained || waitForCompletion) { token.waitForCompletion(); synchronized (currentTokens) { currentTokens.remove(token); } } if (subscribed) { waitForMessage(topic, msg, false); } } /** * @throws Exception */ public void pendingDeliveryTokens() throws Exception { IMqttDeliveryToken[] tokens = client.getPendingDeliveryTokens(); } /** * Checks the pending delivery tokens * @param count the expected number of tokens to be returned * @throws Exception */ public void pendingDeliveryTokens(int count) throws Exception { IMqttDeliveryToken[] tokens = client.getPendingDeliveryTokens(); logToFile("pendingDeliveryTokens [count:" + tokens.length + "]"); if (!client.isConnected() && (tokens.length != count)) { throw new Exception("Unexpected pending tokens [expected:" + count + "][actual:" + tokens.length + "]"); } } /** * @param cause */ public void connectionLost(Throwable cause) { logToFile("Connection Lost:"); logToFile(cause); } /** * @param token */ public void deliveryComplete(IMqttDeliveryToken token) { synchronized (currentTokens) { currentTokens.remove(token); } } /** * Waits for the next message to arrive and checks it's values * @param topic the topic expected * @param message the message expected * @param expectRetained whether the retain flag is expected to be set * @throws Exception */ public void waitForMessage(String topic, MqttMessage message, boolean expectRetained) throws Exception { synchronized (lock) { int count = 0; while (messages.size() == 0 && ++count < 10) { lock.wait(1000); } if (messages.size() == 0) { throw new Exception("message timeout [topic:" + topic + "]"); } String rtopic = topics.remove(0); MqttMessage rmessage = messages.remove(0); if (!rtopic.equals(topic)) { if (rmessage.isRetained() && !expectRetained) { throw new Exception("pre-existing retained message [expectedTopic:" + topic + "][expectedPayload:" + message.toString() + "] [receivedTopic:" + rtopic + "][receivedPayload:" + rmessage.toString() + "]"); } throw new Exception("message topic mismatch [expectedTopic:" + topic + "][expectedPayload:" + message.toString() + "] [receivedTopic:" + rtopic + "][receivedPayload:" + rmessage.toString() + "]"); } if (!rmessage.toString().equals(message.toString())) { if (rmessage.isRetained() && !expectRetained) { throw new Exception("pre-existing retained message [expectedTopic:" + topic + "][expectedPayload:" + message.toString() + "] [receivedTopic:" + rtopic + "][receivedPayload:" + rmessage.toString() + "]"); } throw new Exception("message payload mismatch [expectedTopic:" + topic + "][expectedPayload:" + message.toString() + "] [receivedTopic:" + rtopic + "][receivedPayload:" + rmessage.toString() + "]"); } if (expectRetained && !rmessage.isRetained()) { throw new Exception("message not retained [topic:" + topic + "]"); } else if (!expectRetained && rmessage.isRetained()) { throw new Exception("message retained [topic:" + topic + "]"); } } } /** * @param topic * @param message * @throws Exception */ public void messageArrived(String topic, MqttMessage message) throws Exception { synchronized (lock) { messages.add(message); topics.add(topic); lock.notifyAll(); } } }
31.887918
191
0.620076
14bf87e4550c469e071b9e174706c1b19a4a5ee5
2,460
/* * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eike Stepper - initial API and implementation */ package org.eclipse.emf.cdo.internal.net4j; import org.eclipse.emf.cdo.net4j.CDONet4jSessionConfiguration; import org.eclipse.emf.cdo.net4j.CDONet4jUtil; import org.eclipse.emf.cdo.session.CDOSession; import org.eclipse.emf.internal.cdo.session.CDOSessionFactory; import org.eclipse.net4j.util.container.IManagedContainer; import org.eclipse.net4j.util.container.IPluginContainer; import org.eclipse.net4j.util.security.CredentialsProviderFactory; import org.eclipse.net4j.util.security.IPasswordCredentialsProvider; import org.eclipse.emf.spi.cdo.InternalCDOSession; /** * @author Eike Stepper */ public class Net4jSessionFactory extends CDOSessionFactory { public static final String TYPE = "cdo"; //$NON-NLS-1$ public Net4jSessionFactory() { super(TYPE); } /** * @since 2.0 */ @Override protected InternalCDOSession createSession(String repositoryName, boolean automaticPackageRegistry) { CDONet4jSessionConfiguration configuration = CDONet4jUtil.createNet4jSessionConfiguration(); configuration.setRepositoryName(repositoryName); configuration.getAuthenticator().setCredentialsProvider(getCredentialsProvider()); // The session will be activated by the container configuration.setActivateOnOpen(false); return (InternalCDOSession)configuration.openNet4jSession(); } protected IPasswordCredentialsProvider getCredentialsProvider() { try { IManagedContainer container = getManagedContainer(); String type = getCredentialsProviderType(); return (IPasswordCredentialsProvider)container.getElement(CredentialsProviderFactory.PRODUCT_GROUP, type, null); } catch (Exception ex) { return null; } } protected IManagedContainer getManagedContainer() { return IPluginContainer.INSTANCE; } protected String getCredentialsProviderType() { return "interactive"; } public static CDOSession get(IManagedContainer container, String description) { return (CDOSession)container.getElement(PRODUCT_GROUP, TYPE, description); } }
30
118
0.767886
41c7ddea29f5be28f0cfe23b904410384d5bc1e4
4,343
package tss.tpm; import tss.*; // -----------This is an auto-generated file: do not edit //>>> /** * TPM2_Commit() performs the first part of an ECC anonymous signing operation. The TPM will perform the point multiplications on the provided points and return intermediate signing values. The signHandle parameter shall refer to an ECC key and the signing scheme must be anonymous (TPM_RC_SCHEME). */ public class TPM2_Commit_REQUEST extends TpmStructure { /** * TPM2_Commit() performs the first part of an ECC anonymous signing operation. The TPM will perform the point multiplications on the provided points and return intermediate signing values. The signHandle parameter shall refer to an ECC key and the signing scheme must be anonymous (TPM_RC_SCHEME). * * @param _signHandle handle of the key that will be used in the signing operation Auth Index: 1 Auth Role: USER * @param _P1 a point (M) on the curve used by signHandle * @param _s2 octet array used to derive x-coordinate of a base point * @param _y2 y coordinate of the point associated with s2 */ public TPM2_Commit_REQUEST(TPM_HANDLE _signHandle,TPMS_ECC_POINT _P1,byte[] _s2,byte[] _y2) { signHandle = _signHandle; P1 = _P1; s2 = _s2; y2 = _y2; } /** * TPM2_Commit() performs the first part of an ECC anonymous signing operation. The TPM will perform the point multiplications on the provided points and return intermediate signing values. The signHandle parameter shall refer to an ECC key and the signing scheme must be anonymous (TPM_RC_SCHEME). */ public TPM2_Commit_REQUEST() {}; /** * handle of the key that will be used in the signing operation Auth Index: 1 Auth Role: USER */ public TPM_HANDLE signHandle; /** * size of the remainder of this structure */ // private short P1Size; /** * a point (M) on the curve used by signHandle */ public TPMS_ECC_POINT P1; // private short s2Size; /** * octet array used to derive x-coordinate of a base point */ public byte[] s2; /** * size of buffer */ // private short y2Size; /** * y coordinate of the point associated with s2 */ public byte[] y2; @Override public void toTpm(OutByteBuf buf) { signHandle.toTpm(buf); buf.writeInt((P1!=null)?P1.toTpm().length:0, 2); P1.toTpm(buf); buf.writeInt((s2!=null)?s2.length:0, 2); buf.write(s2); buf.writeInt((y2!=null)?y2.length:0, 2); buf.write(y2); return; } @Override public void initFromTpm(InByteBuf buf) { signHandle = TPM_HANDLE.fromTpm(buf); int _P1Size = buf.readInt(2); buf.structSize.push(buf.new SizedStructInfo(buf.curPos(), _P1Size)); P1 = TPMS_ECC_POINT.fromTpm(buf); buf.structSize.pop(); int _s2Size = buf.readInt(2); s2 = new byte[_s2Size]; buf.readArrayOfInts(s2, 1, _s2Size); int _y2Size = buf.readInt(2); y2 = new byte[_y2Size]; buf.readArrayOfInts(y2, 1, _y2Size); } @Override public byte[] toTpm() { OutByteBuf buf = new OutByteBuf(); toTpm(buf); return buf.getBuf(); } public static TPM2_Commit_REQUEST fromTpm (byte[] x) { TPM2_Commit_REQUEST ret = new TPM2_Commit_REQUEST(); InByteBuf buf = new InByteBuf(x); ret.initFromTpm(buf); if (buf.bytesRemaining()!=0) throw new AssertionError("bytes remaining in buffer after object was de-serialized"); return ret; } public static TPM2_Commit_REQUEST fromTpm (InByteBuf buf) { TPM2_Commit_REQUEST ret = new TPM2_Commit_REQUEST(); ret.initFromTpm(buf); return ret; } @Override public String toString() { TpmStructurePrinter _p = new TpmStructurePrinter("TPM2_Commit_REQUEST"); toStringInternal(_p, 1); _p.endStruct(); return _p.toString(); } @Override public void toStringInternal(TpmStructurePrinter _p, int d) { _p.add(d, "TPM_HANDLE", "signHandle", signHandle); _p.add(d, "TPMS_ECC_POINT", "P1", P1); _p.add(d, "byte", "s2", s2); _p.add(d, "byte", "y2", y2); }; }; //<<<
33.152672
301
0.635045
4c5ad66e013353a7f6810bbfd22599d0ebe64b00
1,905
// Less probability /* Count number of squares in a rectangle Given a m x n rectangle, how many squares are there in it? ${number of squares in matrix.png} Let us first solve this problem for m = n, i.e., for a square: For m = n = 1, output: 1 For m = n = 2, output: 4 + 1 [4 of size 1×1 + 1 of size 2×2] For m = n = 3, output: 9 + 4 + 1 [4 of size 1×1 + 4 of size 2×2 + 1 of size 3×3] For m = n = 4, output 16 + 9 + 4 + 1 [16 of size 1×1 + 9 of size 2×2 + 4 of size 3×3 + 1 of size 4×4] In general, it seems to be n^2 + (n-1)^2 + … 1 = n(n+1)(2n+1)/6 Let us solve this problem when m may not be equal to n: Let us assume that m <= n From above explanation, we know that number of squares in a m x m matrix is m(m+1)(2m+1)/6 What happens when we add a column, i.e., what is the number of squares in m x (m+1) matrix? When we add a column, number of squares increased is m + (m-1) + … + 3 + 2 + 1 [m squares of size 1×1 + (m-1) squares of size 2×2 + … + 1 square of size m x m] Which is equal to m(m+1)/2 So when we add (n-m) columns, total number of squares increased is (n-m)*m(m+1)/2. So total number of squares is m(m+1)(2m+1)/6 + (n-m)*m(m+1)/2. Using same logic we can prove when n <= m. */ // Java program to count squares // in a rectangle of size m x n class countSquares { // Returns count of all squares // in a rectangle of size m x n static int countSquares(int m, int n) { // If n is smaller, swap m and n if (n < m) { // swap(m, n) int temp = m; m = n; n = temp; } // Now n is greater dimension, // apply formula return m * (m + 1) * (2 * m + 1) / 6 + (n - m) * m * (m + 1) / 2; } // Driver Code public static void main(String[] args) { int m = 4, n = 3; System.out.println("Count of squares is " + countSquares(m, n)); } }
26.830986
101
0.573228
42982b9cd7d084b9d441bb6007df71cf114a8d80
2,929
/* * Copyright 2004-2010 the Seasar Foundation and the 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.seasar.aptina.unit; import static org.seasar.aptina.unit.AssertionUtils.assertEquals; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; /** @author koichik */ class IOUtils { private IOUtils() {} public static void closeSilently(final Closeable closeable) { try { closeable.close(); } catch (final IOException ignore) { } } public static String readString(final File file) throws IOException { return new String(readBytes(file)); } public static String readString(final File file, final Charset charset) throws IOException { return new String(readBytes(file), charset); } public static String readString(final File file, final String charsetName) throws IOException { return readString(file, Charset.forName(charsetName)); } public static String readString(final InputStream is) throws IOException { return new String(readBytes(is)); } public static String readString(final InputStream is, final Charset charset) throws IOException { return new String(readBytes(is), charset); } public static String readString(final InputStream is, final String charsetName) throws IOException { return readString(is, Charset.forName(charsetName)); } public static byte[] readBytes(final File file) throws IOException { if (!file.exists()) { throw new FileNotFoundException(file.getPath()); } final FileInputStream is = new FileInputStream(file); try { final FileChannel channel = is.getChannel(); final int size = (int) channel.size(); final ByteBuffer buffer = ByteBuffer.allocate(size); final int readSize = channel.read(buffer); assertEquals(size, readSize); return buffer.array(); } finally { closeSilently(is); } } public static byte[] readBytes(final InputStream is) throws IOException { final int size = is.available(); final byte[] bytes = new byte[size]; int readSize = 0; while (readSize < size) { readSize += is.read(bytes, readSize, size - readSize); } return bytes; } }
31.159574
99
0.717992
f9ed47d9c0158f77ffb6e9e6dcc3216c4c126d94
754
package br.ufcg.ppgcc.compor.ir; public class FontePagadora { private String nome; private String cpfCnpj; private double rendimentoRecebidos; private double impostoPago; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpfCnpj() { return cpfCnpj; } public void setCpfCnpj(String cpfCnpj) { this.cpfCnpj = cpfCnpj; } public double getRendimentoRecebidos() { return rendimentoRecebidos; } public void setRendimentoRecebidos(double rendimentoRecebidos) { this.rendimentoRecebidos = rendimentoRecebidos; } public void setImpostoPago(double impostoPago) { this.impostoPago = impostoPago; } public double getImpostoPago() { return impostoPago; } }
17.534884
65
0.749337
92727c921a6964d4c36247b233ca37ecbf5baffd
4,298
package org.ahocorasick.interval; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class IntervalNode { private enum Direction {LEFT, RIGHT} private IntervalNode left; private IntervalNode right; private int point; private List<Intervalable> intervals = new ArrayList<>(); public IntervalNode(final List<Intervalable> intervals) { this.point = determineMedian(intervals); final List<Intervalable> toLeft = new ArrayList<>(); final List<Intervalable> toRight = new ArrayList<>(); for (Intervalable interval : intervals) { if (interval.getEnd() < this.point) { toLeft.add(interval); } else if (interval.getStart() > this.point) { toRight.add(interval); } else { this.intervals.add(interval); } } if (toLeft.size() > 0) { this.left = new IntervalNode(toLeft); } if (toRight.size() > 0) { this.right = new IntervalNode(toRight); } } public int determineMedian(final List<Intervalable> intervals) { int start = -1; int end = -1; for (Intervalable interval : intervals) { int currentStart = interval.getStart(); int currentEnd = interval.getEnd(); if (start == -1 || currentStart < start) { start = currentStart; } if (end == -1 || currentEnd > end) { end = currentEnd; } } return (start + end) / 2; } public List<Intervalable> findOverlaps(final Intervalable interval) { final List<Intervalable> overlaps = new ArrayList<>(); if (this.point < interval.getStart()) { // Tends to the right addToOverlaps(interval, overlaps, findOverlappingRanges(this.right, interval)); addToOverlaps(interval, overlaps, checkForOverlapsToTheRight(interval)); } else if (this.point > interval.getEnd()) { // Tends to the left addToOverlaps(interval, overlaps, findOverlappingRanges(this.left, interval)); addToOverlaps(interval, overlaps, checkForOverlapsToTheLeft(interval)); } else { // Somewhere in the middle addToOverlaps(interval, overlaps, this.intervals); addToOverlaps(interval, overlaps, findOverlappingRanges(this.left, interval)); addToOverlaps(interval, overlaps, findOverlappingRanges(this.right, interval)); } return overlaps; } protected void addToOverlaps( final Intervalable interval, final List<Intervalable> overlaps, final List<Intervalable> newOverlaps) { for (final Intervalable currentInterval : newOverlaps) { if (!currentInterval.equals(interval)) { overlaps.add(currentInterval); } } } protected List<Intervalable> checkForOverlapsToTheLeft(final Intervalable interval) { return checkForOverlaps(interval, Direction.LEFT); } protected List<Intervalable> checkForOverlapsToTheRight(final Intervalable interval) { return checkForOverlaps(interval, Direction.RIGHT); } protected List<Intervalable> checkForOverlaps( final Intervalable interval, final Direction direction) { final List<Intervalable> overlaps = new ArrayList<>(); for (final Intervalable currentInterval : this.intervals) { switch (direction) { case LEFT: if (currentInterval.getStart() <= interval.getEnd()) { overlaps.add(currentInterval); } break; case RIGHT: if (currentInterval.getEnd() >= interval.getStart()) { overlaps.add(currentInterval); } break; } } return overlaps; } protected List<Intervalable> findOverlappingRanges(IntervalNode node, Intervalable interval) { return node == null ? Collections.<Intervalable>emptyList() : node.findOverlaps(interval); } }
34.66129
98
0.587483
6e088cf3a931bb4a132d95f7ad93d2a355ffb3dc
214
package com.example.mybatis.plus.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.mybatis.plus.demo.model.User2; public interface UserMapper2 extends BaseMapper<User2> { }
23.777778
56
0.817757
7277564fe0323b0739a70b102d436ca922d35cd9
101
package net.cubedserver.webservices.dto; public interface HasValidator { boolean isValid(); }
12.625
40
0.752475
c4bec88582921754847eb104600d2f13ba7c12b1
60,108
package org.seng302.user; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.seng302.exceptions.*; import org.seng302.model.*; import org.seng302.model.enums.BusinessType; import org.seng302.model.enums.Role; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * User test class. */ class UserTests { private static Address address; private static User user; private static Business business; private static Product product; private static InventoryItem inventoryItem; private static Listing listing; @BeforeAll static void before() throws Exception { address = new Address( "3/24", "Ilam Road", "Christchurch", "Canterbury", "New Zealand", "90210", "Ilam" ); user = new User("testfirst", "testlast", "testmiddle", "testnick", "testbiography", "[email protected]", LocalDate.of(2020, 2, 2).minusYears(13), "0271316", address, "Testpassword123!", LocalDateTime.of(LocalDate.of(2021, 2, 2), LocalTime.of(0, 0)), Role.USER); business = new Business( user.getId(), "business name", "some text", address, BusinessType.ACCOMMODATION_AND_FOOD_SERVICES, LocalDateTime.now(), user, "$", "NZD" ); business.setId(1); product = new Product( "PROD", business, "Beans", "Description", "Manufacturer", 20.00, "3274080005003" ); inventoryItem = new InventoryItem( product, product.getProductId(), 4, 6.5, 21.99, null, null, null, LocalDate.of(2022, 1,1) ); listing = new Listing( inventoryItem, 2, 30.00, "more info", LocalDateTime.now(), LocalDateTime.of(2022, 1, 1, 0, 0) ); } /** * Tests that an administrator can be added to a business. * @throws IllegalBusinessArgumentException validation exception * @throws IllegalUserArgumentException validation exception */ @Test void testAddAdministrators() throws IllegalBusinessArgumentException, IllegalUserArgumentException { Business business = new Business( user.getId(), "name", "description", address, BusinessType.RETAIL_TRADE, LocalDateTime.of(LocalDate.of(2021, 2, 2), LocalTime.of(0, 0)), user, "$", "NZD" ); User newUser = new User("NEWUSER", "testlast", "testmiddle", "testnick", "testbiography", "[email protected]", LocalDate.of(2020, 2, 2).minusYears(13), "0999999", address, "Testpassword123!", LocalDateTime.of(LocalDate.of(2021, 2, 2), LocalTime.of(0, 0)), Role.USER); business.addAdministrators(newUser); Assertions.assertEquals(business.getAdministrators(), List.of(user, newUser)); } // ********************************** EMAIL ************************************** /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the length of email address less than the min length. */ @Test void isIllegalUserArgumentExceptionThrownWhenEmailAddressLengthLessThanMinLengthTest() { String email = "z@c"; // min length = 5 try { User user = new User( "first", "last", "middle", "nick", "bio", email, LocalDate.of(2021, Month.JANUARY, 1), "123456789", address, "password", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid email address", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the length of email address greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenEmailAddressLengthGreaterThanMaxLengthTest() { String email = "[email protected]"; // max length = 30 try { User user = new User( "first", "last", "middle", "nick", "bio", email, LocalDate.of(2021, Month.JANUARY, 1), "123456789", address, "password", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid email address", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the email address not containing the @ symbol. */ @Test void isIllegalUserArgumentExceptionThrownWhenEmailAddressDoesNotContainAtSymbolTest() { String email = "zac.gmail.com"; try { User user = new User( "first", "last", "middle", "nick", "bio", email, LocalDate.of(2021, Month.JANUARY, 1), "123456789", address, "password", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid email address", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the email address containing spaces */ @Test void isIllegalUserArgumentExceptionThrownWhenEmailAddressContainsSpacesTest() { String email = "zac [email protected]"; try { User user = new User( "first", "last", "middle", "nick", "bio", email, LocalDate.of(2021, Month.JANUARY, 1), "123456789", address, "password", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid email address", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the email address containing invalid symbols. */ @Test void isIllegalUserArgumentExceptionThrownWhenEmailAddressContainsInvalidSymbolsTest() { String email = "zac#***[email protected]"; try { User user = new User( "first", "last", "middle", "nick", "bio", email, LocalDate.of(2021, Month.JANUARY, 1), "123456789", address, "password", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid email address", e.getMessage()); } } // ********************************* PASSWORD ************************************ /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the length of password less than the min length. */ @Test void isIllegalUserArgumentExceptionThrownWhenPasswordLengthLessThanMinLengthTest() { String password = "1234567"; // min length = 8 try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, password, LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid password", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the length of password greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenPasswordLengthGreaterThanMaxLengthTest() { String string = "1234567"; String password = string.repeat(5); // maxLength = 30 try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, password, LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid password", e.getMessage()); } } /** * Test to see whether a user is successfully created when the password contains all required fields, spaces, * and password length is within the accepted range. */ @Test void isUserSuccessfullyCreatedWhenPasswordContainsRequiredFieldsAndCorrectLengthTest() throws IllegalUserArgumentException { String password = "123ASD!@#as d"; User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, password, LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the password of valid length but not containing an uppercase letter. */ @Test void isIllegalUserArgumentExceptionThrownWhenPasswordHasValidLengthButContainsNoUppercaseLetterTest() { String password = "123!@#asd"; try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, password, LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid password", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the password of valid length but not containing a number. */ @Test void isIllegalUserArgumentExceptionThrownWhenPasswordHasValidLengthButContainsNoNumberTest() { String password = "ASD!@#asd"; try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, password, LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid password", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the password of valid length but not containing a symbol. */ @Test void isIllegalUserArgumentExceptionThrownWhenPasswordHasValidLengthButContainsNoSymbolTest() { String password = "ASD124asd"; try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, password, LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid password", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * the password of valid length but not containing a lower case letter. */ @Test void isIllegalUserArgumentExceptionThrownWhenPasswordHasValidLengthButContainsNoLowercaseLetterTest() { String password = "ASD124#!"; try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, password, LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid password", e.getMessage()); } } /** * Tests that an invalid password with space throws an error. */ @Test void TestInvalidPasswordSpace() { try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, " ", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid password", e.getMessage()); } } // ******************************** FIRST NAME *********************************** /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * first name (a required field) empty. */ @Test void isIllegalUserArgumentExceptionThrownWhenFirstNameEmptyTest() { String firstName = ""; try { User user = new User( firstName, "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid first name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * first name greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenFirstNameLengthGreaterThanMaxLengthTest() { String string = "A"; String firstName = string.repeat(256); // max length = 255; try { User user = new User( firstName, "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid first name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * first name valid, but first name contains invalid symbols. */ @Test void isIllegalUserArgumentExceptionThrownWhenFirstNameHasValidLengthButContainsInvalidSymbolsTest() { String firstName = "Zac!@#"; try { User user = new User( firstName, "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid first name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * first name valid, but first name contains numbers. */ @Test void isIllegalUserArgumentExceptionThrownWhenFirstNameHasValidLengthButContainsNumbersTest() { String firstName = "Zac123"; try { User user = new User( firstName, "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid first name", e.getMessage()); } } /** * Test to see whether a user is successfully created when first name contains valid symbols, diacritics and spaces. */ @Test void isUserSuccessfullyCreatedWhenFirstNameContainsValidSymbolsDiacriticsAndSpacesTest() throws IllegalUserArgumentException { String firstName = "Za-c'bd āâĕ"; User user = new User( firstName, "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(firstName, user.getFirstName()); } // ******************************* PHONE NUMBER ********************************** /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * phone number greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenPhoneNumberLengthGreaterThanMaxLengthTest() { String phoneNumber = "123 456 789 102 345"; // max length = 15 try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), phoneNumber, address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid phone number", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with phone number * having invalid syntax. */ @Test void isIllegalUserArgumentExceptionThrownWhenPhoneNumberHasInvalidSyntax() { String phoneNumber = "111-222-333%!@#"; try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), phoneNumber, address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid phone number", e.getMessage()); } } /** * Test to see whether a user is successfully created when phone number has valid syntax and length equals max * length. */ @Test void isUserSuccessfullyCreatedWhenPhoneNumberHasValidSyntaxAndLengthEqualsMaxLengthTest() throws IllegalUserArgumentException { String phoneNumber = "+64 32 555 0129"; // maxLength = 15 User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), phoneNumber, address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(phoneNumber, user.getPhoneNumber()); } // ******************************* DATE OF BIRTH ********************************* /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user when date of birth * means user is younger than the min age of 13. */ @Test void isIllegalUserArgumentExceptionThrownWhenUserIsYoungerThanThirteenTest() { try { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.now(), "+64 32 555 0129", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid date of birth", e.getMessage()); } } /** * Test to see whether a user is successfully created when date of birth means that user is older than the min age * of 13. */ @Test void isUserSuccessfullyCreatedWhenUserIsOlderThanThirteenTest() throws IllegalUserArgumentException { LocalDate birthDate = LocalDate.of(2000, Month.JANUARY, 1); User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", birthDate, "+64 32 555 0129", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(birthDate, user.getDateOfBirth()); } /** * Test to see whether a user is successfully created when date of birth means that user is the min age * of 13. */ @Test void isUserSuccessfullyCreatedWhenUserAgeIsMinAgeOfThirteen() throws IllegalUserArgumentException { LocalDate birthDate = LocalDate.now().minusYears(13); // min age = 13 User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", birthDate, "+64 32 555 0129", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(birthDate, user.getDateOfBirth()); } // ********************************* LAST NAME *********************************** /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with * last name (a required field) empty. */ @Test void isIllegalUserArgumentExceptionThrownWhenLastNameEmptyTest() { String lastName = ""; try { User user = new User( "first", lastName, "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid last name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * last name greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenLastNameLengthGreaterThanMaxLengthTest() { String string = "A"; String lastName = string.repeat(256); // max length = 255; try { User user = new User( "first", lastName, "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid last name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * last name valid, but last name contains invalid symbols. */ @Test void isIllegalUserArgumentExceptionThrownWhenLastNameHasValidLengthButContainsInvalidSymbolsTest() { String lastName = "Kay!@#"; try { User user = new User( "first", lastName, "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid last name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * last name valid, but last name contains numbers. */ @Test void isIllegalUserArgumentExceptionThrownWhenLastNameHasValidLengthButContainsNumbersTest() { String lastName = "Kay123"; try { User user = new User( "first", lastName, "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid last name", e.getMessage()); } } /** * Test to see whether a user is successfully created when last name contains valid symbols, diacritics and spaces. */ @Test void isUserSuccessfullyCreatedWhenLastNameContainsValidSymbolsDiacriticsAndSpacesTest() throws IllegalUserArgumentException { String lastName = "Ka-y'bd āâĕ"; User user = new User( "first", lastName, "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(lastName, user.getLastName()); } // *********************************** BIO *************************************** /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * bio greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenBioLengthGreaterThanMaxLengthTest() { String string = "Z"; String bio = string.repeat(601); // max length = 600 try { User user = new User( "first", "last", "middle", "nick", bio, "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid bio", e.getMessage()); } } /** * Test to see whether a user is successfully created when bio has valid length and contains symbols, numbers etc. */ @Test void isUserSuccessfullyCreatedWhenBioContainsSymbolsAndNumbersTest() throws IllegalUserArgumentException { String bio = "Hello my name is Euan1234. My email is [email protected]." + "Hello!!!! #$%&&**"; User user = new User( "first", "last", "middle", "nick", bio, "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(bio, user.getBio()); } // ******************************** MIDDLE NAME ********************************** /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * middle name greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenMiddleNameLengthGreaterThanMaxLengthTest() { String string = "F"; String middleName = string.repeat(256); // max length = 255; try { User user = new User( "first", "last", middleName, "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid middle name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * middle name valid, but middle name contains invalid symbols. */ @Test void isIllegalUserArgumentExceptionThrownWhenMiddleNameHasValidLengthButContainsInvalidSymbolsTest() { String middleName = "Cam!@#"; try { User user = new User( "first", "last", middleName, "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid middle name", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * middle name valid, but middle name contains numbers. */ @Test void isIllegalUserArgumentExceptionThrownWhenMiddleNameHasValidLengthButContainsNumbersTest() { String middleName = "Cam123"; try { User user = new User( "first", "last", middleName, "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid middle name", e.getMessage()); } } /** * Test to see whether a user is successfully created when middle name contains valid symbols, diacritics and spaces. */ @Test void isUserSuccessfullyCreatedWhenMiddleNameContainsValidSymbolsDiacriticsAndSpacesTest() throws IllegalUserArgumentException { String middleName = "Ca-m'bd āâĕ"; User user = new User( "first", "last", middleName, "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(middleName, user.getMiddleName()); } // ********************************* NICKNAME ************************************ /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * nick name greater than the max length. */ @Test void isIllegalUserArgumentExceptionThrownWhenNickNameLengthGreaterThanMaxLengthTest() { String string = "P"; String nickName = string.repeat(256); // max length = 255; try { User user = new User( "first", "last", "middle", nickName, "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid nickname", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * nick name valid, but nick name contains invalid symbols. */ @Test void isIllegalUserArgumentExceptionThrownWhenNickNameHasValidLengthButContainsInvalidSymbolsTest() { String nickName = "Peps!@#"; try { User user = new User( "first", "last", "middle", nickName, "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid nickname", e.getMessage()); } } /** * Test to see whether an IllegalUserArgumentException is thrown when trying to create a user with the length of * nick name valid, but nick name contains numbers. */ @Test void isIllegalUserArgumentExceptionThrownWhenNickNameHasValidLengthButContainsNumbersTest() { String nickName = "Peps123"; try { User user = new User( "first", "last", "middle", nickName, "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); } catch (IllegalUserArgumentException e) { Assertions.assertEquals("Invalid nickname", e.getMessage()); } } /** * Test to see whether a user is successfully created when nick name contains valid symbols, diacritics and spaces. */ @Test void isUserSuccessfullyCreatedWhenNickNameContainsValidSymbolsDiacriticsAndSpacesTest() throws IllegalUserArgumentException { String nickName = "Pep-s'bd āâĕ"; User user = new User( "first", "last", "middle", nickName, "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Qwerty123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNotNull(user); Assertions.assertEquals(nickName, user.getNickname()); } // ******************************* ************ ********************************** /** * Tests that the optional fields (middle name, nickname, bio and phone number) are set to null when empty. */ @Test void TestOptionalFields() throws IllegalUserArgumentException { User user = new User( "first", "last", "", "", "", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "", address, "Password123!", LocalDateTime.of(LocalDate.of(2021, Month.JANUARY, 1), LocalTime.of(0, 0)), Role.USER ); Assertions.assertNull(user.getNickname()); Assertions.assertNull(user.getBio()); Assertions.assertNull(user.getMiddleName()); Assertions.assertNull(user.getPhoneNumber()); } /** * Checks to see if the message only contains months when * the user has been registered for less than a year. */ @Test void testMonthsSinceRegistration() throws IllegalUserArgumentException { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Password123!", LocalDateTime.now().minusMonths(2), Role.USER ); Assertions.assertEquals("2 Month(s)\n", user.getTimeSinceRegistration()); } /** * Checks to see if the message contains both years and months when * the user has been registered for more than a year. */ @Test void testYearsSinceRegistration() throws IllegalUserArgumentException { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Password123!", LocalDateTime.now().minusYears(1).minusMonths(2), Role.USER ); Assertions.assertEquals("1 Year(s) and 2 Month(s)\n", user.getTimeSinceRegistration()); } /** * Checks to see if the months are rounded down to the nearest month. */ @Test void testMonthsRounded() throws IllegalUserArgumentException { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Password123!", LocalDateTime.now().minusMonths(1).minusDays(10), Role.USER ); Assertions.assertEquals("1 Month(s)\n", user.getTimeSinceRegistration()); } /** * Checks to see the password has been hashed when create new User object */ @Test void testEncode() throws IllegalUserArgumentException { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Password123!", LocalDateTime.now().minusMonths(1).minusDays(10), Role.USER ); Assertions.assertEquals("UGFzc3dvcmQxMjMh", user.getPassword()); } /** * Checks to see the password has been hashed when create new User object */ @Test void testVerifyPassword() throws IllegalUserArgumentException { User user = new User( "first", "last", "middle", "nick", "bio", "[email protected]", LocalDate.of(2021, Month.JANUARY, 1).minusYears(13), "123456789", address, "Password123!", LocalDateTime.now().minusMonths(1).minusDays(10), Role.USER ); Assertions.assertTrue(user.verifyPassword("Password123!")); } /** * Test to see whether the getBusinessesAdministered method returns a list of * ids' (integers) of the businesses administered by that user. * @throws IllegalBusinessArgumentException validation exception for a business. */ @Test void testGetBusinessesAdministered() throws IllegalBusinessArgumentException { Business business = new Business( user.getId(), "name", "description", address, BusinessType.RETAIL_TRADE, LocalDateTime.of(LocalDate.of(2021, 2, 2), LocalTime.of(0, 0)), user, "$", "NZD" ); business.addAdministrators(user); Assertions.assertEquals(user, business.getAdministrators().get(0)); } /** * Test to see whether the addAListingToBookmark function can successfully add new listing to bookmark */ @Test void testANewListingSuccessfullyBeenAddToBookmark() { // Given user.setBookmarkedListings(new ArrayList<>()); // When user.addAListingToBookmark(listing); // Then Assertions.assertEquals(1, user.getBookmarkedListing().size()); Assertions.assertEquals(listing, user.getBookmarkedListing().get(0)); } /** * Test to see whether the addAListingToBookmark function will not add exist listing again to bookmark */ @Test void testAExistListingNotBeenAddToBookmarkAgain() { // Given user.setBookmarkedListings(new ArrayList<>()); user.addAListingToBookmark(listing); Assertions.assertEquals(1, user.getBookmarkedListing().size()); Assertions.assertEquals(listing, user.getBookmarkedListing().get(0)); // When user.addAListingToBookmark(listing); // Then Assertions.assertEquals(1, user.getBookmarkedListing().size()); } /** * Test to see whether the removeAListingToBookmark function will successfully remove given listing if its exist. */ @Test void testAExistListingSuccessfullyBeenRemoveFromBookmark() { // Given user.setBookmarkedListings(new ArrayList<>()); user.addAListingToBookmark(listing); Assertions.assertEquals(1, user.getBookmarkedListing().size()); Assertions.assertEquals(listing, user.getBookmarkedListing().get(0)); // When user.removeAListingFromBookmark(listing); // Then Assertions.assertTrue(user.getBookmarkedListing().isEmpty()); } /** * Test that a IllegalUserArgumentException been catch If new first name invalid. */ @Test void testAnExceptionBeenThrowIfFirstNameInvalid() { // Given String firstName = ""; String errorMessage = ""; // When try { user.updateFirstName(firstName); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid first name", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new last name invalid. */ @Test void testAnExceptionBeenThrowIfLastNameInvalid() { // Given String lastName = ""; String errorMessage = ""; // When try { user.updateLastName(lastName); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid last name", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new middle name invalid. */ @Test void testAnExceptionBeenThrowIfMiddleNameInvalid() { // Given String middleName = "This is a Invalid middle name".repeat(10); String errorMessage = ""; // When try { user.updateMiddleName(middleName); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid middle name", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new nickname invalid. */ @Test void testAnExceptionBeenThrowIfNicknameInvalid() { // Given String nickname = "This is a Invalid nickname".repeat(10); String errorMessage = ""; // When try { user.updateNickname(nickname); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid nickname", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new bio invalid. */ @Test void testAnExceptionBeenThrowIfBioInvalid() { // Given String bio = "This is a Invalid bio".repeat(100); String errorMessage = ""; // When try { user.updateBio(bio); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid bio", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new email invalid. */ @Test void testAnExceptionBeenThrowIfEmailInvalid() { // Given String email = "abc.abc"; String errorMessage = ""; // When try { user.updateEmail(email); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid email address", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new date of birth invalid. */ @Test void testAnExceptionBeenThrowIfDateOfBirthInvalid() { // Given LocalDate dateOfBirth = LocalDate.now(); String errorMessage = ""; // When try { user.updateDateOfBirth(dateOfBirth); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid date of birth", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new phone number invalid. */ @Test void testAnExceptionBeenThrowIfPhoneNameInvalid() { // Given String phoneNumber = "aa"; String errorMessage = ""; // When try { user.updatePhoneNumber(phoneNumber); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid phone number", errorMessage); } /** * Test that a IllegalUserArgumentException been catch If new password invalid. */ @Test void testAnExceptionBeenThrowIfPasswordInvalid() { // Given String password = ""; String errorMessage = ""; // When try { user.updatePassword(password); } catch (IllegalUserArgumentException e) { errorMessage = e.getMessage(); } // Then Assertions.assertEquals("Invalid password", errorMessage); } // ********************************* useAttempt() method tests ************************************ /** * Test that remainingLoginAttempts is reduced by 1 attempt when the current remainingLoginAttempts is greater than * 0 when useAttempt is called */ @Test void testUseAttempt_AttemptsReducedByOneWhenAttemptsGreaterThanOne() { int attempts = 2; int expectedAttempts = 1; user.setRemainingLoginAttempts(attempts); user.useAttempt(); Assertions.assertEquals(expectedAttempts, user.getRemainingLoginAttempts()); } /** * Test that remainingLoginAttempts is not reduced when the current remainingLoginAttempts is 0 * when useAttempt is called */ @Test void testUseAttempt_AttemptsReducedByOneWhenAttemptsNoAttemptsRemaining() { int attempts = 0; int expectedAttempts = 0; user.setRemainingLoginAttempts(attempts); user.useAttempt(); Assertions.assertEquals(expectedAttempts, user.getRemainingLoginAttempts()); } /** * Test that remainingLoginAttempts is not reduced when the current remainingLoginAttempts is negative * when useAttempt is called */ @Test void testUseAttempt_AttemptsReducedByOneWhenAttemptsNegativeAttemptsRemaining() { int attempts = -10; int expectedAttempts = 0; user.setRemainingLoginAttempts(attempts); user.useAttempt(); Assertions.assertEquals(expectedAttempts, user.getRemainingLoginAttempts()); } // ********************************* hasLoginAttemptsRemaining() method tests ************************************ /** * Test that hasLoginAttemptsRemaining returns true when there is at least one remaining login attempt * available. */ @Test void testHasLoginAttemptsRemaining_AtLeastOneAttemptRemaining_ReturnsTrue() { user.setRemainingLoginAttempts(1); Assertions.assertTrue(user.hasLoginAttemptsRemaining()); } /** * Test that hasLoginAttemptsRemaining returns true when there are no remaining login attempts * available. */ @Test void testHasLoginAttemptsRemaining_NoAttemptsRemaining_ReturnsFalse() { user.setRemainingLoginAttempts(0); Assertions.assertFalse(user.hasLoginAttemptsRemaining()); } // ********************************* isLocked() method tests ************************************ /** * Test that isLocked returns false when the account is not locked. */ @Test void testIsLocked_NotLocked_ReturnsFalse() { user.setTimeWhenUnlocked(null); Assertions.assertFalse(user.isLocked()); } /** * Test that isLocked returns true when the account is locked. */ @Test void testIsLocked_Locked_ReturnsTrue() { user.setTimeWhenUnlocked(LocalDateTime.now().plusMinutes(29)); Assertions.assertTrue(user.isLocked()); } // ********************************* canUnlock() method tests ************************************ /** * Test that canUnlock returns true when the 1 hour since locking the account has passed. */ @Test void testCanUnlock_HourPassed_ReturnsTrue() { user.setTimeWhenUnlocked(LocalDateTime.now().minusHours(2)); Assertions.assertTrue(user.canUnlock()); } /** * Test that canUnlock returns false when the 1 hour since locking the account has not passed yet. */ @Test void testCanUnlock_HourNotPassed_ReturnsFalse() { user.setTimeWhenUnlocked(LocalDateTime.now().plusMinutes(38)); Assertions.assertFalse(user.canUnlock()); } // ********************************* lockAccount() method tests ************************************ /** * Test that lockAccount locks the account for 1 hour. */ @Test void testLockAccount_LocksForOneHour() { user.lockAccount(); LocalDateTime lockedTime = LocalDateTime.now(); LocalDateTime whenLocked = lockedTime.truncatedTo(ChronoUnit.MINUTES); LocalDateTime whenUnlocked = user.getTimeWhenUnlocked().truncatedTo(ChronoUnit.MINUTES); assertThat(user.isLocked()).isTrue(); assertThat(whenUnlocked).isEqualTo(whenLocked.plusHours(1)); } // ********************************* unlockAccount() method tests ************************************ /** * Test that unlockAccount sets timeWhenUnlocked to null. */ @Test void testUnlockAccount_TimeWhenUnlockedSetToNull() { user.unlockAccount(); Assertions.assertEquals(null, user.getTimeWhenUnlocked()); } /** * Test that unlockAccount sets remainingLoginAttempts to three. */ @Test void testUnlockAccount_SetsRemainingLoginAttemptsToThree() { user.unlockAccount(); Assertions.assertEquals(3, user.getRemainingLoginAttempts()); } }
34.132879
131
0.5187
9b1d3010d1753a5a0ab4dd877d07abf8b1827347
3,126
package net.openid.conformance.condition.client; import com.google.gson.JsonObject; import net.openid.conformance.condition.Condition; import net.openid.conformance.condition.ConditionError; import net.openid.conformance.logging.TestInstanceEventLog; import net.openid.conformance.testmodule.Environment; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ValidateIdTokenACRClaimAgainstAcrValuesRequest_UnitTest { @Spy private Environment env = new Environment(); @Mock private TestInstanceEventLog eventLog; private ValidateIdTokenACRClaimAgainstAcrValuesRequest cond; @Before public void setUp() throws Exception { cond = new ValidateIdTokenACRClaimAgainstAcrValuesRequest(); cond.setProperties("UNIT-TEST", eventLog, Condition.ConditionResult.INFO); } @Test public void testEvaluate_caseGood() { JsonObject req = new JsonObject(); req.addProperty("acr_values", "1 2"); env.putObject("authorization_endpoint_request", req); JsonObject id_token_claims = new JsonObject(); id_token_claims.addProperty("acr", "2"); JsonObject id_token = new JsonObject(); id_token.add("claims", id_token_claims); env.putObject("id_token", id_token); cond.execute(env); } @Test public void testEvaluate_caseGoodOne() { JsonObject req = new JsonObject(); req.addProperty("acr_values", "1"); env.putObject("authorization_endpoint_request", req); JsonObject id_token_claims = new JsonObject(); id_token_claims.addProperty("acr", "1"); JsonObject id_token = new JsonObject(); id_token.add("claims", id_token_claims); env.putObject("id_token", id_token); cond.execute(env); } @Test(expected = ConditionError.class) public void testEvaluate_badNotMatching() { JsonObject req = new JsonObject(); req.addProperty("acr_values", "1 2"); env.putObject("authorization_endpoint_request", req); JsonObject id_token_claims = new JsonObject(); id_token_claims.addProperty("acr", "3"); JsonObject id_token = new JsonObject(); id_token.add("claims", id_token_claims); env.putObject("id_token", id_token); cond.execute(env); } @Test(expected = ConditionError.class) public void testEvaluate_badMissing() { JsonObject req = new JsonObject(); req.addProperty("acr_values", "1 2"); env.putObject("authorization_endpoint_request", req); JsonObject id_token_claims = new JsonObject(); JsonObject id_token = new JsonObject(); id_token.add("claims", id_token_claims); env.putObject("id_token", id_token); cond.execute(env); } @Test(expected = ConditionError.class) public void testEvaluate_badNotAString() { JsonObject req = new JsonObject(); req.addProperty("acr_values", "1 2"); env.putObject("authorization_endpoint_request", req); JsonObject id_token_claims = new JsonObject(); id_token_claims.addProperty("acr", 3); JsonObject id_token = new JsonObject(); id_token.add("claims", id_token_claims); env.putObject("id_token", id_token); cond.execute(env); } }
29.214953
76
0.760717
1f53a76b14a6e0c501cfc0e611e79a09e8509ce5
1,857
package com.ttnn.business.wm.controller.zk; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.ttnn.business.wm.service.WMSS01Service; import com.ttnn.framework.support.CSPVOSupport; import com.ttnn.framework.support.impl.MyControllerSupportImpl; import com.ttnn.framework.support.impl.MyServiceSupportImpl; @Controller @RequestMapping("WMZKGGJS") /** 首页*/ public class WMZKGGJSController extends MyControllerSupportImpl { @Resource protected WMSS01Service WMSS01Service_;//系统扩展信息 @Override public MyServiceSupportImpl getService(){ return WMSS01Service_; } @Override public Logger getLogger(){ return LoggerFactory.getLogger(WMZKGGJSController.class); } @Override public ModelAndView getModelAndView(){ return new ModelAndView("/WM/ZK/WMKZ"); } @Override @RequestMapping(value = "/H.go", method = RequestMethod.POST) public ModelAndView home(CSPVOSupport paramBean) { ModelAndView pageMAV = getModelAndView(); getLogger().debug("paramBean===>>>" + paramBean); pageMAV.addObject("paramBean", paramBean); pageMAV.setViewName("WM/ZK/WMKZ"); getLogger().debug("pageMAV===>>>" + pageMAV); return pageMAV; } @Override @RequestMapping(value = "/F.go" ) public ModelAndView doFindList(CSPVOSupport paramBean) { ModelAndView pageMAV = getModelAndView(); getLogger().debug("paramBean===>>>" + paramBean); pageMAV.addObject("paramBean", paramBean); pageMAV.setViewName("WM/ZK/WMJGF1L"); getLogger().debug("pageMAV===>>>" + pageMAV); return pageMAV; } }
30.442623
65
0.739365
40cbfc95dbe1bfc27196db8a2abb8a1cdedf3b2d
3,606
package primal.bukkit.nms; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.netty.channel.Channel; import org.bukkit.entity.Player; import primal.bukkit.plugin.PrimalPlugin; import primal.lang.collection.GMap; public abstract class CatalystPacketListener implements PacketListener { private TinyProtocol protocol; protected GMap<String, String> teamCache; private final Map<Class<?>, List<PacketHandler<?>>> inHandlers = new HashMap<>(); private final Map<Class<?>, List<PacketHandler<?>>> outHandlers = new HashMap<>(); private final List<PacketHandler<?>> inGlobal = new ArrayList<>(); private final List<PacketHandler<?>> outGlobal = new ArrayList<>(); public CatalystPacketListener() { teamCache = new GMap<>(); PacketCache.reset(); } @Override public void openListener() { if(protocol != null) { throw new RuntimeException("Listener is already open"); } try { protocol = new TinyProtocol(PrimalPlugin.instance) { @Override public Object onPacketOutAsync(Player reciever, Channel channel, Object packet) { Object p = packet; for(PacketHandler<?> i : outGlobal) { p = i.onPacket(reciever, p); if(p == null) { break; } } if(p != null && outHandlers.containsKey(packet.getClass())) { for(PacketHandler<?> i : outHandlers.get(packet.getClass())) { p = i.onPacket(reciever, p); if(p == null) { break; } } } return p; } @Override public Object onPacketInAsync(Player sender, Channel channel, Object packet) { Object p = packet; for(PacketHandler<?> i : inGlobal) { p = i.onPacket(sender, p); if(p == null) { break; } } if(p != null && inHandlers.containsKey(packet.getClass())) { for(PacketHandler<?> i : inHandlers.get(packet.getClass())) { p = i.onPacket(sender, p); if(p == null) { break; } } } return p; } }; } catch(Throwable e) { // Derp } onOpened(); } @Override public void closeListener() { if(protocol == null) { // Nobody cares return; } try { protocol.close(); } catch(Throwable e) { // Nobody cares } inHandlers.clear(); outHandlers.clear(); inGlobal.clear(); outGlobal.clear(); protocol = null; } @Override public <T> void addOutgoingListener(Class<? extends T> packetType, PacketHandler<T> handler) { if(!outHandlers.containsKey(packetType)) { outHandlers.put(packetType, new ArrayList<PacketHandler<?>>()); } outHandlers.get(packetType).add(handler); } @Override public void addGlobalOutgoingListener(PacketHandler<?> handler) { outGlobal.add(handler); } @Override public <T> void addIncomingListener(Class<? extends T> packetType, PacketHandler<T> handler) { if(!inHandlers.containsKey(packetType)) { inHandlers.put(packetType, new ArrayList<PacketHandler<?>>()); } inHandlers.get(packetType).add(handler); } @Override public void addGlobalIncomingListener(PacketHandler<?> handler) { inGlobal.add(handler); } @Override public void removeOutgoingPacketListeners(Class<?> c) { outHandlers.remove(c); } @Override public void removeOutgoingPacketListeners() { outHandlers.clear(); } @Override public void removeIncomingPacketListeners(Class<?> c) { inHandlers.remove(c); } @Override public void removeIncomingPacketListeners() { inHandlers.clear(); } }
18.304569
93
0.641986
5406eaa8a02da26a0d798b03280448ec1e5b69a9
4,206
package com.simcoder.bimbo.Admin; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.FirebaseException; import com.google.firebase.auth.PhoneAuthCredential; import com.google.firebase.auth.PhoneAuthProvider; import com.simcoder.bimbo.R; import java.net.Inet4Address; import java.util.concurrent.TimeUnit; public class AdminSendVerificationCodeActivity extends AppCompatActivity { String role; Intent roleintent; Intent traderIDintent; String traderID; Intent verifyintent; public AdminSendVerificationCodeActivity() { super(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { EditText inputCode1, inputCode2, inputCode3, inputCode4, inputCode5, inputCode6; final ProgressBar progressBar = findViewById(R.id.progressBar); super.onCreate(savedInstanceState); setContentView(R.layout.verificodesend); Intent roleintent = getIntent(); if (roleintent.getExtras().getString("role") != null) { role = roleintent.getExtras().getString("role"); } Intent traderIDintent = getIntent(); if (traderIDintent.getExtras().getString("traderID") != null) { traderID = traderIDintent.getExtras().getString("traderID"); } final EditText inputMobile = findViewById(R.id.inputMobile); final Button getcode = findViewById(R.id.getverificationcode); getcode.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if (inputMobile.getText().toString().trim().isEmpty()){ Toast.makeText(AdminSendVerificationCodeActivity.this, "Enter Mobile", Toast.LENGTH_SHORT).show(); return; } progressBar.setVisibility(View.VISIBLE); getcode.setVisibility(View.INVISIBLE); PhoneAuthProvider.getInstance().verifyPhoneNumber("+233" + inputMobile.getText().toString(), 60, TimeUnit.SECONDS,AdminSendVerificationCodeActivity.this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) { progressBar.setVisibility(View.GONE); getcode.setVisibility(View.VISIBLE); } @Override public void onVerificationFailed(@NonNull FirebaseException e) { progressBar.setVisibility(View.GONE); getcode.setVisibility(View.VISIBLE); Toast.makeText(AdminSendVerificationCodeActivity.this, "e.getMessage", Toast.LENGTH_SHORT).show(); } @Override public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) { super.onCodeSent(verificationId, forceResendingToken); progressBar.setVisibility(View.GONE); getcode.setVisibility(View.VISIBLE); Intent codeintent = new Intent(getApplicationContext(), AdminSendVerificationCodeActivity.class); codeintent.putExtra("mobile", inputMobile.getText().toString()); codeintent.putExtra("verificationId", verificationId); startActivity( codeintent); } }); } }); /* verifyintent = new Intent(getApplicationContext(), VerifyVerificationCodeActivity.class); verifyintent.putExtra("mobile", inputMobile.getText().toString() ); verifyintent.putExtra("verificationId", verificationId); startActivity(verifyintent); */ } }
37.891892
231
0.647884
89b715e7b520281bb7e64249a7c76cc7f4346aea
8,477
package com.example.uploadingfiles; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.Queue; import java.util.stream.Collectors; import com.example.uploadingfiles.fileParsing.DataObject; import com.example.uploadingfiles.fileParsing.ExpectedResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.example.uploadingfiles.fileParsing.FileParser; import com.example.uploadingfiles.fileParsing.Parameter; import com.example.uploadingfiles.storage.StorageFileNotFoundException; import com.example.uploadingfiles.storage.StorageService; //This file was imported using spring boot. We did not create this file, but simply modified it to fit our needs //link to the source: https://spring.io/guides/gs/uploading-files/ //This class is used to decide routes for the API to take. @Controller public class FileUploadController { private final StorageService storageService; private final FileParser fileParser; // add this instance variable in order to use our custom methods // update the constructor to use our instance variable @Autowired public FileUploadController(StorageService storageService, FileParser fileParser) { this.storageService = storageService; this.fileParser = fileParser; } // This code remained unchanged. It is used to render our view when the page is // loaded. @GetMapping("/") public String listUploadedFiles(Model model) throws IOException { model.addAttribute("files", storageService.loadAll() .map(path -> MvcUriComponentsBuilder .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString()) .build().toUri().toString()) .collect(Collectors.toList())); return "uploadForm"; } // This code remained unchanged. This is to get a specific file resource stored // in the upload-dir folder. @GetMapping("/files/{filename:.+}") @ResponseBody public ResponseEntity<Resource> serveFile(@PathVariable String filename) { Resource file = storageService.loadAsResource(filename); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"") .body(file); } public void processFile(MultipartFile file, String fileNameNoExt) throws Exception { // store the json file in order to use it later storageService.store(file); // create the File object inside the upload-dir location. Create the // BufferedWriter to write to the File File outputFile = new File("upload-dir/" + fileNameNoExt + "-combos.txt"); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile)); // parse the file and create the count variable and update it as you populate // the arrayList DataObject dataObject = fileParser.parseFile("upload-dir/" + file.getOriginalFilename()); ArrayList<Parameter> arrList = fileParser.parseParameters(dataObject); int count = 1; // create a list of expected results to compare with the combinations of parameters ArrayList<ExpectedResult> expectedResults = fileParser.parseExpectedResults(dataObject); // write to the file and update the count variable, so it can be used later. for (Parameter temp : arrList) { writer.write( "Parameter Name: " + temp.getName() + " | Equivalence Classes: " + temp.getEquivalenceClasses()); writer.write("\n"); count = count * temp.getEquivalenceClasses().size(); } writer.write("\n"); // create a matrix and populate it using the createCombos method. Pass in // arrList and count as parameters String[][] combos = fileParser.createCombos(arrList, count); // create a map to keep track of which index corresponds to which parameter name. // make the map after generating the test cases in case the order of the parameters // changes somehow Map<String, Integer> parameterNameIndexMap = fileParser.getParamMap(arrList); //Map< Integer,String> parameterNameIndexMapByIndex = fileParser.getParamMapByIndex(arrList); // this is used to write the test case combinations to the text file. int testCaseNumber = 1; for (int row = 0; row < combos.length; row++) { if (testCaseNumber < 10) { writer.write("Test Case " + testCaseNumber + ": "); } else if (testCaseNumber >= 10 && testCaseNumber < 100) { writer.write("Test Case " + testCaseNumber + ": "); } else { writer.write("Test Case " + testCaseNumber + ": "); } testCaseNumber++; for (int column = 0; column < combos[row].length; column++) { String paramName = arrList.get(column).getName(); String conjunction = column == 0 ? "When " : "and "; String output = conjunction + paramName + " = "+ combos[row][column] +" "; writer.write(output); //writer.write(combos[row][column] + " "); } // use a string builder so the concatenation of multiple expected results is // slightly more efficient StringBuilder expectedResultsStringBuilder = new StringBuilder(""); for (ExpectedResult er : expectedResults) { Queue<String> condition = fileParser.prepareCondition(er.getCondition()); if(fileParser.compareTestCaseWithCondtions(condition, combos[row], parameterNameIndexMap)) { expectedResultsStringBuilder.append(er.getName()).append(" "); } } if(expectedResultsStringBuilder.toString().equals("")) { expectedResultsStringBuilder.append("Invalid"); } writer.write( "- Expected result => " +expectedResultsStringBuilder.toString()); writer.write("\n"); } writer.close(); } @PostMapping("/api") @ResponseBody public ResponseEntity<Resource> directAPI(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); int dotIndex = fileName.lastIndexOf("."); String fileNameNoExt = fileName.substring(0, dotIndex); try { processFile(file, fileNameNoExt); } catch (Exception ex) { System.out.println(ex.getMessage()); return ResponseEntity.badRequest().body(null); } Resource res = storageService.loadAsResource(fileNameNoExt + "-combos.txt"); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + res.getFilename() + "\"") .body(res); } // This method was modified in order to gain the functionality we need. // The purpose of this method is to store the JSON file submitted in order to // use it // to parse and create combinations. Then it will write to a new file and add // that to the // upload-dir folder. @PostMapping("/") public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { // create the text file name based on the JSON file String fileName = file.getOriginalFilename(); int dotIndex = fileName.lastIndexOf("."); String fileNameNoExt = fileName.substring(0, dotIndex); try { processFile(file, fileNameNoExt); // catch and error and throw an error message. This gets rid of the server error // page } catch (Exception e) { // e.printStackTrace(); redirectAttributes.addFlashAttribute("message", e.getMessage()); return "redirect:/"; } // return a message to indicate the file was successfully submitted and that // they received their text file. redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "\n" + "and received " + fileNameNoExt + "-combos.txt!"); return "redirect:/"; } @ExceptionHandler(StorageFileNotFoundException.class) public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) { return ResponseEntity.notFound().build(); } }
39.427907
114
0.745783
ae722b84238b26e618076e3a96127d2a78626b86
6,589
package es.upm.miw.apaw_ep_computers.api_controllers; import es.upm.miw.apaw_ep_computers.ApiTestConfig; import es.upm.miw.apaw_ep_computers.daos.ComponentDao; import es.upm.miw.apaw_ep_computers.daos.ComputerDao; import es.upm.miw.apaw_ep_computers.daos.SupplierDao; import es.upm.miw.apaw_ep_computers.documents.Component; import es.upm.miw.apaw_ep_computers.documents.Computer; import es.upm.miw.apaw_ep_computers.documents.Supplier; import es.upm.miw.apaw_ep_computers.dtos.ComponentDto; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertNotNull; @ApiTestConfig class ComponentResourceIT { @Autowired private WebTestClient webTestClient; @Autowired private ComputerDao computerDao; @Autowired private SupplierDao supplierDao; @Autowired private ComponentDao componentDao; @Test void testCreate() { ComponentDto componentDto = createComponentAndReturn("cpu", "intel core i5",150d,"7400", true); assertNotNull(componentDto); assertEquals("cpu", componentDto.getType()); assertEquals("intel core i5", componentDto.getName()); assertEquals(150, componentDto.getCost()); assertEquals("7400", componentDto.getModel()); } @Test void testCreateComponentException() { ComponentDto componentDto = new ComponentDto("cpu","intel", 0,null, true); this.webTestClient .post().uri(ComponentResource.COMPONENTS) .body(BodyInserters.fromObject(componentDto)) .exchange() .expectStatus().isEqualTo(HttpStatus.BAD_REQUEST); } void createComponent(String type, String name, Double cost, String model, Boolean isComposite){ this.webTestClient .post().uri(ComponentResource.COMPONENTS) .body(BodyInserters.fromObject(new ComponentDto(type, name, cost, model, isComposite))) .exchange() .expectStatus().isOk() .expectBody(ComponentDto.class).returnResult().getResponseBody(); } ComponentDto createComponentAndReturn(String type, String name, Double cost, String model, Boolean isComposite){ return this.webTestClient .post().uri(ComponentResource.COMPONENTS) .body(BodyInserters.fromObject(new ComponentDto(type, name, cost, model, isComposite))) .exchange() .expectStatus().isOk() .expectBody(ComponentDto.class).returnResult().getResponseBody(); } void createSupplierAndComputer(String description, Double price, Double cost, Boolean isStocked, String component){ Supplier supplier = new Supplier("supplier1", 10.0); this.supplierDao.save(supplier); List<Component> list = new ArrayList<>(); if(this.componentDao.findById(component).isPresent()) list.add(this.componentDao.findById(component).get()); Computer computer = new Computer(description, price, cost, isStocked, supplier, list); this.computerDao.save(computer); } @Test void testGetSearchType() { createComponent("cpu","intel core i5",150.0,"7400", true); createComponent("cpu","intel core i7",180.0,"8400", false); createComponent("cpu","intel core i7",200.90,"9700", true); createComponent("memory","Samsung HDD",50.0,"HDD-1TB", false); List<ComponentDto> components = this.webTestClient .get().uri(uriBuilder -> uriBuilder.path(ComponentResource.COMPONENTS + ComponentResource.SEARCH) .queryParam("q", "type:=cpu") .build()) .exchange() .expectStatus().isOk() .expectBodyList(ComponentDto.class) .returnResult().getResponseBody(); assertFalse(components != null && components.isEmpty()); } @Test void testGetSearchTypeBadQueryException() { this.webTestClient .get().uri(uriBuilder -> uriBuilder.path(ComponentResource.COMPONENTS + ComponentResource.SEARCH) .queryParam("q", "types:=cpu") .build()) .exchange() .expectStatus().isEqualTo(HttpStatus.BAD_REQUEST); } @Test void testDeleteComponentIdWithNoReferences() { ComponentDto componentDto = createComponentAndReturn("component1", "intel core i5",150d,"7400", true); this.webTestClient .delete().uri(ComponentResource.COMPONENTS + ComponentResource.ID_ID, componentDto.getId()) .exchange().expectStatus().isOk(); this.webTestClient .get().uri(ComponentResource.COMPONENTS + ComponentResource.ID_ID, componentDto.getId()) .exchange().expectStatus().isEqualTo(HttpStatus.NOT_FOUND); } @Test void testDeleteComponentIdWithReferences() { ComponentDto componentDto = createComponentAndReturn("component2", "intel core i3",125d,"6100", true); createSupplierAndComputer("pc",500.0d,400.0d,true, componentDto.getId() ); this.webTestClient .delete().uri(ComponentResource.COMPONENTS + ComponentResource.ID_ID, componentDto.getId()) .exchange().expectStatus().isOk(); this.webTestClient .get().uri(ComponentResource.COMPONENTS + ComponentResource.ID_ID, componentDto.getId()) .exchange().expectStatus().isEqualTo(HttpStatus.NOT_FOUND); } @Test void testDeleteExceptionBadRequest() { this.webTestClient .delete().uri(ComponentResource.COMPONENTS, "comp123") .exchange().expectStatus().isEqualTo(HttpStatus.BAD_REQUEST); } @Test void testDeleteNoContent() { ComponentDto componentDto = this.webTestClient .delete().uri(ComponentResource.COMPONENTS + ComponentResource.ID_ID, "example") .exchange().expectStatus().isEqualTo(HttpStatus.OK) .expectBody(ComponentDto.class).returnResult().getResponseBody(); Assert.assertNull(componentDto); } }
41.702532
119
0.659888
048db5527c5abdf44eec36a746ef22d09b5ca0cf
3,202
/** * Copyright 2007-2016, Kaazing Corporation. 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 org.kaazing.gateway.management.monitoring.entity.impl; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import org.junit.Ignore; import org.junit.Test; import org.kaazing.gateway.management.monitoring.configuration.impl.MMFMonitoringDataManager; import org.kaazing.gateway.service.LongMonitoringCounter; import org.kaazing.gateway.service.MonitoringEntityFactory; import org.agrona.IoUtil; @Ignore("doesn't work with latest Agrona 0.4.12") public class AgronaMonitoringEntityFactoryTest { private static final String DEV_SHM = "/dev/shm/"; private static final String LINUX = "Linux"; private static final String OS_NAME = "os.name"; private static final String MONITORING_FILE = "monitor"; private static final String MONITORING_FILE_LOCATION = "/kaazing"; @Test public void testAgronaLifecycle() { File monitoringDir; File monitoringFile; MMFMonitoringDataManager monitoringDataManager = new MMFMonitoringDataManager(MONITORING_FILE); try { MonitoringEntityFactory monitoringEntityFactory = monitoringDataManager.initialize(); try { LongMonitoringCounter longMonitoringCounter = monitoringEntityFactory.makeLongMonitoringCounter("test"); String osName = System.getProperty(OS_NAME); if (LINUX.equals(osName)) { String monitoringDirName = DEV_SHM + IoUtil.tmpDirName() + MONITORING_FILE_LOCATION; monitoringDir = new File(monitoringDirName); assertTrue(monitoringDir.exists()); monitoringFile = new File(monitoringDirName, MONITORING_FILE); assertTrue(monitoringFile.exists()); } else { String monitoringDirName = IoUtil.tmpDirName() + MONITORING_FILE_LOCATION; monitoringDir = new File(monitoringDirName); assertTrue(monitoringDir.exists()); monitoringFile = new File(monitoringDirName, MONITORING_FILE); assertTrue(monitoringFile.exists()); } assertNotNull(longMonitoringCounter); } finally { monitoringEntityFactory.close(); } } finally { monitoringDataManager.close(); } assertFalse(monitoringDir.exists()); assertFalse(monitoringFile.exists()); } }
40.025
120
0.678014
851ba8dd5948d626f936b10ef0a2b45ca3081e17
112
package io.github.kuyer.logmonitor; /** * for test * @author rory.zhang */ public class LogMonitorTest { }
11.2
35
0.6875
89311fc23e2343dc8e951ce8eb495e7b892c9e12
8,319
package io.github.mylyed.gravy.entitis; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Formula; /** * 商品信息 * * @author lilei * */ @Entity @Table(name = "ecs_goods") public class Goods { private Integer goods_id; private String goods_sn; private String goods_name; private String goods_brief; private String goods_keywords; private String specification; private String goods_spec; private String brand_country; private Integer last_update; private BigDecimal market_price; private BigDecimal shop_price; private BigDecimal origin_price; private BigDecimal promote_price; private Integer is_new; private Integer goods_delete; private Integer sort_order; private String is_on_sale; private Integer sales_volume; private Integer goods_number; // ------------------- private String cat_id;// b.cat_id; private String cat_name;// b.cat_name private String category_keywords;// b.keywords private String category_alias;// b.alias private String cat_delete;// b.is_delete private String brand_name;// c.brand_name; private String brand_alias;// c.alias private String brand_country1;// c.country private Integer brand_id;// c.brand_id; private String goods_country;// e.region_name private Integer promote_flag; private Integer goods_num_flag; private Integer volume_flag; @Id @Column(name = "goods_id") public Integer getGoods_id() { return goods_id; } public void setGoods_id(Integer goods_id) { this.goods_id = goods_id; } @Column(name = "goods_sn") public String getGoods_sn() { return goods_sn; } public void setGoods_sn(String goods_sn) { this.goods_sn = goods_sn; } @Column(name = "goods_name") public String getGoods_name() { return goods_name; } public void setGoods_name(String goods_name) { this.goods_name = goods_name; } @Column(name = "goods_brief") public String getGoods_brief() { return goods_brief; } public void setGoods_brief(String goods_brief) { this.goods_brief = goods_brief; } @Column(name = "keywords") public String getGoods_keywords() { return goods_keywords; } public void setGoods_keywords(String goods_keywords) { this.goods_keywords = goods_keywords; } @Column(name = "specification") public String getSpecification() { return specification; } public void setSpecification(String specification) { this.specification = specification; } @Column(name = "goods_spec") public String getGoods_spec() { return goods_spec; } public void setGoods_spec(String goods_spec) { this.goods_spec = goods_spec; } @Column(name = "brand_country") public String getBrand_country() { return brand_country; } public void setBrand_country(String brand_country) { this.brand_country = brand_country; } @Column(name = "last_update") public Integer getLast_update() { return last_update; } public void setLast_update(Integer last_update) { this.last_update = last_update; } @Column(name = "market_price") public BigDecimal getMarket_price() { return market_price; } public void setMarket_price(BigDecimal market_price) { this.market_price = market_price; } @Column(name = "shop_price") public BigDecimal getShop_price() { return shop_price; } public void setShop_price(BigDecimal shop_price) { this.shop_price = shop_price; } @Column(name = "origin_price") public BigDecimal getOrigin_price() { return origin_price; } public void setOrigin_price(BigDecimal origin_price) { this.origin_price = origin_price; } @Column(name = "promote_price", insertable = false, updatable = false) public BigDecimal getPromote_price() { return promote_price; } public void setPromote_price(BigDecimal promote_price) { this.promote_price = promote_price; } @Column(name = "is_new") public Integer getIs_new() { return is_new; } public void setIs_new(Integer is_new) { this.is_new = is_new; } @Column(name = "is_delete") public Integer getGoods_delete() { return goods_delete; } public void setGoods_delete(Integer goods_delete) { this.goods_delete = goods_delete; } @Column(name = "sort_order") public Integer getSort_order() { return sort_order; } public void setSort_order(Integer sort_order) { this.sort_order = sort_order; } @Column(name = "is_on_sale") public String getIs_on_sale() { return is_on_sale; } public void setIs_on_sale(String is_on_sale) { this.is_on_sale = is_on_sale; } @Column(name = "sales_volume") public Integer getSales_volume() { return sales_volume; } public void setSales_volume(Integer sales_volume) { this.sales_volume = sales_volume; } @Column(name = "goods_number") public Integer getGoods_number() { return goods_number; } public void setGoods_number(Integer goods_number) { this.goods_number = goods_number; } // ------------------------------------------------------- @Formula("(SELECT b.cat_id FROM ecs_category b WHERE b.cat_id = cat_id)") public String getCat_id() { return cat_id; } public void setCat_id(String cat_id) { this.cat_id = cat_id; } @Formula("(SELECT b.cat_name FROM ecs_category b WHERE b.cat_id = cat_id)") public String getCat_name() { return cat_name; } public void setCat_name(String cat_name) { this.cat_name = cat_name; } @Formula("(SELECT b.keywords FROM ecs_category b WHERE b.cat_id = cat_id)") public String getCategory_keywords() { return category_keywords; } public void setCategory_keywords(String category_keywords) { this.category_keywords = category_keywords; } @Formula("(SELECT b.is_delete FROM ecs_category b WHERE b.cat_id = cat_id)") public String getCat_delete() { return cat_delete; } public void setCat_delete(String cat_delete) { this.cat_delete = cat_delete; } @Formula("(SELECT b.alias FROM ecs_category b WHERE b.cat_id = cat_id)") public String getCategory_alias() { return category_alias; } public void setCategory_alias(String category_alias) { this.category_alias = category_alias; } @Formula("(SELECT c.brand_name FROM ecs_brand c WHERE c.brand_id = brand_id)") public String getBrand_name() { return brand_name; } public void setBrand_name(String brand_name) { this.brand_name = brand_name; } @Formula("(SELECT c.alias FROM ecs_brand c WHERE c.brand_id = brand_id)") public String getBrand_alias() { return brand_alias; } public void setBrand_alias(String brand_alias) { this.brand_alias = brand_alias; } @Formula("(SELECT c.country FROM ecs_brand c WHERE c.brand_id = brand_id)") public String getBrand_country1() { return brand_country1; } public void setBrand_country1(String brand_country1) { this.brand_country1 = brand_country1; } @Formula("(SELECT c.brand_id FROM ecs_brand c WHERE c.brand_id = brand_id)") public Integer getBrand_id() { return brand_id; } public void setBrand_id(Integer brand_id) { this.brand_id = brand_id; } @Formula("(SELECT e.region_name FROM ecs_region e WHERE e.region_id = goods_country)") public String getGoods_country() { return goods_country; } public void setGoods_country(String goods_country) { this.goods_country = goods_country; } @Column(name = "promote_price", insertable = false, updatable = false) public Integer getPromote_flag() { return promote_flag; } public void setPromote_flag(Integer promote_flag) { this.promote_flag = promote_flag > 0 ? 1 : 0; } @Column(name = "goods_number", insertable = false, updatable = false) public Integer getGoods_num_flag() { return goods_num_flag; } public void setGoods_num_flag(Integer goods_num_flag) { this.goods_num_flag = goods_num_flag > 0 ? 1 : 0; } @Column(name = "sales_volume", insertable = false, updatable = false) public Integer getVolume_flag() { return volume_flag; } public void setVolume_flag(Integer volume_flag) { this.volume_flag = volume_flag > 0 ? 1 : 0; } }
23.974063
88
0.708378
36068ccd9077b70bede68098d77e096df762566d
3,735
package org.apache.taverna.activities.xpath.ui.menu; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.net.URI; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.KeyStroke; import org.apache.taverna.activities.xpath.ui.servicedescription.XPathTemplateService; import org.apache.taverna.ui.menu.AbstractMenuAction; import org.apache.taverna.ui.menu.DesignOnlyAction; import org.apache.taverna.ui.menu.MenuManager; import org.apache.taverna.workbench.activityicons.ActivityIconManager; import org.apache.taverna.workbench.edits.EditManager; import org.apache.taverna.workbench.selection.SelectionManager; import org.apache.taverna.workbench.ui.workflowview.WorkflowView; import org.apache.taverna.services.ServiceRegistry; /** * An action to add a REST activity + a wrapping processor to the workflow. * * @author Alex Nenadic * @author alanrw */ @SuppressWarnings("serial") public class AddXPathTemplateMenuAction extends AbstractMenuAction { private static final String ADD_XPATH = "XPath"; private static final URI INSERT = URI .create("http://taverna.sf.net/2008/t2workbench/menu#insert"); private static final URI ADD_XPATH_URI = URI .create("http://taverna.sf.net/2008/t2workbench/menu#graphMenuAddXPath"); private EditManager editManager; private MenuManager menuManager; private SelectionManager selectionManager; private ActivityIconManager activityIconManager; private ServiceRegistry serviceRegistry; public AddXPathTemplateMenuAction() { super(INSERT, 1000, ADD_XPATH_URI); } @Override protected Action createAction() { return new AddXPathMenuAction(); } protected class AddXPathMenuAction extends AbstractAction implements DesignOnlyAction { AddXPathMenuAction() { super(); putValue(SMALL_ICON, activityIconManager.iconForActivity(XPathTemplateService.ACTIVITY_TYPE)); putValue(NAME, ADD_XPATH); putValue(SHORT_DESCRIPTION, "XPath service"); putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.SHIFT_DOWN_MASK | InputEvent.ALT_DOWN_MASK)); } public void actionPerformed(ActionEvent e) { WorkflowView.importServiceDescription(XPathTemplateService.getServiceDescription(), false, editManager, menuManager, selectionManager, serviceRegistry); } } public void setEditManager(EditManager editManager) { this.editManager = editManager; } public void setMenuManager(MenuManager menuManager) { this.menuManager = menuManager; } public void setSelectionManager(SelectionManager selectionManager) { this.selectionManager = selectionManager; } public void setActivityIconManager(ActivityIconManager activityIconManager) { this.activityIconManager = activityIconManager; } public void setServiceRegistry(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } }
32.763158
88
0.790897
b76a296fed89afa9dcd2119c55a30242e43350d1
2,587
package com.haoyue.app.happyreader.interactor.impl; import com.haoyue.app.happyreader.bean.HotNewsEntity; import com.haoyue.app.happyreader.bean.HotWxNewsEntity; import com.haoyue.app.happyreader.interactor.HotWxNewsListInteractor; import com.haoyue.app.happyreader.interactor.NewsListInteractor; import com.haoyue.app.happyreader.listeners.BaseMultiLoadedListener; import com.haoyue.app.happyreader.utils.ApiManager; import com.haoyue.app.happyreader.utils.Config; import com.haoyue.app.happyreader.utils.Md5Util; import com.haoyue.app.happyreader.utils.TimeUtil; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; public class NewsListInteractorImpl implements NewsListInteractor { private BaseMultiLoadedListener<HotNewsEntity> loadedListener = null; public NewsListInteractorImpl(BaseMultiLoadedListener<HotNewsEntity> loadedListener) { this.loadedListener = loadedListener; } @Override public void getCommonListData(final String requestTag, final int event_tag, String channelId, int page) { String timestamp = TimeUtil.getCurrentTimeStr(); StringBuffer signSb = new StringBuffer(); signSb.append("channelId").append(channelId) .append("page").append(page) .append("showapi_appid").append(Config.API_ID) .append("showapi_timestamp").append(timestamp) .append(Config.API_SECRET); String showapi_sign = Md5Util.doMD5(signSb.toString()); ApiManager.getInstance().getHotNews(channelId, "", page, Config.API_ID, timestamp, "", showapi_sign) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<HotNewsEntity>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { loadedListener.onException(e.getMessage()); } @Override public void onNext(HotNewsEntity hotWxNewsEntity) { if (hotWxNewsEntity.getShowapi_res_code()==0){ loadedListener.onSuccess(event_tag, hotWxNewsEntity); }else { loadedListener.onError(hotWxNewsEntity.getShowapi_res_error()); } } }); } }
41.725806
109
0.611519
882936ec9b7b1fa24635f9e65d0c7b830d59859e
1,741
package ch7.ex1; import java.util.function.Function; public class Demo01_ExecuteAround_duration { public static void main(String[] args) { System.out.println(imperativeSquareApproach(5)); System.out.println(imperativeCubeApproach(5)); Function<Integer, Integer> computeSquare = x -> x * x; Function<Integer, Integer> computeCube = x -> x * x * x; System.out.println(functionalApproach(computeSquare, 5)); System.out.println(functionalApproach(computeCube, 5)); } // imperative public static int imperativeSquareApproach(int value) { long start = System.currentTimeMillis(); int result = 0; try { result = value * value; Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); long duration = end - start; System.out.print("Duration: " + duration + " - "); return result; } public static int imperativeCubeApproach(int value) { long start = System.currentTimeMillis(); int result = 0; try { result = value * value * value; Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); long duration = end - start; System.out.print("Duration: " + duration + " - "); return result; } // functional public static int functionalApproach(Function<Integer, Integer> computation, int value) { long start = System.currentTimeMillis(); Integer result = null; try { result = computation.apply(value); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); long duration = end - start; System.out.print("Duration: " + duration + " - "); return result; } }
27.203125
90
0.68811
acb26fb9ebcc32b71d0268a867b7e8d0e02de937
14,398
/* * 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.connect.runtime.isolation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Modifier; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; /** * Connect plugin utility methods. */ public class PluginUtils { private static final Logger log = LoggerFactory.getLogger(PluginUtils.class); // Be specific about javax packages and exclude those existing in Java SE and Java EE libraries. private static final Pattern BLACKLIST = Pattern.compile("^(?:" + "java" + "|javax\\.accessibility" + "|javax\\.activation" + "|javax\\.activity" + "|javax\\.annotation" + "|javax\\.batch\\.api" + "|javax\\.batch\\.operations" + "|javax\\.batch\\.runtime" + "|javax\\.crypto" + "|javax\\.decorator" + "|javax\\.ejb" + "|javax\\.el" + "|javax\\.enterprise\\.concurrent" + "|javax\\.enterprise\\.context" + "|javax\\.enterprise\\.context\\.spi" + "|javax\\.enterprise\\.deploy\\.model" + "|javax\\.enterprise\\.deploy\\.shared" + "|javax\\.enterprise\\.deploy\\.spi" + "|javax\\.enterprise\\.event" + "|javax\\.enterprise\\.inject" + "|javax\\.enterprise\\.inject\\.spi" + "|javax\\.enterprise\\.util" + "|javax\\.faces" + "|javax\\.imageio" + "|javax\\.inject" + "|javax\\.interceptor" + "|javax\\.jms" + "|javax\\.json" + "|javax\\.jws" + "|javax\\.lang\\.model" + "|javax\\.mail" + "|javax\\.management" + "|javax\\.management\\.j2ee" + "|javax\\.naming" + "|javax\\.net" + "|javax\\.persistence" + "|javax\\.print" + "|javax\\.resource" + "|javax\\.rmi" + "|javax\\.script" + "|javax\\.security\\.auth" + "|javax\\.security\\.auth\\.message" + "|javax\\.security\\.cert" + "|javax\\.security\\.jacc" + "|javax\\.security\\.sasl" + "|javax\\.servlet" + "|javax\\.sound\\.midi" + "|javax\\.sound\\.sampled" + "|javax\\.sql" + "|javax\\.swing" + "|javax\\.tools" + "|javax\\.transaction" + "|javax\\.validation" + "|javax\\.websocket" + "|javax\\.ws\\.rs" + "|javax\\.xml" + "|javax\\.xml\\.bind" + "|javax\\.xml\\.registry" + "|javax\\.xml\\.rpc" + "|javax\\.xml\\.soap" + "|javax\\.xml\\.ws" + "|org\\.ietf\\.jgss" + "|org\\.omg\\.CORBA" + "|org\\.omg\\.CosNaming" + "|org\\.omg\\.Dynamic" + "|org\\.omg\\.DynamicAny" + "|org\\.omg\\.IOP" + "|org\\.omg\\.Messaging" + "|org\\.omg\\.PortableInterceptor" + "|org\\.omg\\.PortableServer" + "|org\\.omg\\.SendingContext" + "|org\\.omg\\.stub\\.java\\.rmi" + "|org\\.w3c\\.dom" + "|org\\.xml\\.sax" + "|org\\.apache\\.kafka" + "|org\\.slf4j" + ")\\..*$"); // If the base interface or class that will be used to identify Connect plugins resides within // the same java package as the plugins that need to be loaded in isolation (and thus are // added to the WHITELIST), then this base interface or class needs to be excluded in the // regular expression pattern private static final Pattern WHITELIST = Pattern.compile("^org\\.apache\\.kafka\\.(?:connect\\.(?:" + "transforms\\.(?!Transformation$).*" + "|json\\..*" + "|file\\..*" + "|mirror\\..*" + "|mirror-client\\..*" + "|converters\\..*" + "|storage\\.StringConverter" + "|storage\\.SimpleHeaderConverter" + "|rest\\.basic\\.auth\\.extension\\.BasicAuthSecurityRestExtension" + "|connector\\.policy\\.(?!ConnectorClientConfig(?:OverridePolicy|Request(?:\\$ClientType)?)$).*" + ")" + "|common\\.config\\.provider\\.(?!ConfigProvider$).*" + ")$"); private static final DirectoryStream.Filter<Path> PLUGIN_PATH_FILTER = new DirectoryStream .Filter<Path>() { @Override public boolean accept(Path path) { return Files.isDirectory(path) || isArchive(path) || isClassFile(path); } }; /** * Return whether the class with the given name should be loaded in isolation using a plugin * classloader. * * @param name the fully qualified name of the class. * @return true if this class should be loaded in isolation, false otherwise. */ public static boolean shouldLoadInIsolation(String name) { return !(BLACKLIST.matcher(name).matches() && !WHITELIST.matcher(name).matches()); } /** * Verify the given class corresponds to a concrete class and not to an abstract class or * interface. * @param klass the class object. * @return true if the argument is a concrete class, false if it's abstract or interface. */ public static boolean isConcrete(Class<?> klass) { int mod = klass.getModifiers(); return !Modifier.isAbstract(mod) && !Modifier.isInterface(mod); } /** * Return whether a path corresponds to a JAR or ZIP archive. * * @param path the path to validate. * @return true if the path is a JAR or ZIP archive file, otherwise false. */ public static boolean isArchive(Path path) { String archivePath = path.toString().toLowerCase(Locale.ROOT); return archivePath.endsWith(".jar") || archivePath.endsWith(".zip"); } /** * Return whether a path corresponds java class file. * * @param path the path to validate. * @return true if the path is a java class file, otherwise false. */ public static boolean isClassFile(Path path) { return path.toString().toLowerCase(Locale.ROOT).endsWith(".class"); } public static List<Path> pluginLocations(Path topPath) throws IOException { List<Path> locations = new ArrayList<>(); try ( DirectoryStream<Path> listing = Files.newDirectoryStream( topPath, PLUGIN_PATH_FILTER ) ) { for (Path dir : listing) { locations.add(dir); } } return locations; } /** * Given a top path in the filesystem, return a list of paths to archives (JAR or ZIP * files) contained under this top path. If the top path contains only java class files, * return the top path itself. This method follows symbolic links to discover archives and * returns the such archives as absolute paths. * * @param topPath the path to use as root of plugin search. * @return a list of potential plugin paths, or empty list if no such paths exist. * @throws IOException */ public static List<Path> pluginUrls(Path topPath) throws IOException { boolean containsClassFiles = false; Set<Path> archives = new TreeSet<>(); LinkedList<DirectoryEntry> dfs = new LinkedList<>(); Set<Path> visited = new HashSet<>(); if (isArchive(topPath)) { return Collections.singletonList(topPath); } DirectoryStream<Path> topListing = Files.newDirectoryStream( topPath, PLUGIN_PATH_FILTER ); dfs.push(new DirectoryEntry(topListing)); visited.add(topPath); try { while (!dfs.isEmpty()) { Iterator<Path> neighbors = dfs.peek().iterator; if (!neighbors.hasNext()) { dfs.pop().stream.close(); continue; } Path adjacent = neighbors.next(); if (Files.isSymbolicLink(adjacent)) { try { Path symlink = Files.readSymbolicLink(adjacent); // if symlink is absolute resolve() returns the absolute symlink itself Path parent = adjacent.getParent(); if (parent == null) { continue; } Path absolute = parent.resolve(symlink).toRealPath(); if (Files.exists(absolute)) { adjacent = absolute; } else { continue; } } catch (IOException e) { // See https://issues.apache.org/jira/browse/KAFKA-6288 for a reported // failure. Such a failure at this stage is not easily reproducible and // therefore an exception is caught and ignored after issuing a // warning. This allows class scanning to continue for non-broken plugins. log.warn( "Resolving symbolic link '{}' failed. Ignoring this path.", adjacent, e ); continue; } } if (!visited.contains(adjacent)) { visited.add(adjacent); if (isArchive(adjacent)) { archives.add(adjacent); } else if (isClassFile(adjacent)) { containsClassFiles = true; } else { DirectoryStream<Path> listing = Files.newDirectoryStream( adjacent, PLUGIN_PATH_FILTER ); dfs.push(new DirectoryEntry(listing)); } } } } finally { while (!dfs.isEmpty()) { dfs.pop().stream.close(); } } if (containsClassFiles) { if (archives.isEmpty()) { return Collections.singletonList(topPath); } log.warn("Plugin path contains both java archives and class files. Returning only the" + " archives"); } return Arrays.asList(archives.toArray(new Path[0])); } /** * Return the simple class name of a plugin as {@code String}. * * @param plugin the plugin descriptor. * @return the plugin's simple class name. */ public static String simpleName(PluginDesc<?> plugin) { return plugin.pluginClass().getSimpleName(); } /** * Remove the plugin type name at the end of a plugin class name, if such suffix is present. * This method is meant to be used to extract plugin aliases. * * @param plugin the plugin descriptor. * @return the pruned simple class name of the plugin. */ public static String prunedName(PluginDesc<?> plugin) { // It's currently simpler to switch on type than do pattern matching. switch (plugin.type()) { case SOURCE: case SINK: case CONNECTOR: return prunePluginName(plugin, "Connector"); default: return prunePluginName(plugin, plugin.type().simpleName()); } } /** * Verify whether a given plugin's alias matches another alias in a collection of plugins. * * @param alias the plugin descriptor to test for alias matching. * @param plugins the collection of plugins to test against. * @param <U> the plugin type. * @return false if a match was found in the collection, otherwise true. */ public static <U> boolean isAliasUnique( PluginDesc<U> alias, Collection<PluginDesc<U>> plugins ) { boolean matched = false; for (PluginDesc<U> plugin : plugins) { if (simpleName(alias).equals(simpleName(plugin)) || prunedName(alias).equals(prunedName(plugin))) { if (matched) { return false; } matched = true; } } return true; } private static String prunePluginName(PluginDesc<?> plugin, String suffix) { String simple = plugin.pluginClass().getSimpleName(); int pos = simple.lastIndexOf(suffix); if (pos > 0) { return simple.substring(0, pos); } return simple; } private static class DirectoryEntry { final DirectoryStream<Path> stream; final Iterator<Path> iterator; DirectoryEntry(DirectoryStream<Path> stream) { this.stream = stream; this.iterator = stream.iterator(); } } }
37.989446
110
0.538755
91c101aeb096221f73bc50efc920ab15f67ae9ce
146
package com.test.behavior; public class FlyNoWay implements FlyBehavior{ @Override public void fly() { System.out.println("no fly"); } }
13.272727
45
0.712329
21c9b49a6c5ea566b7362c0d91861508b9e17ec7
2,707
/* * Copyright 2019 The TranSysLab Authors. 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.transyslab.experiments; import com.transyslab.commons.io.TXTUtils; import com.transyslab.commons.tools.adapter.SimProblem; import com.transyslab.commons.tools.adapter.SimSolution; import com.transyslab.commons.tools.optimizer.DifferentialEvolution; import com.transyslab.commons.tools.optimizer.DominanceComparator; import com.transyslab.simcore.mlp.ExpSwitch; import org.uma.jmetal.operator.impl.crossover.DifferentialEvolutionCrossover; import org.uma.jmetal.operator.impl.selection.DifferentialEvolutionSelection; import org.uma.jmetal.util.evaluator.impl.SequentialSolutionListEvaluator; import org.uma.jmetal.util.pseudorandom.JMetalRandom; import java.util.Arrays; public class OptmRMSEProblem { public static void main(String[] args) { int popSize = 20; int maxGeneration = 1000; double crossOver_cr = 0.5; double crossOver_f = 0.5; String crossOver_variant = "rand/1/bin"; String simMasterFileName = "src/main/resources/optmksidvd.properties"; SimProblem problem = new RMSEProblem(simMasterFileName); DifferentialEvolution algorithm; DifferentialEvolutionSelection selection = new DifferentialEvolutionSelection(); DifferentialEvolutionCrossover crossover = new DifferentialEvolutionCrossover(crossOver_cr, crossOver_f, crossOver_variant) ; algorithm = new DifferentialEvolution(problem,maxGeneration*popSize,popSize, crossover,selection,new SequentialSolutionListEvaluator<>()); // algorithm.setComparator(new DominanceComparator<>()); algorithm.setSolutionWriter(new TXTUtils("src/main/resources/rs(RMSE).csv")); algorithm.run(); SimSolution bestSolution = (SimSolution) algorithm.getResult(); System.out.println("BestFitness: " + Arrays.toString(bestSolution.getObjectiveValues())); System.out.println("BestSolution: " + Arrays.toString(bestSolution.getInputVariables())); System.out.println("AlgSeed: " + JMetalRandom.getInstance().getSeed()); problem.closeProblem(); } }
45.116667
133
0.753602
bb23f7c0b0d5eef1605b90a6410403eb14f50086
2,552
// Copyright 2009 Distributed Systems Group, University of Kassel // This program is distributed under the GNU Lesser General Public License (LGPL). // // This file is part of the Carpe Noctem Software Framework. // // The Carpe Noctem Software Framework is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The Carpe Noctem Software Framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. package de.uni_kassel.cn.planDesigner.ui.util; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.transaction.NotificationFilter; import org.eclipse.emf.transaction.ResourceSetChangeEvent; import org.eclipse.emf.transaction.ResourceSetListener; import org.eclipse.emf.transaction.RollbackException; public class ResourceSetChangeListener implements ResourceSetListener { public NotificationFilter getFilter() { // TODO Auto-generated method stub return null; } public boolean isAggregatePrecommitListener() { // TODO Auto-generated method stub return false; } public boolean isPostcommitOnly() { // TODO Auto-generated method stub return false; } public boolean isPrecommitOnly() { // TODO Auto-generated method stub return false; } public void resourceSetChanged(ResourceSetChangeEvent event) { // System.out.println("\n------------------------------------------\n"); // System.out.println("Domain " + event.getEditingDomain().getID() + // " changed " + event.getNotifications().size() + " times" ); // // for(Notification n : event.getNotifications()){ // System.out.println("\tNotifaction -> \n" // +"\t\tType: " +n.getEventType() // +", \n\t\tFeatureID: " +n.getFeatureID(null) +", Feature: " +n.getFeature() // +", \n\t\tNotifier: " +n.getNotifier() // +", \n\t\tOldValue: " +n.getOldValue() // +", \n\t\tNewValue: " +n.getNewValue()); // // } // System.out.println("\n------------------------------------------\n"); } public Command transactionAboutToCommit(ResourceSetChangeEvent event) throws RollbackException { // TODO Auto-generated method stub return null; } }
36.985507
97
0.675157
7d9af8cf7327844bb63d88e6d97b8c7a9c220d55
1,498
package com.tech.xiwi.xpay; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.tech.xiwi.pay.alipay.AliPay; import com.tech.xiwi.pay.common.Channel; import com.tech.xiwi.pay.common.IPay; import com.tech.xiwi.pay.common.PayApi; import com.tech.xiwi.pay.wechat.WXPay; import org.json.JSONObject; import java.util.Map; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private void patAli() { PayApi payApi = new PayApi(); payApi.pay(this, AliPay.build(), Channel.Ali, "", new IPay.PayCallback() { @Override public void onSuccess(Map<String, String> data) { } @Override public void onFailed() { } @Override public void onCancel() { } }); } private void payWechat() { PayApi payApi = new PayApi(); WXPay.ParamBuilder builder = new WXPay.ParamBuilder(); payApi.pay(this, WXPay.build(), Channel.Wechat, builder.create(), new IPay.PayCallback() { @Override public void onSuccess(Map<String, String> data) { } @Override public void onFailed() { } @Override public void onCancel() { } }); } }
23.046154
98
0.591455
eb795ff5e02ce4d98306b80bbe4302bdc406a94e
3,344
/* * Copyright 2021 EPAM Systems. * * 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.epam.digital.data.platform.excerpt.api.service; import com.epam.digital.data.platform.excerpt.api.exception.ExcerptNotFoundException; import com.epam.digital.data.platform.excerpt.api.exception.InvalidKeycloakIdException; import com.epam.digital.data.platform.excerpt.api.model.CephObjectWrapper; import com.epam.digital.data.platform.excerpt.api.model.SecurityContext; import com.epam.digital.data.platform.excerpt.api.repository.RecordRepository; import com.epam.digital.data.platform.excerpt.api.util.JwtHelper; import com.epam.digital.data.platform.excerpt.dao.ExcerptRecord; import com.epam.digital.data.platform.integration.ceph.model.CephObject; import com.epam.digital.data.platform.integration.ceph.service.CephService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.UUID; @Service public class ExcerptRetrievingService { private final Logger log = LoggerFactory.getLogger(ExcerptRetrievingService.class); private final RecordRepository recordRepository; private final JwtHelper jwtHelper; private final CephService excerptCephService; private final String bucket; public ExcerptRetrievingService( RecordRepository recordRepository, JwtHelper jwtHelper, CephService excerptCephService, @Value("${datafactory-excerpt-ceph.bucket}") String bucket) { this.recordRepository = recordRepository; this.jwtHelper = jwtHelper; this.excerptCephService = excerptCephService; this.bucket = bucket; } public CephObjectWrapper getExcerpt(UUID id, SecurityContext context) { var excerpt = recordRepository.findById(id) .orElseThrow(() -> new ExcerptNotFoundException("Record not found in DB: " + id)); validateKeycloakId(excerpt, context); log.info("Searching Excerpt in Ceph"); if (excerpt.getExcerptKey() == null) { log.error("Could not find excerpt with null Ceph key"); throw new ExcerptNotFoundException("Could not find excerpt with null Ceph key"); } CephObject cephObject = excerptCephService .get(bucket, excerpt.getExcerptKey()) .orElseThrow(() -> new ExcerptNotFoundException( "Excerpt not found in Ceph: " + excerpt.getExcerptKey())); return new CephObjectWrapper(cephObject, excerpt.getExcerptType()); } private void validateKeycloakId(ExcerptRecord excerpt, SecurityContext context) { var requestKeycloakId = jwtHelper.getKeycloakId(context.getAccessToken()); if (!excerpt.getKeycloakId().equals(requestKeycloakId)) { throw new InvalidKeycloakIdException("KeycloakId does not match one stored in database"); } } }
40.289157
95
0.764952
9f421f011a4f69345083e32fe2a575ca73d3236b
3,057
package Screens; import Minesweeper.Cell; import Lookup.*; import Minesweeper.Grid; import Minesweeper.Main; import Minesweeper.Settings; public class StartScreen extends Screen { StartScreen(Main main){ this.main = main; initialize(); } @Override protected void initialize() { Main.mainClass.image(Sprites.background, 0, 0); Main.mainClass.pushStyle(); Main.mainClass.tint(255, 150); Main.mainClass.image(Sprites.vignette, 0, 0); Main.mainClass.popStyle(); // Draw Difficulty Buttons Main.mainClass.image(Sprites.difficultyLabels[0], Cell.CELL_WIDTH*12, Cell.CELL_HEIGHT*(9), Cell.CELL_WIDTH*6, Cell.CELL_HEIGHT); Main.mainClass.image(Sprites.difficultyLabels[1], Cell.CELL_WIDTH*12, Cell.CELL_HEIGHT*(10), Cell.CELL_WIDTH*6, Cell.CELL_HEIGHT); Main.mainClass.image(Sprites.difficultyLabels[2], Cell.CELL_WIDTH*12, Cell.CELL_HEIGHT*(11), Cell.CELL_WIDTH*6, Cell.CELL_HEIGHT); } @Override public void update(){ // Draw Background Main.mainClass.image(Sprites.background, 0, 0); Main.mainClass.pushStyle(); Main.mainClass.tint(255, 150); Main.mainClass.image(Sprites.vignette, 0, 0); Main.mainClass.popStyle(); // Draw instructions] Main.mainClass.fill(150); Main.mainClass.image(Sprites.instructions, 0, 0); Main.mainClass.fill(255); // Draw Difficulty Buttons Main.mainClass.image(Sprites.difficultyLabels[0], Cell.CELL_WIDTH*12, Cell.CELL_HEIGHT*(9), Cell.CELL_WIDTH*6, Cell.CELL_HEIGHT); Main.mainClass.image(Sprites.difficultyLabels[1], Cell.CELL_WIDTH*12, Cell.CELL_HEIGHT*(10), Cell.CELL_WIDTH*6, Cell.CELL_HEIGHT); Main.mainClass.image(Sprites.difficultyLabels[2], Cell.CELL_WIDTH*12, Cell.CELL_HEIGHT*(11), Cell.CELL_WIDTH*6, Cell.CELL_HEIGHT); // Hover Arrow if(Utility.inRect(Utility.mousePos(), Cell.CELL_WIDTH * 11, Cell.CELL_HEIGHT * 9, Cell.CELL_WIDTH * 6, Cell.CELL_HEIGHT*35)){ int y = (Main.mainClass.mouseY / Cell.CELL_HEIGHT); Main.mainClass.image(Sprites.selectArrowL, Cell.CELL_WIDTH * 11, Cell.CELL_HEIGHT * y, Cell.CELL_WIDTH, Cell.CELL_HEIGHT); Main.mainClass.image(Sprites.selectArrowR, Cell.CELL_WIDTH * 18, Cell.CELL_HEIGHT * y, Cell.CELL_WIDTH, Cell.CELL_HEIGHT); } } @Override public void keyPressed(int keyCode){ } @Override public void keyReleased(int keyCode){ if(keyCode == 'Z') { boolean createGame = false; if (Utility.inRect(Utility.mousePos(), Cell.CELL_WIDTH * 11, Cell.CELL_HEIGHT * 9, Cell.CELL_WIDTH * 6, Cell.CELL_HEIGHT)){ main.grid = new Grid(Main.mainClass, Settings.EASY); createGame = true; } if (Utility.inRect(Utility.mousePos(), Cell.CELL_WIDTH * 11, Cell.CELL_HEIGHT * 10, Cell.CELL_WIDTH * 6, Cell.CELL_HEIGHT)){ main.grid = new Grid(Main.mainClass, Settings.MEDIUM); createGame = true; } if (Utility.inRect(Utility.mousePos(), Cell.CELL_WIDTH * 11, Cell.CELL_HEIGHT * 11, Cell.CELL_WIDTH * 6, Cell.CELL_HEIGHT)){ main.grid = new Grid(Main.mainClass, Settings.HARD); createGame = true; } if(createGame){ main.ChangeScreen(new GameScreen(main)); } } } }
35.546512
132
0.730782
413f129de2f2b93fd73ea8575b32b338e9fa2628
473
package icpc.tab1; import java.util.Scanner; public class cf136d2a { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int [] arr=new int[n+1]; int j=1; for(int i=1;i<=n;i++){ int x=sc.nextInt(); arr[x]=j; j++; } for(int i=1;i<=n;i++){ System.out.print(arr[i]+" "); } System.out.print("\n"); } }
20.565217
44
0.460888
7082d45d7d604520d6262d2b4d3d64729e59a0eb
733
package seatsio.events; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.Test; import seatsio.SeatsioClientTest; import java.util.Map; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; public class UpdateExtraDataTest extends SeatsioClientTest { @Test public void test() { String chartKey = createTestChart(); Event event = client.events.create(chartKey); Map<String, Object> extraData = ImmutableMap.of("foo", "bar"); client.events.updateExtraData(event.key, "A-1", extraData); assertThat(client.events.retrieveObjectInfo(event.key, "A-1").extraData).isEqualTo(extraData); } }
28.192308
102
0.735334
9fb33faeb537d835f53b2696036d7d52612fde66
4,318
package com.zyd.blog.util; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.util.StringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author yadong.zhang email:yadong.zhang0415(a)gmail.com * @website http://www.zhrey.cn * @date 2018/1/19 10:32 */ public class HtmlUtil { /** * 获取首个Element信息 * * @param htmlDocument * @param styleClassName * @return */ public static Element getFirstElementByClass(Document htmlDocument, String styleClassName) { if (htmlDocument == null || styleClassName == null || styleClassName.equals("")) { return null; } Elements elements = htmlDocument.getElementsByClass(styleClassName); if (elements == null || elements.size() <= 0) { return null; } return elements.get(0); } public static Element getFirstElementByClass(Element element, String styleClassName) { if (element == null || styleClassName == null || styleClassName.equals("")) { return null; } Elements elements = element.getElementsByClass(styleClassName); if (elements == null || elements.size() <= 0) { return null; } return elements.get(0); } /** * 获取Elements * * @param htmlDocument * @param styleClassName * @return */ public static Elements getElementsByClass(Document htmlDocument, String styleClassName) { if (htmlDocument == null || styleClassName == null || styleClassName.equals("")) { return null; } return htmlDocument.getElementsByClass(styleClassName); } /** * 获取首个Element * * @param htmlDocument * @param tag * @return */ public static Element getFirstElementByTag(Document htmlDocument, String tag) { if (htmlDocument == null || tag == null || tag.equals("")) { return null; } Elements elements = htmlDocument.getElementsByTag(tag); if (elements == null || elements.size() <= 0) { return null; } return elements.get(0); } public static Element getFirstElementByTag(Element element, String tag) { if (element == null || tag == null || tag.equals("")) { return null; } Elements elements = element.getElementsByTag(tag); if (elements == null || elements.size() <= 0) { return null; } return elements.get(0); } public static Elements getElementsByTag(Document htmlDocument, String tag) { if (htmlDocument == null || tag == null || tag.equals("")) { return null; } return htmlDocument.getElementsByTag(tag); } public static Elements getElementsByTag(Element element, String tag) { if (element == null || tag == null || tag.equals("")) { return null; } return element.getElementsByTag(tag); } /** * 获取Element * * @param htmlDocument * @param id * @return */ public static Element getElementById(Document htmlDocument, String id) { if (htmlDocument == null || id == null || id.equals("")) { return null; } return htmlDocument.getElementById(id); } /** * 替换所有标签 * * @param content * @return */ public static String html2Text(String content) { if (StringUtils.isEmpty(content)) { return null; } // 定义HTML标签的正则表达式 String regEx_html = "<[^>]+>"; content = content.replaceAll(regEx_html, "").replaceAll(" ", ""); content = content.replaceAll("&quot;", "\"") .replaceAll("&nbsp;", "") .replaceAll("&amp;", "&") .replaceAll("\n", " ") .replaceAll("&#39;", "\'") .replaceAll("&lt;", "<") .replaceAll("&gt;", ">") .replaceAll("[ \\f\\t\\v]{2,}", "\t"); String regEx = "<.+?>"; Pattern pattern = Pattern.compile(regEx); Matcher matcher = pattern.matcher(content); content = matcher.replaceAll(""); return content.trim(); } }
29.575342
96
0.560676
68b1fda5da12c527ac354d5759566fde1457ed28
9,328
/* * Created by JFormDesigner on Wed Apr 02 18:28:03 CEST 2014 */ package gameshop.advance.ui.swing.manager; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.CC; import com.jgoodies.forms.layout.FormLayout; import gameshop.advance.controller.FornitureControllerSingleton; import gameshop.advance.exceptions.ConfigurationException; import gameshop.advance.exceptions.QuantityException; import gameshop.advance.technicalservices.ExceptionHandlerSingleton; import gameshop.advance.technicalservices.LoggerSingleton; import gameshop.advance.ui.swing.UIWindowSingleton; import gameshop.advance.ui.swing.factory.UIFactory; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.rmi.RemoteException; import javax.swing.AbstractListModel; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import javax.swing.border.TitledBorder; /** * Schermata principale del Client Manager.Contiene il menu delle operazioni che può effettuare il manager. * @author Salx */ public class ManagerMenu extends JPanel { public ManagerMenu() { initComponents(); } private void fornitureActionPerformed(ActionEvent e) { try { FornitureControllerSingleton.getInstance().avviaGestioneForniture(); } catch (ConfigurationException ex) { UIWindowSingleton.getInstance().displayError(ExceptionHandlerSingleton.getInstance().getMessage(ex)); LoggerSingleton.getInstance().log(ex); } catch (RemoteException ex) { UIWindowSingleton.getInstance().displayError(ExceptionHandlerSingleton.getInstance().getMessage(ex)); LoggerSingleton.getInstance().log(ex); } catch (QuantityException ex) { UIWindowSingleton.getInstance().displayError(ExceptionHandlerSingleton.getInstance().getMessage(ex)); LoggerSingleton.getInstance().log(ex); } } private void createUIComponents() { this.fornitureButton = UIFactory.getInstance().getSimpleButton(); this.magazzinoButton = UIFactory.getInstance().getSimpleButton(); this.prezziButton = UIFactory.getInstance().getSimpleButton(); this.scontiButton = UIFactory.getInstance().getSimpleButton(); this.venditeButton = UIFactory.getInstance().getSimpleButton(); this.nullButton1 = UIFactory.getInstance().getSimpleButton(); this.nullButton2 = UIFactory.getInstance().getSimpleButton(); } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents createUIComponents(); panel1 = new JPanel(); panel2 = new JPanel(); scrollPane2 = new JScrollPane(); offertsList = new JList<>(); panel3 = new JPanel(); scrollPane1 = new JScrollPane(); lowQuantityList = new JList<>(); //======== this ======== setMinimumSize(new Dimension(720, 480)); setName("this"); //---- fornitureButton ---- fornitureButton.setText("Gestisci Forniture"); fornitureButton.setName("fornitureButton"); fornitureButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fornitureActionPerformed(e); } }); //======== panel1 ======== { panel1.setName("panel1"); //======== panel2 ======== { panel2.setBorder(new TitledBorder("Prodotti in esaurimento scorte")); panel2.setName("panel2"); //======== scrollPane2 ======== { scrollPane2.setName("scrollPane2"); //---- offertsList ---- offertsList.setModel(new AbstractListModel<String>() { String[] values = { "Prodotto 1", "Prodotto 2", "Prodotto 3", "..." }; @Override public int getSize() { return values.length; } @Override public String getElementAt(int i) { return values[i]; } }); offertsList.setFont(new Font("Tahoma", Font.PLAIN, 14)); offertsList.setName("offertsList"); scrollPane2.setViewportView(offertsList); } PanelBuilder panel2Builder = new PanelBuilder(new FormLayout( "[245px,pref]:grow", "fill:81dlu:grow"), panel2); panel2Builder.add(scrollPane2, CC.xy(1, 1)); } //======== panel3 ======== { panel3.setBorder(new TitledBorder("Attualmente in offerta")); panel3.setName("panel3"); //======== scrollPane1 ======== { scrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane1.setViewportBorder(null); scrollPane1.setName("scrollPane1"); //---- lowQuantityList ---- lowQuantityList.setModel(new AbstractListModel<String>() { String[] values = { "Prodotto 1", "Prodotto 2", "Prodotto 3", "..." }; @Override public int getSize() { return values.length; } @Override public String getElementAt(int i) { return values[i]; } }); lowQuantityList.setFont(new Font("Tahoma", Font.PLAIN, 14)); lowQuantityList.setName("lowQuantityList"); scrollPane1.setViewportView(lowQuantityList); } PanelBuilder panel3Builder = new PanelBuilder(new FormLayout( "[245px,pref]:grow", "fill:[35px,default]:grow"), panel3); panel3Builder.add(scrollPane1, CC.xy(1, 1)); } PanelBuilder panel1Builder = new PanelBuilder(new FormLayout( "[288px,pref]:grow", "fill:30dlu, $lgap, fill:30dlu:grow, 2*($lgap, fill:30dlu), $lgap, fill:30dlu:grow, $lgap, fill:30dlu"), panel1); ((FormLayout)panel1.getLayout()).setRowGroups(new int[][] {{1, 3, 5}, {7, 9, 11}}); panel1Builder.add(panel2, CC.xywh(1, 1, 1, 5)); panel1Builder.add(panel3, CC.xywh(1, 7, 1, 5)); } //---- magazzinoButton ---- magazzinoButton.setText("Controlla Magazzino"); magazzinoButton.setEnabled(false); magazzinoButton.setName("magazzinoButton"); //---- nullButton1 ---- nullButton1.setEnabled(false); nullButton1.setName("nullButton1"); //---- prezziButton ---- prezziButton.setText("Gestisci Prezzi"); prezziButton.setEnabled(false); prezziButton.setName("prezziButton"); //---- scontiButton ---- scontiButton.setText("Gestisci Sconti"); scontiButton.setEnabled(false); scontiButton.setName("scontiButton"); //---- nullButton2 ---- nullButton2.setEnabled(false); nullButton2.setName("nullButton2"); //---- venditeButton ---- venditeButton.setText("Analizza Vendite"); venditeButton.setEnabled(false); venditeButton.setName("venditeButton"); PanelBuilder builder = new PanelBuilder(new FormLayout( "$rgap, [303px,pref]:grow, $ugap, [288px,pref]:grow, $rgap", "$rgap, 6*(fill:30dlu, $lgap), fill:30dlu, $rgap, default:grow, $rgap"), this); builder.add(fornitureButton, CC.xy (2, 2)); builder.add(panel1, CC.xywh(4, 2, 1, 15)); builder.add(magazzinoButton, CC.xy (2, 4)); builder.add(nullButton1, CC.xy (2, 6)); builder.add(prezziButton, CC.xy (2, 8)); builder.add(scontiButton, CC.xy (2, 10)); builder.add(nullButton2, CC.xy (2, 12)); builder.add(venditeButton, CC.xy (2, 14)); // JFormDesigner - End of component initialization //GEN-END:initComponents } // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables private JButton fornitureButton; private JPanel panel1; private JPanel panel2; private JScrollPane scrollPane2; private JList<String> offertsList; private JPanel panel3; private JScrollPane scrollPane1; private JList<String> lowQuantityList; private JButton magazzinoButton; private JButton nullButton1; private JButton prezziButton; private JButton scontiButton; private JButton nullButton2; private JButton venditeButton; // JFormDesigner - End of variables declaration //GEN-END:variables }
39.35865
129
0.584155
24de14593cd6cb897d6d3a35158cd40e54d532ae
786
package com.konselorku.android.Fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.konselorku.android.R; public class KontakFragment extends Fragment { public KontakFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_kontak, container, false); return v; } }
25.354839
78
0.703562
ac7d839f53bb3df648af381c7a80ac71dfe1b26a
213
package com.usher.mapper; import com.usher.base.MyMapper; import com.usher.pojo.ChatMsg; import org.springframework.stereotype.Repository; @Repository public interface ChatMsgMapper extends MyMapper<ChatMsg> { }
23.666667
58
0.826291
b4a76d985ec73a6f3fceb0614bb4f2a9dd87cbaf
1,232
package de.ellpeck.actuallyadditions.common.gen.village.component.handler; import java.util.List; import java.util.Random; import de.ellpeck.actuallyadditions.common.gen.village.component.VillageComponentEngineerHouse; import net.minecraft.util.EnumFacing; import net.minecraft.world.gen.structure.StructureComponent; import net.minecraft.world.gen.structure.StructureVillagePieces; import net.minecraftforge.fml.common.registry.VillagerRegistry; public class VillageEngineerHouseHandler implements VillagerRegistry.IVillageCreationHandler { @Override public StructureVillagePieces.PieceWeight getVillagePieceWeight(Random random, int i) { return new StructureVillagePieces.PieceWeight(VillageComponentEngineerHouse.class, 10, 1); } @Override public Class<?> getComponentClass() { return VillageComponentEngineerHouse.class; } @Override public StructureVillagePieces.Village buildComponent(StructureVillagePieces.PieceWeight villagePiece, StructureVillagePieces.Start startPiece, List<StructureComponent> pieces, Random random, int p1, int p2, int p3, EnumFacing facing, int p5) { return VillageComponentEngineerHouse.buildComponent(pieces, p1, p2, p3, facing); } }
42.482759
247
0.80763
5ddb348603634b9accddfa89a7505e05e229ca28
3,588
package com.l000phone.themovietime.user; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.l000phone.themovietime.BaseActivity; import com.l000phone.themovietime.R; import com.l000phone.themovietime.user.asynctasks.LoginAsyncTask; import com.l000phone.themovietime.user.asynctasks.LoginAsyncTask.LoginCallback; import com.l000phone.themovietime.user.bean.LoginBean; import com.l000phone.themovietime.utils.LogUtil; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class LoginActivity extends BaseActivity implements View.OnClickListener,LoginCallback{ private String path = "http://api.m.mtime.cn/Mobile/Login.api"; private ImageView login_back; private EditText login_account; private EditText login_pwd; private Button login_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); } private void initView() { login_back = (ImageView) findViewById(R.id.login_back); login_account = (EditText) findViewById(R.id.login_account); login_pwd = (EditText) findViewById(R.id.login_pwd); login_btn = (Button) findViewById(R.id.login_btn); login_back.setOnClickListener(this); login_btn.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.login_back: LoginActivity.this.finish(); break; case R.id.login_btn: String account = login_account.getText().toString(); String pwd = login_pwd.getText().toString(); if (TextUtils.isEmpty(account)){ Toast.makeText(this,"请输入登录账号!",Toast.LENGTH_SHORT).show(); return; }else if (TextUtils.isEmpty(pwd)){ Toast.makeText(this,"请输入密码!",Toast.LENGTH_SHORT).show(); return; } String password = getMD5(pwd); LogUtil.log("login",password); String params = "password="+password+"&email="+account; new LoginAsyncTask(LoginActivity.this,this).execute(path,params); break; } } //将密码进行MD5加密 private String getMD5(String pwd) { StringBuffer sb = new StringBuffer(""); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pwd.getBytes()); byte[] buf = md.digest(); int index; for (int i=0;i<buf.length;i++){ index = buf[i]; if (index<0){ index+=256; } if (index<16){ sb.append("0"); } sb.append(Integer.toHexString(index)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return sb.toString(); } //登录回调 @Override public void getLogin(LoginBean bean) { boolean success = bean.isSuccess(); if (success){ Toast.makeText(this,"登录成功",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this,bean.getError(),Toast.LENGTH_SHORT).show(); } } }
30.666667
94
0.608417
dde35773a80723da8392d7297af027b94ee58474
2,322
package com.programmerdan.minecraft.simpleadminhacks.hacks.basic; import co.aikar.commands.BaseCommand; import co.aikar.commands.annotation.CommandAlias; import co.aikar.commands.annotation.CommandCompletion; import co.aikar.commands.annotation.CommandPermission; import co.aikar.commands.annotation.Description; import co.aikar.commands.annotation.Single; import co.aikar.commands.annotation.Syntax; import com.programmerdan.minecraft.simpleadminhacks.SimpleAdminHacks; import com.programmerdan.minecraft.simpleadminhacks.framework.BasicHack; import com.programmerdan.minecraft.simpleadminhacks.framework.BasicHackConfig; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import vg.civcraft.mc.civmodcore.commands.CommandManager; public final class PlayerRevive extends BasicHack { private final CommandManager commands; public PlayerRevive(final SimpleAdminHacks plugin, final BasicHackConfig config) { super(plugin, config); this.commands = new CommandManager(plugin) { @Override public void registerCommands() { registerCommand(new ReviveCommand()); } }; } @Override public void onEnable() { super.onEnable(); this.commands.init(); } @Override public void onDisable() { this.commands.reset(); super.onDisable(); } @CommandPermission("simpleadmin.revive") public static class ReviveCommand extends BaseCommand { @CommandAlias("revive|respawn|resurrect|ress") @Syntax("<player name>") @Description("Revives a player") @CommandCompletion("@players") public void revivePlayer(final CommandSender sender, @Single final String name) { final Player player = Bukkit.getPlayer(name); if (player == null) { sender.sendMessage(ChatColor.RED + "That player doesn't exist or isn't online."); return; } if (!player.isDead()) { sender.sendMessage(ChatColor.RED + "That player is not dead."); return; } final Location prevBedSpawn = player.getBedSpawnLocation(); player.setBedSpawnLocation(player.getLocation(), true); player.spigot().respawn(); player.setBedSpawnLocation(prevBedSpawn, true); player.sendMessage(ChatColor.YELLOW + "You have been revived."); sender.sendMessage(player.getName() + " revived."); } } }
31.378378
85
0.767442
7f1bfdff04c469652fb968420458f0d37374f0e0
3,418
/* * 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.borisfarber.instasearch.contollers; import com.borisfarber.instasearch.models.formats.BinaryFileModel; import com.borisfarber.instasearch.models.search.Search; import com.borisfarber.instasearch.ui.HexPanel; import dorkbox.notify.Notify; import dorkbox.notify.Pos; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.concurrent.ThreadPoolExecutor; public class FileView { private FileView() { } public static void viewFile(Search search, String filename, Integer position, ThreadPoolExecutor previewExecutor, JTextPane previewTextPane, File file) { Path viewPath = search.extractSelectedFile(filename); if (viewPath == null) { // garbage files return; } if (PathMatchers.SOURCE_OR_TEXT_MATCHER.matches(viewPath)) { showFileInEditor(viewPath, position); return; } if (PathMatchers.BINARY_MATCHER.matches(viewPath)) { previewExecutor.execute(() -> { BinaryFileModel fileModel = new BinaryFileModel(viewPath, file); showFile(previewTextPane, fileModel.getFileName(), fileModel.getText()); }); return; } HexPanel.createJFrameWithHexPanel(viewPath.toFile()); } private static void showFile(JTextPane previewTextPane, File file, String text) { Runnable runnable = () -> { if(text != null) { if(text.length() > 150) { previewTextPane.setText(text.substring(0, 150) + "\n..."); } else { previewTextPane.setText(text); } } showFileInEditor(file.toPath(), 0); }; SwingUtilities.invokeLater(runnable); } private static void showFileInEditor(Path path, int line) { try { Desktop desktop = Desktop.getDesktop(); desktop.open(new File(path.toString())); if(line > 0) { Notify.TITLE_TEXT_FONT = "Source Code Pro BOLD 22"; Notify.MAIN_TEXT_FONT = "Source Code Pro BOLD 22"; Notify.create() .title("Insta Search") .text("Line " + line) .hideCloseButton() .position(Pos.TOP_RIGHT) .darkStyle() .showInformation(); } } catch (IOException ioException) { ioException.printStackTrace(); } } }
34.18
89
0.565535
4552d34a32b7d7c88d673e801eb2237a3450d239
2,406
/* * FILE: RtreePartitioning * Copyright (c) 2015 - 2018 GeoSpark Development Team * * MIT License * * 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 org.datasyslab.geospark.spatialPartitioning; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.index.strtree.STRtree; import java.io.Serializable; import java.util.ArrayList; import java.util.List; // TODO: Auto-generated Javadoc /** * The Class RtreePartitioning. */ public class RtreePartitioning implements Serializable { /** * The grids. */ final List<Envelope> grids = new ArrayList<>(); /** * Instantiates a new rtree partitioning. * * @param samples the sample list * @param partitions the partitions * @throws Exception the exception */ public RtreePartitioning(List<Envelope> samples, int partitions) throws Exception { STRtree strtree = new STRtree(samples.size() / partitions); for (Envelope sample : samples) { strtree.insert(sample, sample); } List<Envelope> envelopes = strtree.queryBoundary(); for (Envelope envelope : envelopes) { grids.add(envelope); } } /** * Gets the grids. * * @return the grids */ public List<Envelope> getGrids() { return this.grids; } }
29.703704
81
0.691189
25758b17a72dcbacd2492a4883794b15c4a00608
390
package ru.javabegin.library; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(basePackages = {"ru.javabegin.library"}) public class ServletInitializer extends SpringBootServletInitializer { }
30
73
0.858974
a45cff27682b1d9ab69593418fcbe79a3507e6b2
301
/* * 文件名:IUserLogic.java * 版权:Copyright by http://nercel.ccnu.edu.cn/ * 描述: * 修改人:longyunxiang * 修改时间:2016年3月28日 * 跟踪单号: * 修改单号: * 修改内容: */ package com.yllyx.clubs.logic.user; public interface IUserLogic { boolean invalidByNamePasswd(String name, String passwd); }
15.05
61
0.644518
04036bf92fc40004ea316206231f9c40604a0b44
915
import java.util.Stack; public class S0682BaseballGame { public int calPoints(String[] ops) { Stack<Integer> vals = new Stack<>(); int sum = 0; for (int i = 0; i < ops.length; i++) { String op = ops[i]; if (op.equals("+")) { int v1 = vals.pop(); int v2 = vals.pop(); vals.push(v2); vals.push(v1); int s = v1+v2; sum += s; vals.push(s); } else if (op.equals("D")) { int d = vals.peek()*2; sum += d; vals.push(d); } else if (op.equals("C")) { int c = vals.pop(); sum -= c; } else { int v = Integer.valueOf(op); vals.push(v); sum += v; } } return sum; } }
26.911765
46
0.35847
6bfc23d5e8860b932c06a309c48ae6b31a939328
130
package com.lqr.wechat.ui.view; import android.widget.EditText; public interface IPostScriptAtView { EditText getEtMsg(); }
16.25
36
0.769231
6980a6ba60eb84c76d7ad41413cbe22257be256c
2,755
package com.shushanfx.zconfig.client.config; import com.shushanfx.zconfig.client.ZKConfig; import com.shushanfx.zconfig.client.ZKConfigParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * 字符串 * Created by shushanfx on 2017/6/12. */ public class ZKPropertiesConfig extends AbstractZKConfig implements ZKConfigParser { private static final Logger logger = LoggerFactory.getLogger(ZKPropertiesConfig.class); Properties properties = null; @Override public Object getValue(String path) { return properties.get(path); } @Override public Integer getInteger(String path) { String value = properties.getProperty(path); if (value != null) { try { return Integer.parseInt(value); } catch (Exception e) { logger.error("Can not parse " + value + " to int.", e); } } return null; } @Override public Boolean getBoolean(String path) { String value = properties.getProperty(path); if (value != null) { if ("1".equals(value) || "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) { return true; } else if ("0".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value) || "off".equalsIgnoreCase(value)) return false; } return null; } @Override public String getString(String path) { return properties.getProperty(path); } @Override public Double getDouble(String path) { String value = getString(path); if (value != null) { try { return Double.parseDouble(value); } catch (Exception e) { logger.error("Can not parse " + value + " to double.", e); } } return null; } @Override public List getList(String path) { String value = getString(path); if (value != null) { String[] values = value.split("\\|"); List list = new ArrayList(); for(String item: values){ list.add(item); } return list; } return null; } @Override public ZKConfig parse(String content) { properties = new Properties(); if (content != null) { try { properties.load(new StringReader(content)); } catch (Exception e) { logger.error("parse error!", e); } } return this; } }
27.55
91
0.550998
cafc07146e44f78f3dcdd74585ccd31124cbe49c
9,210
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.adrianjg.dlab; public final class R { public static final class attr { } public static final class color { public static final int black=0x7f060000; public static final int gray=0x7f060002; public static final int light_gray=0x7f060003; public static final int overlay_bottom_bar_background=0x7f060006; public static final int overlay_bottom_bar_separators=0x7f060005; public static final int semi_transparent_black=0x7f060004; public static final int white=0x7f060001; } public static final class dimen { /** Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f070009; public static final int menu_activities_list_padding_left=0x7f070002; public static final int menu_activities_list_padding_top_down=0x7f070003; public static final int menu_entries_sides_padding=0x7f070006; public static final int menu_entries_text=0x7f070004; public static final int menu_entries_title=0x7f070005; public static final int menu_entries_top_down_padding=0x7f070007; public static final int menu_entries_top_down_radio_padding=0x7f070008; public static final int menu_title=0x7f070000; public static final int menu_title_padding=0x7f070001; } public static final class drawable { public static final int bg00=0x7f020000; public static final int bg70=0x7f020001; public static final int button_close_normal=0x7f020002; public static final int button_close_pressed=0x7f020003; public static final int camera_button_background=0x7f020004; public static final int close_button_background=0x7f020005; public static final int ic_launcher=0x7f020006; public static final int icon=0x7f020007; public static final int icon_01=0x7f020008; public static final int icon_02=0x7f020009; public static final int icon_03=0x7f02000a; public static final int icon_camera_normal=0x7f02000b; public static final int icon_camera_pressed=0x7f02000c; public static final int icon_plus_normal=0x7f02000d; public static final int icon_plus_pressed=0x7f02000e; public static final int logo=0x7f02000f; public static final int new_target_button_background=0x7f020010; public static final int vuforia_splash=0x7f020011; } public static final class id { public static final int activities_list_title=0x7f080000; public static final int bottom_bar=0x7f08000c; public static final int byte_count=0x7f080003; public static final int camera_button=0x7f08000d; public static final int camera_overlay_layout=0x7f080001; public static final int leftMargin=0x7f080007; public static final int loading_indicator=0x7f080002; public static final int loading_layout=0x7f08000b; public static final int logo_image=0x7f080013; public static final int loupe=0x7f080008; public static final int loupeLayout=0x7f080006; public static final int menu_group_title=0x7f08000e; public static final int menu_group_title_divider=0x7f08000f; public static final int read=0x7f080004; public static final int rightMargin=0x7f080009; public static final int settings_menu=0x7f080010; public static final int settings_menu_title=0x7f080011; public static final int splash_image=0x7f080012; public static final int topMargin=0x7f080005; public static final int wordList=0x7f08000a; } public static final class layout { public static final int activities_list=0x7f030000; public static final int activities_list_text_view=0x7f030001; public static final int camera_overlay=0x7f030002; public static final int camera_overlay_textreco=0x7f030003; public static final int camera_overlay_udt=0x7f030004; public static final int sample_app_menu_group=0x7f030005; public static final int sample_app_menu_group_divider=0x7f030006; public static final int sample_app_menu_group_radio_button=0x7f030007; public static final int sample_app_menu_layer=0x7f030008; public static final int splash_screen=0x7f030009; } public static final class string { public static final int UPDATE_ERROR_AUTHORIZATION_FAILED_DESC=0x7f04000f; public static final int UPDATE_ERROR_AUTHORIZATION_FAILED_TITLE=0x7f040006; public static final int UPDATE_ERROR_BAD_FRAME_QUALITY_DESC=0x7f040016; public static final int UPDATE_ERROR_BAD_FRAME_QUALITY_TITLE=0x7f04000d; public static final int UPDATE_ERROR_NO_NETWORK_CONNECTION_DESC=0x7f040011; public static final int UPDATE_ERROR_NO_NETWORK_CONNECTION_TITLE=0x7f040008; public static final int UPDATE_ERROR_PROJECT_SUSPENDED_DESC=0x7f040010; public static final int UPDATE_ERROR_PROJECT_SUSPENDED_TITLE=0x7f040007; public static final int UPDATE_ERROR_REQUEST_TIMEOUT_DESC=0x7f040015; public static final int UPDATE_ERROR_REQUEST_TIMEOUT_TITLE=0x7f04000c; public static final int UPDATE_ERROR_SERVICE_NOT_AVAILABLE_DESC=0x7f040012; public static final int UPDATE_ERROR_SERVICE_NOT_AVAILABLE_TITLE=0x7f040009; public static final int UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE_DESC=0x7f040014; public static final int UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE_TITLE=0x7f04000b; public static final int UPDATE_ERROR_UNKNOWN_DESC=0x7f040017; public static final int UPDATE_ERROR_UNKNOWN_TITLE=0x7f04000e; public static final int UPDATE_ERROR_UPDATE_SDK_DESC=0x7f040013; public static final int UPDATE_ERROR_UPDATE_SDK_TITLE=0x7f04000a; public static final int activities_list_empty=0x7f040004; public static final int activities_list_title_string=0x7f040003; public static final int app_description=0x7f040001; public static final int app_name=0x7f040000; public static final int button_OK=0x7f040005; public static final int button_start=0x7f040002; public static final int content_desc_camera_button=0x7f040018; public static final int menu_back=0x7f04001c; public static final int menu_button_blue=0x7f04002a; public static final int menu_button_green=0x7f04002c; public static final int menu_button_red=0x7f040029; public static final int menu_button_yellow=0x7f04002b; public static final int menu_camera=0x7f040026; public static final int menu_camera_back=0x7f040028; public static final int menu_camera_front=0x7f040027; public static final int menu_character_mode=0x7f04001e; public static final int menu_contAutofocus=0x7f040022; public static final int menu_contAutofocus_error_off=0x7f040024; public static final int menu_contAutofocus_error_on=0x7f040023; public static final int menu_datasets=0x7f040025; public static final int menu_extended_tracking=0x7f04001d; public static final int menu_flash=0x7f04001f; public static final int menu_flash_error_off=0x7f040021; public static final int menu_flash_error_on=0x7f040020; public static final int overlay_build_target_help=0x7f040019; public static final int splash_screen_description=0x7f04002d; public static final int target_quality_error_desc=0x7f04001b; public static final int target_quality_error_title=0x7f04001a; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f050000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f050001; public static final int SampleAppsTheme=0x7f050002; } }
53.546512
91
0.74658
102731a9d520a9fdcf5bcb2c42a47b7b7b28a767
938
public class W_Machine extends Home { private String en_class; private float storage; private int rpm; //set public void setstorage(float storage){ this.storage=storage; } public void setrpm(int rpm){ this.rpm=rpm; } //get public float getstorage(){ return storage; } public int getrpm(){ return rpm; } //constructor here: public W_Machine(String name,int age,String manufacturer,double price,String en_class,float storage,int rpm) { super(name,age,manufacturer,price); seten_class(en_class); setstorage(storage); setrpm(rpm); } //toString public String toString() { return "\nDevice chracteristics:\n"+"\nModel name:"+this.getname()+"\nProduction year:"+this.getage()+"\nManufacturer name:"+this.getmanufacturer()+"\nPrice:"+this.getprice()+"Energy Class:"+en_class+"\nStorage:"+storage+"\nRounds Per Minute:"+rpm ; } }
26.055556
256
0.660981
61e941e22778f2d5125de565f3840508c13198d4
961
package com.cjm.wcpe.sample.server; import com.cjm.wcpe.sdk.mobile.server.BaseWcpeServer; import java.util.ArrayList; import java.util.List; /** * Created by jiaminchen on 16/3/18. */ public class TestShortServer extends BaseWcpeServer { private final static String TAG = "Wcpe.TestShortServer"; public final static int TEST_SMALL_FUN_ID = 0x01000; public final static int TEST_LARGE_FUN_ID = 0x02000; @Override public List<Integer> getFunIdList() { ArrayList<Integer> funIdList = new ArrayList<>(); funIdList.add(TEST_SMALL_FUN_ID); funIdList.add(TEST_LARGE_FUN_ID); return funIdList; } @Override public byte[] handleData(int funId, byte[] data) { switch (funId) { case TEST_LARGE_FUN_ID: return new byte[1024 * 4000]; case TEST_SMALL_FUN_ID: return "response test string".getBytes(); } return null; } }
27.457143
61
0.654527
d5f0e0bb1b546f36fa561023fd5b26265a3216bc
3,981
package uk.gov.cshr.service; import org.hamcrest.MatcherAssert; import org.junit.Test; import org.mockito.ArgumentCaptor; import uk.gov.cshr.domain.Invite; import uk.gov.cshr.domain.InviteStatus; import uk.gov.cshr.domain.factory.InviteFactory; import uk.gov.cshr.repository.InviteRepository; import uk.gov.service.notify.NotificationClientException; import java.time.LocalDate; import java.util.Date; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.CoreMatchers.equalTo; import static org.mockito.Mockito.*; public class InviteServiceTest { private static final String EMAIL = "[email protected]"; private final String govNotifyTemplateId = "template-id"; private final int validityInSeconds = 259200; private final String signupUrlFormat = "invite-url"; private InviteRepository inviteRepository = mock(InviteRepository.class); private InviteFactory inviteFactory = mock(InviteFactory.class); private NotifyService notifyService = mock(NotifyService.class); private InviteService inviteService = new InviteService(govNotifyTemplateId, validityInSeconds, signupUrlFormat, notifyService, inviteRepository, inviteFactory); @Test public void updateInviteByCodeShouldUpdateStatusCorrectly() { final String code = "123abc"; Invite invite = new Invite(); invite.setStatus(InviteStatus.PENDING); invite.setCode(code); when(inviteRepository.findByCode(code)) .thenReturn(invite); inviteService.updateInviteByCode(code, InviteStatus.ACCEPTED); ArgumentCaptor<Invite> inviteArgumentCaptor = ArgumentCaptor.forClass(Invite.class); verify(inviteRepository).save(inviteArgumentCaptor.capture()); invite = inviteArgumentCaptor.getValue(); MatcherAssert.assertThat(invite.getCode(), equalTo(code)); MatcherAssert.assertThat(invite.getStatus(), equalTo(InviteStatus.ACCEPTED)); } @Test public void inviteCodesLessThan24HrsShouldNotBeExpired() { final String code = "123abc"; Invite invite = new Invite(); invite.setStatus(InviteStatus.PENDING); invite.setCode(code); invite.setInvitedAt(new Date(2323223232L)); when(inviteRepository.findByCode(code)) .thenReturn(invite); MatcherAssert.assertThat(inviteService.isCodeExpired(code), equalTo(true)); } @Test public void inviteCodesOlderThanValidityDurationShouldBeExpired() { final String code = "123abc"; Invite invite = new Invite(); invite.setStatus(InviteStatus.PENDING); invite.setCode(code); invite.setInvitedAt(new Date(new Date().getTime() - 1000 * 60 * 60 * 24)); when(inviteRepository.findByCode(code)) .thenReturn(invite); MatcherAssert.assertThat(inviteService.isCodeExpired(code), equalTo(false)); } @Test public void shouldSendAndSaveSelfSignupInvite() throws NotificationClientException { String email = "[email protected]"; String code = "invite-code"; Invite invite = new Invite(); invite.setForEmail(email); invite.setCode(code); when(inviteFactory.createSelfSignUpInvite(email)).thenReturn(invite); inviteService.sendSelfSignupInvite(email, true); verify(notifyService).notify(email, code, govNotifyTemplateId, signupUrlFormat); verify(inviteRepository).save(invite); } @Test public void shouldReturnTrueIfEmailInvited() { when(inviteRepository.existsByForEmailAndInviterIdIsNotNull(EMAIL)).thenReturn(true); assertTrue(inviteService.isEmailInvited(EMAIL)); } @Test public void shouldReturnFalseIfEmailNotInvited() { when(inviteRepository.existsByForEmailAndInviterIdIsNotNull(EMAIL)).thenReturn(false); assertFalse(inviteService.isEmailInvited(EMAIL)); } }
35.864865
99
0.721929
e30e09bda7e7f52895410784c932a321a8892126
14,891
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations; import com.orientechnologies.common.concur.lock.OLockException; import com.orientechnologies.common.concur.lock.OOneEntryPerKeyLockManager; import com.orientechnologies.common.exception.OException; import com.orientechnologies.common.function.TxConsumer; import com.orientechnologies.common.function.TxFunction; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.exception.ODatabaseException; import com.orientechnologies.orient.core.exception.OStorageException; import com.orientechnologies.orient.core.storage.cache.OReadCache; import com.orientechnologies.orient.core.storage.cache.OWriteCache; import com.orientechnologies.orient.core.storage.impl.local.AtomicOperationIdGen; import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage; import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.operationsfreezer.OperationsFreezer; import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurableComponent; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OLogSequenceNumber; import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWriteAheadLog; import java.io.IOException; import java.util.Iterator; import java.util.Objects; /** * @author Andrey Lomakin (a.lomakin-at-orientdb.com) * @since 12/3/13 */ public class OAtomicOperationsManager { private final ThreadLocal<OAtomicOperation> currentOperation = new ThreadLocal<>(); private final OAbstractPaginatedStorage storage; private final OWriteAheadLog writeAheadLog; private final OOneEntryPerKeyLockManager<String> lockManager = new OOneEntryPerKeyLockManager<>( true, -1, OGlobalConfiguration.COMPONENTS_LOCK_CACHE.getValueAsInteger()); private final OReadCache readCache; private final OWriteCache writeCache; private final Object segmentLock = new Object(); private final AtomicOperationIdGen idGen; private final boolean trackPageOperations; private final int operationsCacheLimit; private final OperationsFreezer atomicOperationsFreezer = new OperationsFreezer(); private final OperationsFreezer componentOperationsFreezer = new OperationsFreezer(); private final AtomicOperationsTable atomicOperationsTable; public OAtomicOperationsManager( OAbstractPaginatedStorage storage, boolean trackPageOperations, int operationsCacheLimit, AtomicOperationsTable atomicOperationsTable) { this.storage = storage; this.writeAheadLog = storage.getWALInstance(); this.readCache = storage.getReadCache(); this.writeCache = storage.getWriteCache(); this.trackPageOperations = trackPageOperations; this.operationsCacheLimit = operationsCacheLimit; this.idGen = storage.getIdGen(); this.atomicOperationsTable = atomicOperationsTable; } public OAtomicOperation startAtomicOperation(final byte[] metadata) throws IOException { OAtomicOperation operation = currentOperation.get(); if (operation != null) { throw new OStorageException("Atomic operation already started"); } atomicOperationsFreezer.startOperation(); final OLogSequenceNumber lsn; final long activeSegment; final long unitId; // transaction id and id of active segment should grow synchronously to maintain correct size of // WAL synchronized (segmentLock) { unitId = idGen.nextId(); activeSegment = writeAheadLog.activeSegment(); } atomicOperationsTable.startOperation(unitId, activeSegment); if (metadata != null) { lsn = writeAheadLog.logAtomicOperationStartRecord(true, unitId, metadata); } else { lsn = writeAheadLog.logAtomicOperationStartRecord(true, unitId); } if (!trackPageOperations) { operation = new OAtomicOperationBinaryTracking(lsn, unitId, readCache, writeCache, storage.getId()); } else { operation = new OAtomicOperationPageOperationsTracking( readCache, writeCache, writeAheadLog, unitId, operationsCacheLimit, lsn); } currentOperation.set(operation); return operation; } public <T> T calculateInsideAtomicOperation(final byte[] metadata, final TxFunction<T> function) throws IOException { Throwable error = null; final OAtomicOperation atomicOperation = startAtomicOperation(metadata); try { return function.accept(atomicOperation); } catch (Exception e) { error = e; throw OException.wrapException( new OStorageException( "Exception during execution of atomic operation inside of storage " + storage.getName()), e); } finally { endAtomicOperation(error); } } public void executeInsideAtomicOperation(final byte[] metadata, final TxConsumer consumer) throws IOException { Throwable error = null; final OAtomicOperation atomicOperation = startAtomicOperation(metadata); try { consumer.accept(atomicOperation); } catch (Exception e) { error = e; throw OException.wrapException( new OStorageException( "Exception during execution of atomic operation inside of storage " + storage.getName()), e); } finally { endAtomicOperation(error); } } public void executeInsideComponentOperation( final OAtomicOperation atomicOperation, final ODurableComponent component, final TxConsumer consumer) { executeInsideComponentOperation(atomicOperation, component.getLockName(), consumer); } public void executeInsideComponentOperation( final OAtomicOperation atomicOperation, final String lockName, final TxConsumer consumer) { Objects.requireNonNull(atomicOperation); startComponentOperation(atomicOperation, lockName); try { consumer.accept(atomicOperation); } catch (Exception e) { throw OException.wrapException( new OStorageException( "Exception during execution of component operation inside component " + lockName + " in storage " + storage.getName()), e); } finally { endComponentOperation(atomicOperation); } } public boolean tryExecuteInsideComponentOperation( final OAtomicOperation atomicOperation, final ODurableComponent component, final TxConsumer consumer) { return tryExecuteInsideComponentOperation(atomicOperation, component.getLockName(), consumer); } private boolean tryExecuteInsideComponentOperation( final OAtomicOperation atomicOperation, final String lockName, final TxConsumer consumer) { Objects.requireNonNull(atomicOperation); final boolean result = tryStartComponentOperation(atomicOperation, lockName); if (!result) { return false; } try { consumer.accept(atomicOperation); } catch (Exception e) { throw OException.wrapException( new OStorageException( "Exception during execution of component operation inside of storage " + storage.getName()), e); } finally { endComponentOperation(atomicOperation); } return true; } public <T> T calculateInsideComponentOperation( final OAtomicOperation atomicOperation, final ODurableComponent component, final TxFunction<T> function) { return calculateInsideComponentOperation(atomicOperation, component.getLockName(), function); } public <T> T calculateInsideComponentOperation( final OAtomicOperation atomicOperation, final String lockName, final TxFunction<T> function) { Objects.requireNonNull(atomicOperation); startComponentOperation(atomicOperation, lockName); try { return function.accept(atomicOperation); } catch (Exception e) { throw OException.wrapException( new OStorageException( "Exception during execution of component operation inside of storage " + storage.getName()), e); } finally { endComponentOperation(atomicOperation); } } private void startComponentOperation( final OAtomicOperation atomicOperation, final String lockName) { acquireExclusiveLockTillOperationComplete(atomicOperation, lockName); atomicOperation.incrementComponentOperations(); componentOperationsFreezer.startOperation(); } private void endComponentOperation(final OAtomicOperation atomicOperation) { atomicOperation.decrementComponentOperations(); componentOperationsFreezer.endOperation(); } public long freezeComponentOperations() { return componentOperationsFreezer.freezeOperations(null, null); } public void releaseComponentOperations(final long freezeId) { componentOperationsFreezer.releaseOperations(freezeId); } private boolean tryStartComponentOperation( final OAtomicOperation atomicOperation, final String lockName) { final boolean result = tryAcquireExclusiveLockTillOperationComplete(atomicOperation, lockName); if (!result) { return false; } atomicOperation.incrementComponentOperations(); return true; } private boolean tryAcquireExclusiveLockTillOperationComplete( OAtomicOperation operation, String lockName) { if (operation.containsInLockedObjects(lockName)) { return true; } try { lockManager.acquireLock(lockName, OOneEntryPerKeyLockManager.LOCK.EXCLUSIVE, 1); } catch (OLockException e) { return false; } operation.addLockedObject(lockName); componentOperationsFreezer.startOperation(); return true; } public void alarmClearOfAtomicOperation() { final OAtomicOperation current = currentOperation.get(); if (current != null) { currentOperation.set(null); } } public long freezeAtomicOperations(Class<? extends OException> exceptionClass, String message) { return atomicOperationsFreezer.freezeOperations(exceptionClass, message); } public void releaseAtomicOperations(long id) { atomicOperationsFreezer.releaseOperations(id); } public final OAtomicOperation getCurrentOperation() { return currentOperation.get(); } /** Ends the current atomic operation on this manager. */ public void endAtomicOperation(final Throwable error) throws IOException { final OAtomicOperation operation = currentOperation.get(); if (operation == null) { OLogManager.instance().error(this, "There is no atomic operation active", null); throw new ODatabaseException("There is no atomic operation active"); } try { storage.moveToErrorStateIfNeeded(error); if (error != null) { operation.rollbackInProgress(); } try { final OLogSequenceNumber lsn; if (trackPageOperations) { lsn = operation.commitChanges(writeAheadLog); } else if (!operation.isRollbackInProgress()) { lsn = operation.commitChanges(writeAheadLog); } else { lsn = null; } final long operationId = operation.getOperationUnitId(); if (error != null) { atomicOperationsTable.rollbackOperation(operationId); } else { atomicOperationsTable.commitOperation(operationId); writeAheadLog.addEventAt(lsn, () -> atomicOperationsTable.persistOperation(operationId)); } } finally { final Iterator<String> lockedObjectIterator = operation.lockedObjects().iterator(); try { while (lockedObjectIterator.hasNext()) { final String lockedObject = lockedObjectIterator.next(); lockedObjectIterator.remove(); lockManager.releaseLock(this, lockedObject, OOneEntryPerKeyLockManager.LOCK.EXCLUSIVE); } } finally { currentOperation.set(null); } } } finally { atomicOperationsFreezer.endOperation(); } } public void ensureThatComponentsUnlocked() { final OAtomicOperation operation = currentOperation.get(); if (operation != null) { final Iterator<String> lockedObjectIterator = operation.lockedObjects().iterator(); while (lockedObjectIterator.hasNext()) { final String lockedObject = lockedObjectIterator.next(); lockedObjectIterator.remove(); lockManager.releaseLock(this, lockedObject, OOneEntryPerKeyLockManager.LOCK.EXCLUSIVE); } } } /** * Acquires exclusive lock with the given lock name in the given atomic operation. * * @param operation the atomic operation to acquire the lock in. * @param lockName the lock name to acquire. */ public void acquireExclusiveLockTillOperationComplete( OAtomicOperation operation, String lockName) { storage.checkErrorState(); if (operation.containsInLockedObjects(lockName)) { return; } lockManager.acquireLock(lockName, OOneEntryPerKeyLockManager.LOCK.EXCLUSIVE); operation.addLockedObject(lockName); } /** * Acquires exclusive lock in the active atomic operation running on the current thread for the * {@code durableComponent}. */ public void acquireExclusiveLockTillOperationComplete(ODurableComponent durableComponent) { final OAtomicOperation operation = currentOperation.get(); assert operation != null; acquireExclusiveLockTillOperationComplete(operation, durableComponent.getLockName()); } public void acquireReadLock(ODurableComponent durableComponent) { assert durableComponent.getLockName() != null; storage.checkErrorState(); lockManager.acquireLock(durableComponent.getLockName(), OOneEntryPerKeyLockManager.LOCK.SHARED); } public void releaseReadLock(ODurableComponent durableComponent) { assert durableComponent.getName() != null; assert durableComponent.getLockName() != null; lockManager.releaseLock( this, durableComponent.getLockName(), OOneEntryPerKeyLockManager.LOCK.SHARED); } }
35.20331
123
0.726143
5c119e38d25a1d3856f48272714d0079964fc474
1,792
package org.infinispan.xsite; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.concurrent.CompletionStage; import org.infinispan.commands.VisitableCommand; import org.infinispan.factories.ComponentRegistry; import org.infinispan.util.ByteString; /** * RPC command to replicate cache operations (such as put, remove, replace, etc.) to the backup site. * * @author Pedro Ruivo * @since 7.0 */ public class SingleXSiteRpcCommand extends XSiteReplicateCommand { public static final byte COMMAND_ID = 40; private VisitableCommand command; public SingleXSiteRpcCommand(ByteString cacheName, VisitableCommand command) { super(COMMAND_ID, cacheName); this.command = command; } public SingleXSiteRpcCommand(ByteString cacheName) { this(cacheName, null); } public SingleXSiteRpcCommand() { this(null); } @Override public CompletionStage<Void> performInLocalSite(BackupReceiver receiver, boolean preserveOrder) { return receiver.handleRemoteCommand(command, preserveOrder); } @Override public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable { throw new UnsupportedOperationException(); } @Override public void writeTo(ObjectOutput output) throws IOException { output.writeObject(command); } @Override public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { command = (VisitableCommand) input.readObject(); } @Override public boolean isReturnValueExpected() { return command.isReturnValueExpected(); } @Override public String toString() { return "SingleXSiteRpcCommand{" + "command=" + command + '}'; } }
26.352941
101
0.728795
95614af19bc0d281fb0102368606e322c0f51051
2,564
package me.bscal.game.GUI; import java.awt.Graphics; import java.awt.event.MouseEvent; import me.bscal.game.Game; import me.bscal.game.graphics.Rectangle; import me.bscal.game.graphics.Render; import me.bscal.game.listeners.MouseClickListener; import me.bscal.game.sprites.Sprite; public abstract class GUIButton extends GUIComponent implements GUIListener{ public enum Action { NONE, EXIT, HIDE, TEXT, ACTION } private Sprite sprite; public boolean isFixed; protected boolean clicked = false; protected boolean inside = false; protected int x, y; public GUIButton(Sprite sprite, Rectangle rect, boolean fixed) { super(rect.x, rect.y, rect.width, rect.height); this.sprite = sprite; this.isFixed = fixed; } public void render(Render renderer, int xZoom, int yZoom) { renderer.renderSprite(sprite, rect.x, rect.y, xZoom, yZoom, isFixed); } public void render(Render renderer, int xZoom, int yZoom, Rectangle interfaceRectangle) { if(sprite != null) { renderer.renderSprite(sprite, rect.x + interfaceRectangle.x, rect.y + interfaceRectangle.y, xZoom, yZoom, isFixed); } else { renderer.renderRectangle(rect, xZoom, yZoom, isFixed); } } public void render(Render renderer, Graphics g, int xZoom, int yZoom) { renderer.renderRectangle(rect, 1, 1, isFixed); if(sprite != null) { renderer.renderSprite(sprite, rect.x, rect.y, xZoom, yZoom, isFixed); } } public void update(Game game) { if(isFixed) { rect.x = parent.rect.width/2 + x; rect.y = parent.rect.height + y; } Rectangle mouse = new Rectangle((int) MouseClickListener.x, (int) MouseClickListener.y, 1, 1); if(clicked && MouseClickListener.button == MouseEvent.NOBUTTON) { released(); clicked = false; } if(mouse.intersects(rect)) { if(!inside) { hovered(); inside = true; } } else { if(!inside) { exited(); } inside = false; } } public boolean handleMouseClick(Rectangle mouseRectangle, Rectangle Camera, int xZoom, int yZoom) { if(mouseRectangle.intersects(rect)) { clicked(); clicked = true; return clicked; } clicked = false; return clicked; } public Sprite getSprite() { if(sprite != null) { return sprite; } return null; } public Rectangle getRect() { return rect; } public boolean isFixed() { return isFixed; } public String toString() { return "[" + rect.x + " , " + rect.y + " , " + rect.width + " , " + rect.height + "]"; } }
24.653846
119
0.655226
a521f3476c94c7025a811162ab3a964f052c22fc
2,904
package de.notecho.spotify.bot.modules.commands; import com.neovisionaries.i18n.CountryCode; import de.notecho.spotify.bot.instance.BotInstance; import de.notecho.spotify.bot.modules.Command; import de.notecho.spotify.database.user.entities.module.Module; import de.notecho.spotify.database.user.entities.module.ModuleEntry; import de.notecho.spotify.module.ModuleType; import de.notecho.spotify.module.UserLevel; import de.notecho.spotify.utils.SpotifyUtils; import lombok.SneakyThrows; import se.michaelthelin.spotify.model_objects.specification.Track; import java.util.Arrays; public class PlayCommand extends Command { public PlayCommand(Module module, BotInstance root) { super(module, root); } @SneakyThrows @Override public void exec(String userName, String id, UserLevel userLevel, String[] args) { ModuleEntry sPlay = getModule().getEntry("sPlay"); if (!userLevel.isHigherOrEquals(sPlay.getUserLevel())) { sendMessage(getModule(ModuleType.SYSTEM).getEntry("noPerms"), "$USER", userName, "$ROLE", sPlay.getUserLevel().getPrettyName()); return; } if (args.length >= 1) { StringBuilder searchQuery = new StringBuilder(); for (int i = 0; i < args.length; i++) if (i != 0) searchQuery.append(" "); else searchQuery.append(args[i]); Track track = SpotifyUtils.getTrackFromString(searchQuery.toString(), getRoot().getSpotifyApi()); if (track == null) { sendMessage(getModule().getEntry("notFound"), "$USER", userName); return; } CountryCode country = getRoot().getSpotifyApi().getCurrentUsersProfile().build().execute().getCountry(); if (Arrays.stream(track.getAvailableMarkets()).noneMatch(countryCode -> countryCode.equals(country != null ? country : CountryCode.US))) { sendMessage(getModule(ModuleType.SONGREQUEST).getEntry("notAvailable"), "$USER", userName, "$SONG", track.getName()); return; } getRoot().getSpotifyApi().addItemToUsersPlaybackQueue(track.getUri()).build().execute(); getRoot().getSpotifyApi().skipUsersPlaybackToNextTrack().build().execute(); sendMessage(sPlay, "$USER", userName, "$SONG", track.getName(), "$ARTISTS", SpotifyUtils.getArtists(track)); return; } getRoot().getSpotifyApi().startResumeUsersPlayback().build().execute(); String uri = SpotifyUtils.getUriFromJson(getRoot().getSpotifyApi().getUsersCurrentlyPlayingTrack().build().getJson()); Track track = getRoot().getSpotifyApi().getTrack(SpotifyUtils.getIdFromUri(uri)).build().execute(); sendMessage(sPlay, "$USER", userName, "$SONG", track.getName(), "$ARTISTS", SpotifyUtils.getArtists(track)); } }
50.068966
150
0.662534
d9bd96d90621eaace9db5c92acfb387df02df3c3
2,506
package com.sequenceiq.it.cloudbreak.actor; import java.util.Base64; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.sequenceiq.it.TestParameter; import com.sequenceiq.it.cloudbreak.CloudbreakTest; @Component public class CloudbreakActor extends CloudbreakUserCache implements Actor { private static final Logger LOGGER = LoggerFactory.getLogger(CloudbreakActor.class); @Inject private TestParameter testParameter; @Override public CloudbreakUser defaultUser() { String accessKey = testParameter.get(CloudbreakTest.ACCESS_KEY); String secretKey = testParameter.get(CloudbreakTest.SECRET_KEY); checkNonEmpty("integrationtest.user.accesskey", accessKey); checkNonEmpty("integrationtest.user.secretkey", secretKey); return new CloudbreakUser(accessKey, secretKey); } @Override public CloudbreakUser secondUser() { String secondaryAccessKey = testParameter.get(CloudbreakTest.SECONDARY_ACCESS_KEY); String secondarySecretKey = testParameter.get(CloudbreakTest.SECONDARY_SECRET_KEY); checkNonEmpty("integrationtest.cb.secondary.accesskey", secondaryAccessKey); checkNonEmpty("integrationtest.cb.secondary.secretkey", secondarySecretKey); return new CloudbreakUser(secondaryAccessKey, secondarySecretKey); } @Override public CloudbreakUser create(String tenantName, String username) { String secretKey = testParameter.get(CloudbreakTest.SECRET_KEY); String crn = String.format("crn:cdp:iam:us-west-1:%s:user:%s", tenantName, username); String accessKey = Base64.getEncoder().encodeToString(crn.getBytes()); checkNonEmpty("integrationtest.user.secretkey", secretKey); return new CloudbreakUser(accessKey, secretKey, username + " at tenant " + tenantName); } @Override public CloudbreakUser useRealUmsUser(String key) { LOGGER.info("Getting the requested real UMS user by key:: {}", key); return getUserByDisplayName(key); } private void checkNonEmpty(String name, String value) { if (StringUtils.isBlank(value)) { throw new NullPointerException(String.format("Following variable must be set whether as environment variables or (test) application.yml:: %s", name.replaceAll("\\.", "_").toUpperCase())); } } }
40.419355
154
0.731844
63d98b4df61c7e654776a05257fda49d8d7b258d
4,652
/* Copyright (C) 2005-2011 Fabio Riccardi */ package painting; import com.lightcrafts.model.ImageEditor.ImageEditorDisplay; import com.lightcrafts.jai.JAIContext; import com.lightcrafts.jai.utils.Functions; import com.lightcrafts.image.ImageInfo; import javax.imageio.ImageIO; import javax.swing.*; import com.lightcrafts.mediax.jai.RasterFactory; import com.lightcrafts.mediax.jai.PlanarImage; import com.lightcrafts.mediax.jai.RenderedOp; import java.awt.event.WindowAdapter; import java.awt.*; import java.awt.image.*; import java.awt.color.ICC_Profile; import java.awt.color.ColorSpace; import java.awt.color.ICC_ColorSpace; import java.util.Arrays; import java.io.File; /** * Created by IntelliJ IDEA. * User: fabio * Date: Mar 23, 2005 * Time: 2:53:28 PM * To change this template use File | Settings | File Templates. */ public class PaintingTest extends WindowAdapter { PaintingTest() { Frame frame = new Frame(); frame.addWindowListener(this); File imageFile = null; if (false) { JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); imageFile = chooser.getSelectedFile(); } else { FileDialog fileDialog = new FileDialog(frame, "Open"); fileDialog.show(); String fileName = fileDialog.getDirectory() + fileDialog.getFile(); imageFile = new File(fileName); } RenderedImage source = null; RenderedImage dest = null; if ( imageFile.exists() && imageFile.canRead() ) { ICC_Profile profile = null; RenderedImage ri = null; try { ImageInfo imageInfo = ImageInfo.getInstanceFor( imageFile ); ri = imageInfo.getImage( null ); } catch ( Exception e ) { e.printStackTrace(); System.exit( -1 ); } Raster data = ri.getTile(0, 0); System.out.print("Pixels:"); for (int i = 0; i < 20; i++) for (int b = 0; b < ri.getColorModel().getNumComponents(); b++) { int sample = data.getSample(i, i, b); System.out.print(" " + sample); } System.out.println(); ColorSpace defaultCs; if (ri.getColorModel().getNumComponents() == 1) defaultCs = JAIContext.linearGrayColorSpace; else defaultCs = JAIContext.sRGBColorSpace; ColorSpace cs = (profile == null) ? defaultCs : new ICC_ColorSpace(profile); ColorModel colorModel = RasterFactory.createComponentColorModel(ri.getSampleModel().getDataType(), cs, false, false, Transparency.OPAQUE); source = new BufferedImage(colorModel, (WritableRaster) ri.getData(), false, null); if (source.getSampleModel().getDataType() == DataBuffer.TYPE_BYTE) { dest = Functions.toColorSpace(PlanarImage.wrapRenderedImage(source), JAIContext.sRGBColorSpace, null); } else { dest = Functions.fromUShortToByte( Functions.toColorSpace(PlanarImage.wrapRenderedImage(source), JAIContext.sRGBColorSpace, JAIContext.noCacheHint), null); } data = dest.getTile(0, 0); System.out.print("Pixels:"); for (int i = 0; i < 20; i++) for (int b = 0; b < dest.getColorModel().getNumComponents(); b++) { int sample = data.getSample(i, i, b); System.out.print(" " + sample); } System.out.println(); // DisplayJAI canvas = new DisplayJAI(dest); // LCPlanarImage planarSource = new LCPlanarImage(dest); ImageEditorDisplay canvas = new ImageEditorDisplay(null, (RenderedOp) dest); Component pane = new JScrollPane(canvas); frame.add(pane, BorderLayout.CENTER); } frame.pack(); frame.setSize(new Dimension(1024, 800)); frame.setVisible(true); } public static void main(String[] args) { String readFormats[] = ImageIO.getReaderMIMETypes(); String writeFormats[] = ImageIO.getWriterMIMETypes(); System.out.println("Readers: " + Arrays.asList(readFormats)); System.out.println("Writers: " + Arrays.asList(writeFormats)); new PaintingTest(); } }
35.51145
143
0.575021
da9f166872b2dbe1143f955e57f0b4c02aa1ef0c
2,692
/* * Copyright (c) 2020, Jonathan Revusky [email protected] * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package freemarker.core.ast; import freemarker.template.*; /** * A class that represents a Range between two integers. * inclusive of the end-points. It can be ascending or * descending. * @author <a href="mailto:[email protected]">Jonathan Revusky</a> */ class NumericalRange implements TemplateSequenceModel, java.io.Serializable { private static final long serialVersionUID = 8329795189999011437L; private int lower, upper; private boolean descending, norhs; // if norhs is true, then we have a half-range, like n.. /** * Constructor for half-range, i.e. n.. */ public NumericalRange(int lower) { this.norhs = true; this.lower = lower; } public NumericalRange(int left, int right) { lower = Math.min(left, right); upper = Math.max(left, right); descending = (left != lower); } public TemplateModel get(int i) throws TemplateModelException { int index = descending ? (upper -i) : (lower + i); if ((norhs && index > upper) || index <lower) { throw new TemplateModelException("out of bounds of range"); } return new SimpleNumber(index); } public int size() { return 1 + upper - lower; } boolean hasRhs() { return !norhs; } }
36.876712
95
0.69688
c1d561411c18959806adedd39f45f7c6b9efc09a
7,251
package james.crasher.activities; import android.content.ClipData; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import java.util.Locale; import james.buttons.Button; import james.crasher.BuildConfig; import james.crasher.R; import james.crasher.utils.ColorUtils; import james.crasher.utils.CrashUtils; import james.crasher.utils.ImageUtils; public class CrashActivity extends AppCompatActivity implements View.OnClickListener { public static final String EXTRA_NAME = "james.crasher.EXTRA_NAME"; public static final String EXTRA_MESSAGE = "james.crasher.EXTRA_MESSAGE"; public static final String EXTRA_STACK_TRACE = "james.crasher.EXTRA_STACK_TRACE"; public static final String EXTRA_EMAIL = "james.crasher.EXTRA_EMAIL"; public static final String EXTRA_DEBUG_MESSAGE = "james.crasher.EXTRA_DEBUG_MESSAGE"; public static final String EXTRA_COLOR = "james.crasher.EXTRA_COLOR"; private Toolbar toolbar; private ActionBar actionBar; private TextView name; private TextView message; private TextView description; private Button copy; private Button share; private Button email; private View stackTraceHeader; private ImageView stackTraceArrow; private TextView stackTrace; private String body; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crash); toolbar = findViewById(R.id.toolbar); name = findViewById(R.id.name); message = findViewById(R.id.message); description = findViewById(R.id.description); copy = findViewById(R.id.copy); share = findViewById(R.id.share); email = findViewById(R.id.email); stackTraceHeader = findViewById(R.id.stackTraceHeader); stackTraceArrow = findViewById(R.id.stackTraceArrow); stackTrace = findViewById(R.id.stackTrace); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); int color = getIntent().getIntExtra(EXTRA_COLOR, ContextCompat.getColor(this, R.color.colorPrimary)); int colorDark = ColorUtils.darkColor(color); boolean isColorDark = ColorUtils.isColorDark(color); toolbar.setBackgroundColor(color); toolbar.setTitleTextColor(isColorDark ? Color.WHITE : Color.BLACK); copy.setBackgroundColor(colorDark); copy.setTextColor(colorDark); copy.setOnClickListener(this); share.setBackgroundColor(colorDark); share.setTextColor(colorDark); share.setOnClickListener(this); email.setBackgroundColor(colorDark); email.setTextColor(colorDark); if (getIntent().hasExtra(EXTRA_EMAIL)) { email.setOnClickListener(this); } else email.setVisibility(View.GONE); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(String.format(Locale.getDefault(), getString(R.string.title_crasher_crashed), getString(R.string.app_name))); actionBar.setHomeAsUpIndicator(ImageUtils.getVectorDrawable(this, R.drawable.ic_crasher_back, isColorDark ? Color.WHITE : Color.BLACK)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(colorDark); getWindow().setNavigationBarColor(colorDark); } String stack = getIntent().getStringExtra(EXTRA_STACK_TRACE); String stackCause = CrashUtils.getCause(this, stack); String nameString = getIntent().getStringExtra(EXTRA_NAME) + (stackCause != null ? " at " + stackCause : ""); String messageString = getIntent().getStringExtra(EXTRA_NAME); name.setText(nameString); if (messageString != null && messageString.length() > 0) message.setText(messageString); else message.setVisibility(View.GONE); description.setText(String.format(Locale.getDefault(), getString(R.string.msg_crasher_crashed), getString(R.string.app_name))); stackTrace.setText(stack); stackTraceHeader.setOnClickListener(this); if (BuildConfig.DEBUG) stackTraceHeader.callOnClick(); body = nameString + "\n" + (messageString != null ? messageString : "") + "\n\n" + stack + "\n\nAndroid Version: " + Build.VERSION.SDK_INT + "\nDevice Manufacturer: " + Build.MANUFACTURER + "\nDevice Model: " + Build.MODEL + "\n\n" + (getIntent().hasExtra(EXTRA_DEBUG_MESSAGE) ? getIntent().getStringExtra(EXTRA_DEBUG_MESSAGE) : ""); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { if (v.getId() == R.id.copy) { Object service = getSystemService(CLIPBOARD_SERVICE); if (service instanceof android.content.ClipboardManager) ((android.content.ClipboardManager) service).setPrimaryClip(ClipData.newPlainText(name.getText().toString(), stackTrace.getText().toString())); else if (service instanceof android.text.ClipboardManager) ((android.text.ClipboardManager) service).setText(stackTrace.getText().toString()); } else if (v.getId() == R.id.share) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, body); startActivity(Intent.createChooser(intent, getString(R.string.title_crasher_share))); } else if (v.getId() == R.id.email) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setType("text/plain"); intent.setData(Uri.parse("mailto:" + getIntent().getStringExtra(EXTRA_EMAIL))); intent.putExtra(Intent.EXTRA_EMAIL, getIntent().getStringExtra(EXTRA_EMAIL)); intent.putExtra(Intent.EXTRA_SUBJECT, String.format(Locale.getDefault(), getString(R.string.title_crasher_exception), name.getText().toString(), getString(R.string.app_name))); intent.putExtra(Intent.EXTRA_TEXT, body); startActivity(Intent.createChooser(intent, getString(R.string.title_crasher_send_email))); } else if (v.getId() == R.id.stackTraceHeader) { if (stackTrace.getVisibility() == View.GONE) { stackTrace.setVisibility(View.VISIBLE); stackTraceArrow.animate().scaleY(-1).start(); } else { stackTrace.setVisibility(View.GONE); stackTraceArrow.animate().scaleY(1).start(); } } } }
42.403509
188
0.682664
0f1618f278900ec487203c45fed4f5dce0e67227
2,511
package com.aisino.modules.system.service; import com.aisino.modules.system.entity.Menu; import com.aisino.base.BaseService; import com.aisino.modules.system.entity.vo.MenuTreeVo; import com.aisino.modules.system.service.dto.MenuDtoBase; import com.aisino.modules.system.service.dto.MenuQueryParam; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Set; /** * @author rxx * @date 2020-09-25 */ public interface MenuService extends BaseService<Menu> { /** * 查询数据分页 * @param query 条件 * @return PageInfo<MenuDtoBase> */ List<MenuDtoBase> queryAll(MenuQueryParam query, boolean isQuery); /** * 查询所有数据不分页 * @param query 条件参数 * @return List<MenuDtoBase> */ List<MenuDtoBase> queryAll(MenuQueryParam query); Menu getById(Long id); MenuDtoBase findById(Long id); /** * 插入一条新数据。 */ boolean save(Menu resources); boolean updateById(Menu resources); boolean removeById(Long id); boolean removeByIds(Set<Long> ids); /** * 获取待删除的菜单 * @param menuList / * @param menuSet / * @return / */ Set<Menu> getDeleteMenus(List<Menu> menuList, Set<Menu> menuSet); /** * 构建菜单树 * @param menuDtos 原始数据 * @return / */ List<MenuDtoBase> buildTree(List<MenuDtoBase> menuDtos); /** * 构建菜单树 * @param menuDtos / * @return / */ Object buildMenus(List<MenuDtoBase> menuDtos); /** * 懒加载菜单数据 * @param pid / * @return / */ List<MenuDtoBase> getMenus(Long pid); /** * 根据ID获取同级与上级数据 * @param menuDto / * @param objects / * @return / */ List<MenuDtoBase> getSuperior(MenuDtoBase menuDto, List<Menu> objects); /** * 根据当前用户获取菜单 * @param currentUserId / * @return / */ List<MenuDtoBase> findByUser(Long currentUserId); /** * 导出数据 * @param all 待导出的数据 * @param response / * @throws IOException / */ void download(List<MenuDtoBase> all, HttpServletResponse response) throws IOException; /** * 通过菜单ID获取所有父节点ID * @param menuId * @return */ List<Long> getFullPidByMenuId(Long menuId); /** * 菜单树 * @return */ List<MenuTreeVo> getMenusTree(); /** * @Author raoxingxing * @Description 查询角色的最下级菜单列表 * @Date 2021/1/16 16:38 * @Param [roleId] * @return **/ List<MenuTreeVo> getLowerMenus(Long roleId); }
21.10084
90
0.616886
90fca28ee0989526d5fb60fe37d624b97aa4a57a
1,309
package com.mj.weather.weather.model.dp.dao; import com.mj.weather.weather.model.dp.entity.WeatherCache; import org.litepal.crud.DataSupport; /** * Created by MengJie on 2017/6/27. */ public class WeatherCacheDao { /** * @return */ public static WeatherCache getLatestWeather() { WeatherCache last = DataSupport.findLast(WeatherCache.class); return last; } /** * @param city * @return */ public static String getWeatherByCity(String city) { WeatherCache cache = DataSupport.where("city=?", city + "").findFirst(WeatherCache.class); String json = null; if (cache != null) { json = cache.json; } return json; } /** * 先删除或添加(使最新数据始终在最后一条) * * @param city * @param district * @param json */ public static boolean addWeatherCache(String city, String district, String json) { int i = DataSupport.deleteAll(WeatherCache.class, "city=?", city + ""); WeatherCache cache = new WeatherCache(); cache.city = city; cache.district = district; cache.json = json; return cache.save(); } /** * 清空该表 */ public static void clear() { DataSupport.deleteAll(WeatherCache.class); } }
22.568966
98
0.589763
55aa2369dce78b491c05cd7b5e11887328ff92c4
657
package br.com.zup.mercado_livre.controllers.requests; import br.com.zup.mercado_livre.controllers.validations.*; import br.com.zup.mercado_livre.models.*; import javax.validation.constraints.*; public class NotaFiscalRequest { @NotNull private Long idCompra; @NotNull private Long idComprador; public NotaFiscalRequest(Long idCompra, Long idComprador) { this.idCompra = idCompra; this.idComprador = idComprador; } @Override public String toString() { return "NotaFiscal{" + "idCompra=" + idCompra + ", idComprador=" + idComprador + '}'; } }
22.655172
63
0.642314
d2c7945c1d2bf65678af8176872fc6479df26e5b
227
package com.usf.catalogservice.repositories; import com.usf.catalogservice.models.Level; import org.springframework.data.jpa.repository.JpaRepository; public interface LevelRepository extends JpaRepository<Level, Integer> {}
28.375
61
0.845815
ef3ee1a303e5e15dabf1c8b895ad6d761ad9a72e
2,216
/* * Copyright (C) 2019 Toshiba Corporation * SPDX-License-Identifier: Apache-2.0 */ package snavigablemap.random; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.springframework.beans.factory.annotation.Autowired; import org.wcardinal.controller.AbstractController; import org.wcardinal.controller.annotation.Callable; import org.wcardinal.controller.annotation.Constant; import org.wcardinal.controller.annotation.Controller; import org.wcardinal.controller.annotation.Locked; import org.wcardinal.controller.annotation.OnChange; import org.wcardinal.controller.annotation.OnTime; import org.wcardinal.controller.data.SBoolean; import org.wcardinal.controller.data.SClass; import org.wcardinal.controller.data.SNavigableMap; import org.wcardinal.controller.data.annotation.NonNull; @Controller public class SNavigableMapController extends AbstractController { @Constant int MAX_COUNT = 1000; @Autowired SNavigableMap<Integer> field_map; final AtomicLong count = new AtomicLong( 0L ); @Callable void start() { timeout( "modify", 0 ); } @OnTime @Locked void modify() { int ocount = (int) Math.floor( 10 * Math.random() ) + 1; for( int i=0; i<ocount; ++i ) { int size = field_map.size(); int index = (int) Math.floor( size * Math.random() ); int value = (int) Math.round(Math.random()*100); if( size <= 0 ) { field_map.put( "0", 0 ); } else { final double choice = Math.random(); if( 0.5 <= choice ) { field_map.put( String.valueOf( value ), value ); } else { final Iterator<String> itr = field_map.keySet().iterator(); for( int j=0; j<index; ++j ) itr.next(); itr.remove(); } } } if( count.incrementAndGet() < MAX_COUNT ) { timeout( "modify", 12 ); } } @Autowired SClass<Map<String, Integer>> check; @Autowired @NonNull SBoolean check_result; @OnChange( "check" ) void check( Map<String, Integer> data ) { if( MAX_COUNT <= count.get() ) { System.out.println( "Check server: "+field_map.toString() ); System.out.println( "Check browser: "+data.toString() ); if( field_map.equals( data ) ) { check_result.set( true ); } } } }
25.181818
65
0.699007
af1a5a2bda87b0c64d04054540d47684c6beaf26
1,597
package com.behsazan.model.sqlite; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; /** * Created by admin on 08/27/2017. */ public class SettingDb extends SqliteHelper { public void updateKey(String key,String value) throws SQLException { Connection c = getConnection(); PreparedStatement stmt = c.prepareStatement("UPDATE SETTING SET VAR_VALUE = ? WHERE VAR_KEY =?"); stmt.setString(1, value); stmt.setString(2, key); int rows = stmt.executeUpdate(); if(rows == 0){ stmt = c.prepareStatement("INSERT INTO SETTING (VAR_KEY,VAR_VALUE) VALUES (?,?)"); stmt.setString(1, key); stmt.setString(2, value); stmt.executeUpdate(); } stmt.close(); c.close(); } public String loadSettings(String key) throws SQLException{ Connection c = null; PreparedStatement stmt = null; ResultSet rq = null; try { c = getConnection(); stmt = c.prepareStatement("SELECT VAR_KEY,VAR_VALUE from SETTING WHERE VAR_KEY = ?"); stmt.setString(1,key); rq = stmt.executeQuery(); if (rq.next()) { return rq.getString(2); } } finally { if (rq != null) rq.close(); if (stmt != null) stmt.close(); if (c != null) c.close(); } return null; } }
29.036364
105
0.560426
4cb9f3f4a51d16ec409dce387aba14ae52dc9539
2,029
package com.sample.andremion.musicplayer.model; import android.net.Uri; import java.io.Serializable; public class MediaEntity implements Serializable { private static final long serialVersionUID = 1L; public int id; //id标识 public String title; // 显示名称 public String display_name; // 文件名称 public String path; // 音乐文件的路径 public int duration; // 媒体播放总时间 public String durationStr; // 媒体播放总时间 public String albums; // 专辑 public String artist; // 艺术家 public String singer; //歌手 public long size; public Uri uri = Uri.parse("-1"); public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDisplay_name() { return display_name; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public String getDurationStr() { return durationStr; } public void setDurationStr(String durationStr) { this.durationStr = durationStr; } public String getAlbums() { return albums; } public void setAlbums(String albums) { this.albums = albums; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public String getSinger() { return singer; } public void setSinger(String singer) { this.singer = singer; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public Uri getUri() { return uri; } public void setUri(Uri uri) { this.uri = uri; } }
19.892157
54
0.600789
2b7139e5786cc52e228c23ad0df235e1685174c1
993
package ch.helin.messages.dto.message.missionMessage; import ch.helin.messages.dto.MissionDto; import ch.helin.messages.dto.message.Message; import ch.helin.messages.dto.message.PayloadType; /** * Message to assign a drone a specific mission. */ public class AssignMissionMessage extends Message{ private MissionDto mission; public AssignMissionMessage() { super(PayloadType.AssignMission); } public MissionDto getMission() { return mission; } public void setMission(MissionDto mission) { this.mission = mission; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AssignMissionMessage)) return false; AssignMissionMessage that = (AssignMissionMessage) o; return mission != null ? mission.equals(that.mission) : that.mission == null; } @Override public int hashCode() { return mission != null ? mission.hashCode() : 0; } }
23.642857
85
0.673716
701d25ba0da0dc3d2e8641fe8c6925a8f9adc539
128
/** * Package for the local enactables performing simple calculations. */ package at.uibk.dps.ee.enactables.local.calculation;
32
67
0.78125
fb7ba65ab2e1ba29cfc378a88b8cfe261ffbdf71
6,051
package com.adriel.calculator; import com.adriel.calculator.exception.OperatorNotDefinedException; import com.adriel.calculator.util.StringAndBoolReturn; public class Splitter { private final String OPERATOR_NOT_DEFINED_MSG = "Operator %s cannot be used in first position, or after another operator."; private final String ALPHABET_OPERATOR_MSG = "Alphabet %s cannot be used."; private final String OPERATOR_IN_LAST_MSG = "Operator %s cannot be used in last position."; private final String MULTI_DECIMAL_MSG = "Multiple decimal points (%s) found in number %s."; private final String NO_OPEN_BRACKET_MSG = "Cannot find appropriate opening bracket %s for %s"; protected Splitter() {} /** * Splits the string expression <b>sum</b> by operators (non-numeric characters), and stores these into an array <b>eval_arr</b>. Another array <b>num_op_arr</b> is used to store whether the string at each position is a numeric (true). * @param sum * @return <b>eval_arr</b>, <b>num_op_arr</b> as new <tt>StringAndBoolReturn</tt> object */ public StringAndBoolReturn splitNumeric(String sum) { // Stores the current value found String numStore = ""; // Two arrays: one stores all values and operators to evaluate, the other stores whether it is a value (true) or an operator (false) in each position StringAndBoolReturn splittedExpression = new StringAndBoolReturn(sum.length()); // Position in array int pos = 0; // Boolean value to check whether previous char is an operator // If previous char is operator, next can only be +/-/digit boolean operatorAppeared = true; // After each operator, this indicates whether the positive / negaive number indicator has appeared boolean posNegAppeared = false; // Check whether decimal point has appeared boolean pointAppeared = false; // Check whether a left bracket equivalent has appeared boolean roundParenthesisAppeared = false; boolean squareBracketAppeared = false; boolean curlyBraceAppeared = false; for (int i = 0; i < sum.length(); i++) { Character c = sum.charAt(i); if (Character.isDigit(c)) { operatorAppeared = false; posNegAppeared = false; // Still a number, add to storage numStore += c; } else if (String.valueOf(c).equals(".")) { if (pointAppeared) { throw new OperatorNotDefinedException(String.format(MULTI_DECIMAL_MSG, String.valueOf(c), numStore)); } else { operatorAppeared = false; posNegAppeared = false; // Still a number, add to storage numStore += c; pointAppeared = true; } } else if (Character.isAlphabetic(c)) { throw new OperatorNotDefinedException(String.format(ALPHABET_OPERATOR_MSG, String.valueOf(c))); } else if (String.valueOf(c).equals("(")) { if (roundParenthesisAppeared) { throw new OperatorNotDefinedException(String.format(OPERATOR_NOT_DEFINED_MSG, String.valueOf(c))); } roundParenthesisAppeared = true; splittedExpression.store(String.valueOf(c), false, pos); pos++; } else if (String.valueOf(c).equals(")")) { if (!roundParenthesisAppeared) { throw new OperatorNotDefinedException(String.format(NO_OPEN_BRACKET_MSG, "(", String.valueOf(c))); } roundParenthesisAppeared = false; // Store number (there must be a number before closing bracket, for any valid expression) splittedExpression.store(numStore, true, pos); numStore = ""; pos++; splittedExpression.store(String.valueOf(c), false, pos); pos++; } else if (String.valueOf(c).equals("[")) { if (squareBracketAppeared || roundParenthesisAppeared) { throw new OperatorNotDefinedException(String.format(OPERATOR_NOT_DEFINED_MSG, String.valueOf(c))); } squareBracketAppeared = true; splittedExpression.store(String.valueOf(c), false, pos); pos++; } else if (String.valueOf(c).equals("]")) { if (!squareBracketAppeared) { throw new OperatorNotDefinedException(String.format(NO_OPEN_BRACKET_MSG, "[", String.valueOf(c))); } squareBracketAppeared = false; // Store number if found if (!"".equals(numStore)) { splittedExpression.store(numStore, true, pos); numStore = ""; pos++; } splittedExpression.store(String.valueOf(c), false, pos); pos++; } else if (String.valueOf(c).equals("{")) { if (curlyBraceAppeared || squareBracketAppeared || roundParenthesisAppeared) { throw new OperatorNotDefinedException(String.format(OPERATOR_NOT_DEFINED_MSG, String.valueOf(c))); } curlyBraceAppeared = true; splittedExpression.store(String.valueOf(c), false, pos); pos++; } else if (String.valueOf(c).equals("}")) { if (!curlyBraceAppeared) { throw new OperatorNotDefinedException(String.format(NO_OPEN_BRACKET_MSG, "{", String.valueOf(c))); } curlyBraceAppeared = false; // Store number if found if (!"".equals(numStore)) { splittedExpression.store(numStore, true, pos); numStore = ""; pos++; } splittedExpression.store(String.valueOf(c), false, pos); pos++; } else { if (operatorAppeared) { // Operator at first position, don't break if (!posNegAppeared && (String.valueOf(c).equals("-") || String.valueOf(c).equals("+"))) { posNegAppeared = true; numStore += c; continue; } else { throw new OperatorNotDefinedException(String.format(OPERATOR_NOT_DEFINED_MSG, String.valueOf(c))); } } if (i == sum.length()-1) { throw new OperatorNotDefinedException(String.format(OPERATOR_IN_LAST_MSG, String.valueOf(c))); } // Store number if found if (!"".equals(numStore)) { splittedExpression.store(numStore, true, pos); numStore = ""; pos++; } // Store the operator splittedExpression.store(String.valueOf(c), false, pos); pos++; operatorAppeared = true; pointAppeared = false; } // A number at the end if (!"".equals(numStore)) { splittedExpression.store(numStore, true, pos); } } return splittedExpression; } }
38.541401
236
0.689473
4c9994dee97322021edac3b7d7b7ffd10f016876
2,027
package org.codeforamerica.shiba.output.documentfieldpreparers; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.codeforamerica.shiba.application.Application; import org.codeforamerica.shiba.output.DocumentField; import org.codeforamerica.shiba.output.DocumentFieldType; import org.codeforamerica.shiba.output.Document; import org.codeforamerica.shiba.output.FullNameFormatter; import org.codeforamerica.shiba.output.Recipient; import org.codeforamerica.shiba.pages.data.PageData; import org.springframework.stereotype.Component; @Component public class ParentNotLivingAtHomePreparer implements DocumentFieldPreparer { @Override public List<DocumentField> prepareDocumentFields(Application application, Document document, Recipient recipient, SubworkflowIterationScopeTracker scopeTracker) { Map<String, String> idToChild = application.getApplicationData().getPagesData() .safeGetPageInputValue("childrenInNeedOfCare", "whoNeedsChildCare").stream() .collect(Collectors.toMap(FullNameFormatter::getId, FullNameFormatter::format)); PageData pageData = application.getApplicationData().getPageData("parentNotAtHomeNames"); if (pageData == null) { return List.of(); } List<String> parentNames = pageData.get("whatAreTheParentsNames").getValue(); List<String> childIds = pageData.get("childIdMap").getValue(); List<DocumentField> result = new ArrayList<>(); for (int i = 0; i < childIds.size(); i++) { String parentName = parentNames.get(i); String childId = childIds.get(i); result.add(new DocumentField( "custodyArrangement", "parentNotAtHomeName", List.of(parentName), DocumentFieldType.SINGLE_VALUE, i)); result.add(new DocumentField( "custodyArrangement", "childFullName", List.of(idToChild.get(childId)), DocumentFieldType.SINGLE_VALUE, i)); } return result; } }
36.854545
94
0.74001
696aba025c37aff6cd4da9f061107df412bdb34c
349
package io.dockstore.tooltester.blueOceanJsonObjects; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Json object part of the Links json object */ public class Link { @SerializedName("href") @Expose private String href; public String getHref() { return href; } }
18.368421
53
0.707736
50790281505fa7fb8c8f8f66b08fcbf155fbac57
69
package factory; public enum ListType {Array, LinkedList, SyncList}
17.25
50
0.797101
873b0f21ff0e98058b936524fe1334a1b8363d82
5,546
package guitests; import static org.junit.Assert.assertTrue; import static savvytodo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static savvytodo.logic.commands.MarkCommand.MESSAGE_MARK_TASK_SUCCESS; import static savvytodo.logic.commands.MarkCommand.MESSAGE_USAGE; import java.util.LinkedList; import org.junit.Test; import guitests.guihandles.TaskCardHandle; import savvytodo.model.task.Status; import savvytodo.testutil.TestTask; //@@author A0140016B public class MarkCommandTest extends TaskManagerGuiTest { // The list of tasks in the task list panel is expected to match this list. // This list is updated with every successful call to assertMarkSuccess(). TestTask[] expectedTasksList = td.getTypicalTasks(); @Test public void markInvalidCommand() { commandBox.runCommand("mark "); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MESSAGE_USAGE)); } @Test public void mark() { //mark the first in the list int targetIndex = 1; TestTask markedTask = expectedTasksList[targetIndex - 1]; markedTask.setCompleted(new Status(true)); assertMarkSuccess(targetIndex, targetIndex, markedTask); //mark the last in the list targetIndex = expectedTasksList.length; TestTask markedTask2 = expectedTasksList[targetIndex - 1]; markedTask2.setCompleted(new Status(true)); assertMarkSuccess(targetIndex, targetIndex, markedTask2); //mark from the middle of the list targetIndex = expectedTasksList.length / 2; TestTask markedTask3 = expectedTasksList[targetIndex - 1]; markedTask3.setCompleted(new Status(true)); assertMarkSuccess(targetIndex, targetIndex, markedTask3); //invalid index commandBox.runCommand("mark " + expectedTasksList.length + 1); assertResultMessage("The task index provided is invalid"); } @Test public void markMultiple() { LinkedList<Integer> targetIndices = new LinkedList<Integer>(); LinkedList<TestTask> markedTasks = new LinkedList<TestTask>(); //mark the first in the list int targetIndex = 1; TestTask markedTask = expectedTasksList[targetIndex - 1]; markedTask.setCompleted(new Status(true)); targetIndices.add(targetIndex); markedTasks.add(markedTask); //mark the last in the list targetIndex = expectedTasksList.length; TestTask markedTask2 = expectedTasksList[targetIndex - 1]; markedTask2.setCompleted(new Status(true)); targetIndices.add(targetIndex); markedTasks.add(markedTask2); //mark from the middle of the list targetIndex = expectedTasksList.length / 2; TestTask markedTask3 = expectedTasksList[targetIndex - 1]; markedTask3.setCompleted(new Status(true)); targetIndices.add(targetIndex); markedTasks.add(markedTask3); assertMarkMultipleSuccess(targetIndices, markedTasks); } /** * Checks whether the marked tasks has the correct updated details. * * @param targetIndices * indices of task to mark in filtered list * @param markedTasks * the expected task after marking the task's details */ private void assertMarkMultipleSuccess(LinkedList<Integer> targetIndices, LinkedList<TestTask> markedTasks) { StringBuilder indices = new StringBuilder(); for (Integer markedTaskIndex : targetIndices) { indices.append(markedTaskIndex + " "); } commandBox.runCommand("mark " + indices); StringBuilder resultSb = new StringBuilder(); for (TestTask markedTask : markedTasks) { // confirm the new card contains the right data TaskCardHandle editedCard = eventTaskListPanel.navigateToTask(markedTask.getName().name); assertMatching(markedTask, editedCard); expectedTasksList[targetIndices.peek() - 1] = markedTask; resultSb.append(String.format(MESSAGE_MARK_TASK_SUCCESS, targetIndices.pop())); } assertTrue(eventTaskListPanel.isListMatching(expectedTasksList)); assertResultMessage(resultSb.toString()); } /** * Checks whether the marked task has the correct updated details. * * @param filteredTaskListIndex * index of task to mark in filtered list * @param markedTaskIndex * index of task to mark in the task manager. Must refer to the * same task as {@code filteredTaskListIndex} * @param detailsToMark * details to mark the task with as input to the mark command * @param markedTask * the expected task after marking the task's details */ private void assertMarkSuccess(int filteredTaskListIndex, int markedTaskIndex, TestTask markedTask) { commandBox.runCommand("mark " + filteredTaskListIndex); // confirm the new card contains the right data TaskCardHandle editedCard = eventTaskListPanel.navigateToTask(markedTask.getName().name); assertMatching(markedTask, editedCard); // confirm the list now contains all previous tasks plus the task with // updated details expectedTasksList[markedTaskIndex - 1] = markedTask; assertTrue(eventTaskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(MESSAGE_MARK_TASK_SUCCESS, markedTaskIndex)); } }
37.727891
113
0.689326
1b5e302cf0458ebc3b7ae6b9ab0ed19ee9859987
239
package org.prebid.server.bidder.thirtythreeacross.proto; import lombok.AllArgsConstructor; import lombok.Value; @AllArgsConstructor(staticName = "of") @Value public class ThirtyThreeAcrossReqExt { ThirtyThreeAcrossReqExtTtx ttx; }
19.916667
57
0.8159