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
4c0a332ac6a6260c4ed09a23ccb5977f406d84e4
1,882
package org.codingeasy.shiroplus.loader.admin.server.controller; import org.codingeasy.shiroplus.loader.admin.server.models.Action; import org.codingeasy.shiroplus.loader.admin.server.models.entity.RoleEntity; import org.codingeasy.shiroplus.loader.admin.server.service.PermissionService; import org.codingeasy.shiroplus.loader.admin.server.models.Page; import org.codingeasy.shiroplus.loader.admin.server.models.Response; import org.codingeasy.shiroplus.loader.admin.server.models.entity.UserRolesEntity; import org.codingeasy.shiroplus.loader.admin.server.models.request.PermissionRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; /** * 权限管理 * @author : KangNing Hu */ @RestController @RequestMapping("/admin/permission") public class PermissionController { @Autowired private PermissionService permissionService; /** * 用户角色分页列表 * @param request 查询条件 * @return 返回响应结果 用户分页列表信息 */ @PostMapping("/page") public Response<Page<UserRolesEntity>> page(@RequestBody PermissionRequest request){ return Response.ok(permissionService.page(request)); } /** * 详情 * @param userId 用户id * @return 返回响应结果 用户名称 和 角色列表 */ @GetMapping("") public Response<UserRolesEntity> get(Long userId){ return Response.ok(permissionService.get(userId)); } /** * 获取角色列表 * @return */ @GetMapping("/getRoles") public Response<List<RoleEntity>> getRoles(){ return Response.ok(permissionService.getRoles()); } /** * 修改用户角色 * @param userRolesEntity 用户角色列表信息 * @return 响应修改结果 */ @PutMapping("") public Response update(@RequestBody @Validated(Action.Update.class) UserRolesEntity userRolesEntity){ return Response.ok(permissionService.update(userRolesEntity)); } }
27.676471
102
0.774708
997561c22119222d142f8ffa6babcf30d50b8a33
2,501
//@@author nusjzx package seedu.address.logic.commands; import static org.junit.Assert.fail; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.logic.commands.CommandTestUtil.showFirstTaskOnly; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON; import static seedu.address.testutil.TypicalPersons.getTypicalAddressBook; import static seedu.address.testutil.TypicalTasks.getTypicalTaskbook; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import seedu.address.logic.CommandHistory; import seedu.address.logic.UndoRedoStack; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.TaskBook; import seedu.address.model.UserPrefs; import seedu.address.model.person.ReadOnlyPerson; import seedu.address.model.task.ReadOnlyTask; import seedu.address.model.task.Task; import seedu.address.model.task.exceptions.DuplicateTaskException; import seedu.address.model.task.exceptions.TaskNotFoundException; public class LinkedTasksCommandTest { private Model model; private Model expectedModel; private LinkedTasksCommand linkedTasksCommand; @Before public void setUp() { model = new ModelManager(getTypicalAddressBook(), getTypicalTaskbook(), new UserPrefs()); } @Test public void executeLinkedPersonsSuccessful() { ReadOnlyTask firstTask = model.getTaskBook().getTaskList().get(0); ArrayList<Integer> firstId = new ArrayList<>(); ReadOnlyPerson firstPerson = model.getAddressBook().getPersonList().get(0); firstId.add(firstPerson.getId()); Task linkedTask = new Task(firstTask); linkedTask.setPeopleIds(firstId); try { model.updateTask(firstTask, linkedTask); } catch (DuplicateTaskException e) { fail("never reach this."); } catch (TaskNotFoundException e) { fail("never reach this."); } expectedModel = new ModelManager(model.getAddressBook(), new TaskBook(model.getTaskBook()), new UserPrefs()); linkedTasksCommand = new LinkedTasksCommand(INDEX_FIRST_PERSON); linkedTasksCommand.setData(model, new CommandHistory(), new UndoRedoStack()); showFirstTaskOnly(expectedModel); assertCommandSuccess(linkedTasksCommand, model, String.format( linkedTasksCommand.MESSAGE_LINKED_TASKS_SUCCESS, firstPerson.getName()), expectedModel); } }
38.476923
117
0.752099
4ab0665a6b824231fcf7134ff98d1bf71bf8f33e
1,852
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.apkcheck; /** * Container representing a method with parameters. */ public class FieldInfo { private String mName; private String mType; private String mNameAndType; private boolean mTypeNormalized; /** * Constructs a FieldInfo. * * @param name Field name. * @param type Fully-qualified binary or non-binary type name. */ public FieldInfo(String name, String type) { mName = name; mType = type; } /** * Returns the combined name and type. This value is used as a hash * table key. */ public String getNameAndType() { if (mNameAndType == null) mNameAndType = mName + ":" + TypeUtils.typeToDescriptor(mType); return mNameAndType; } /** * Normalize the type used in fields. */ public void normalizeType(ApiList apiList) { if (!mTypeNormalized) { String type = TypeUtils.ambiguousToBinaryName(mType, apiList); if (!type.equals(mType)) { /* name changed, force regen on name+type */ mType = type; mNameAndType = null; } mTypeNormalized = true; } } }
28.492308
75
0.63013
84091029516743f58f8a3c162ce2b442332d15d6
2,507
package com.forum.controllers; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.forum.commands.ChoiceCommand; import com.forum.commands.OpinionChoiceCommand; import com.forum.domain.Answer; import com.forum.domain.User; import com.forum.services.AnswerService; import com.forum.services.ChoiceService; import com.forum.utils.MyUtils; @Controller public class ChoiceController { private static Log log = LogFactory.getLog(ChoiceController.class); @Autowired private ChoiceService choiceService; @Autowired private AnswerService answerService; /* public ChoiceController(ChoiceService choiceService, AnswerService answerService) { this.choiceService = choiceService; this.answerService = answerService; } */ @GetMapping("choice/{answerId}") public @ResponseBody Answer choice(@PathVariable Long answerId, @RequestParam String choice, @RequestParam Long opinionId) { ChoiceCommand choiceCommand = new ChoiceCommand(); choiceCommand.setChoice(choice); choiceCommand.setAnswerId(answerId); choiceService.create(choiceCommand); //DebateController debateController = new DebateController(opinionService, answerService); //return debateController.debate(opinionId, model); return verCantidadesRespuesta(answerId); } @GetMapping("choice/op/{opinionChoiceId}") public @ResponseBody OpinionChoiceCommand chooseChoice ( @PathVariable Long opinionChoiceId ) { User currentUser = MyUtils.currentUser().get(); log.info("invocando choiceService.chooseChoice..."); choiceService.chooseChoice(opinionChoiceId, currentUser.getId()); return choiceService.findChoiceResult(opinionChoiceId); } @GetMapping("/choice/buscar2/{answerId}") public @ResponseBody Answer verCantidades(@PathVariable Long answerId) { Answer answer = new Answer(); answer.setId(answerId); answer.setPositiveAmount((long) 4); return answer; } private Answer verCantidadesRespuesta(long answerId) { return answerService.buscarRespuesta(answerId); } }
27.25
92
0.763861
097e2dc3f77b9b37bb68164876418d4a6d01448c
949
package geekforgeek; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.Buffer; import java.util.Arrays; public class MZeroes { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int[] array= Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); int n=Integer.parseInt(reader.readLine()); int nz=0; int i=0; for(i=0;i<array.length && nz<n;i++) { if(array[i]==0) { nz++; } } int max=i; int j=i; while(i<array.length) { if(array[i]==0) { while (array[j]!=0) { j++; } } i++; max=Math.max(max,i-j+1); } System.out.println(max); } }
24.973684
103
0.523709
039040f054561036eca0b7dad0f75e5a23617bd6
3,931
package com.tianci.weather.ui; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.widget.TextView; import com.tianci.weather.Debugger; import com.tianci.weather.R; import com.tianci.weather.WeatherApplication; import com.tianci.weather.WeatherConfig; import com.tianci.weather.data.TCWeatherEnum; /** * @Date : 2016年4月20日 * @Author : Zhan Yu * @Description : TODO */ public class UIUtils { public final static int POS_IMG_LEFT = 0; public final static int POS_IMG_TOP = 1; public final static int POS_IMG_RIGHT = 2; public final static int POS_IMG_BOTTOM = 3; /** * 在文本中添加图片 * * @param tv * TextView * @param imgRes * 图片资源 * @param 图片大小 * @param pos * 图片位置: <li>0:左</li> <li>1:上</li> <li>2:右</li> <li>3:下</li> */ @SuppressWarnings("unused") public static void addImgToTextView(TextView tv, Drawable d, int imgSize, int pos) { if (d == null) return; d.setBounds(0, 0, imgSize, imgSize); switch (pos) { case POS_IMG_LEFT: tv.setCompoundDrawables(d, null, null, null); break; case POS_IMG_TOP: tv.setCompoundDrawables(null, d, null, null); break; case POS_IMG_RIGHT: tv.setCompoundDrawables(null, null, d, null); break; case POS_IMG_BOTTOM: tv.setCompoundDrawables(null, null, null, d); break; default: tv.setCompoundDrawables(null, null, d, null); break; } tv.setCompoundDrawablePadding(WeatherConfig.getResolutionValue(30)); } /** * 根据天气状况获取对应图标 * * @param wenum * @return */ public static int[] getWeatherIconRes(TCWeatherEnum wenum) { int[] resId = new int[3]; int id = WeatherApplication.context.getResources().getIdentifier( "weather_icon_" + wenum.toString().toLowerCase(), "drawable", WeatherApplication.context.getPackageName()); int focusId = WeatherApplication.context.getResources().getIdentifier( "weather_icon_" + wenum.toString().toLowerCase() + "_focus", "drawable", WeatherApplication.context.getPackageName()); Debugger.i("getWeatherIconRes" + wenum.toString().toLowerCase()); int unfocusId = WeatherApplication.context.getResources() .getIdentifier( "weather_icon_" + wenum.toString().toLowerCase() + "_nofocus", "drawable", WeatherApplication.context.getPackageName()); if (id == 0) { id = R.drawable.weather_icon_default; } if (focusId == 0) { focusId = R.drawable.weather_icon_sunny_focus; } if (unfocusId == 0) { unfocusId = R.drawable.weather_icon_sunny_nofocus; } resId[0] = id; resId[1] = focusId; resId[2] = unfocusId; return resId; } /** * 根据天气状况获取对应背景图片 * * @param wenum * @return */ public static BitmapDrawable getWeatherBackgroundDrawable( TCWeatherEnum wenum) { Debugger.d("getWeatherBackgroundDrawable wenum : " + wenum); // BitmapDrawable.createFromPath(WeatherApplication.context.getDir( // "cached_image", Context.MODE_PRIVATE).getAbsolutePath()+ // "/weather_bg_"+wenum.toString().toLowerCase() + ".jpg"); // toLowerCase():将stringObject 的所有大写字符全部被转换为了小写字符 int resId = wenum == null ? 0 : WeatherApplication.context.getResources() .getIdentifier( "weather_bg_" + wenum.toString().toLowerCase(), "drawable", WeatherApplication.context.getPackageName()); if (resId == 0) resId = R.drawable.weather_bg_default; BitmapDrawable bmp = (BitmapDrawable) WeatherApplication.context .getResources().getDrawable(resId);// R.drawable.weather_bg_default; return bmp; } /** * 将“yyyy-MM-dd”格式的日期转化为“MM/dd”格式 * * @Title:getFormatDate * @param string * @return String */ public static String getFormatDate(String string) { String str = ""; if (string != null && string.length() != 0) { str = string.substring(5); str = str.replace('-', '/'); System.out.println(str); } return str; } }
26.206667
74
0.685067
1a36c7e27ff4a233d2d7310366b2a78cb6aa642f
4,914
/* * Copyright 2008-2013 Hippo B.V. (http://www.onehippo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hippoecm.frontend.model.ocm; import java.util.Iterator; import javax.jcr.ItemNotFoundException; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.apache.wicket.model.IDetachable; import org.apache.wicket.model.IModel; import org.hippoecm.frontend.model.JcrNodeModel; import org.hippoecm.frontend.model.event.IEvent; import org.hippoecm.frontend.model.event.IObservable; import org.hippoecm.frontend.model.event.IObservationContext; import org.hippoecm.frontend.model.event.IObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A base class for implementing object content mapping. It wraps a JcrNodeModel, * and provides an observable on top of JCR. Subclasses can override the processEvents * method to translate these events to object-type specific events. * <p> * All instances of a type that correspond to the same node are equivalent with respect * to the hashCode and equals methods. */ abstract public class JcrObject implements IDetachable, IObservable { private static final long serialVersionUID = 1L; static final Logger log = LoggerFactory.getLogger(JcrObject.class); private JcrNodeModel nodeModel; private IObserver<JcrNodeModel> observer; private IObservationContext<JcrObject> obContext; private boolean observing = false; /** * Legacy constructor, to provide binary compatibility with 2.10. */ @Deprecated public JcrObject(JcrNodeModel model) { this((IModel<Node>) model); } public JcrObject(IModel<Node> nodeModel) { if (nodeModel instanceof JcrNodeModel) { this.nodeModel = (JcrNodeModel) nodeModel; } else { Node node = nodeModel.getObject(); if (node == null) { throw new RuntimeException("No node in model for " + this); } this.nodeModel = new JcrNodeModel(node); } } protected Node getNode() throws ItemNotFoundException { Node node = nodeModel.getNode(); if (node == null) { throw new ItemNotFoundException("No node exists at " + nodeModel.getItemModel().getPath()); } return node; } protected JcrNodeModel getNodeModel() { return nodeModel; } public void save() { if (nodeModel.getNode() != null) { try { nodeModel.getNode().save(); } catch (RepositoryException ex) { log.error(ex.getMessage()); } } else { log.error("Node does not exist"); } } public void detach() { if (nodeModel != null) { nodeModel.detach(); } } @SuppressWarnings("unchecked") public void setObservationContext(IObservationContext<? extends IObservable> context) { this.obContext = (IObservationContext<JcrObject>) context; } protected IObservationContext getObservationContext() { return observing ? obContext : null; } /** * Process the JCR events. Implementations should create higher-level events that are * meaningful for the subtype. These must be broadcast to the observation context. * @param context subtype specific observation context * @param events received JCR events */ abstract protected void processEvents(IObservationContext context, Iterator<? extends IEvent> events); public void startObservation() { observing = true; obContext.registerObserver(observer = new IObserver<JcrNodeModel>() { private static final long serialVersionUID = 1L; public JcrNodeModel getObservable() { return nodeModel; } public void onEvent(Iterator<? extends IEvent<JcrNodeModel>> events) { JcrObject.this.processEvents(obContext, events); } }); } public void stopObservation() { obContext.unregisterObserver(observer); observing = false; } @Override public int hashCode() { return 345791 ^ nodeModel.hashCode(); } @Override public boolean equals(Object obj) { return ((obj instanceof JcrObject) && ((JcrObject) obj).nodeModel.equals(nodeModel)); } }
32.328947
106
0.665649
0ac165976dc5fcf48b710d7d80c4efdaafdb8798
16,154
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 org.hisp.dhis.tracker.programrule; import static org.hisp.dhis.rules.models.AttributeType.DATA_ELEMENT; import static org.hisp.dhis.rules.models.AttributeType.UNKNOWN; import static org.hisp.dhis.rules.models.TrackerObjectType.ENROLLMENT; import static org.hisp.dhis.rules.models.TrackerObjectType.EVENT; import static org.junit.Assert.*; import static org.mockito.Mockito.when; import java.util.Collection; import java.util.List; import java.util.Map; import org.hisp.dhis.DhisConvenienceTest; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.event.EventStatus; import org.hisp.dhis.program.ProgramStage; import org.hisp.dhis.program.ProgramStageDataElement; import org.hisp.dhis.program.ValidationStrategy; import org.hisp.dhis.rules.models.*; import org.hisp.dhis.tracker.bundle.TrackerBundle; import org.hisp.dhis.tracker.domain.Enrollment; import org.hisp.dhis.tracker.domain.EnrollmentStatus; import org.hisp.dhis.tracker.domain.Event; import org.hisp.dhis.tracker.preheat.TrackerPreheat; import org.hisp.dhis.tracker.programrule.implementers.ShowErrorOnCompleteValidator; import org.hisp.dhis.tracker.programrule.implementers.ShowErrorValidator; import org.hisp.dhis.tracker.programrule.implementers.ShowWarningOnCompleteValidator; import org.hisp.dhis.tracker.programrule.implementers.ShowWarningValidator; import org.hisp.dhis.tracker.report.TrackerErrorCode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @RunWith( MockitoJUnitRunner.class ) public class ShowErrorWarningImplementerTest extends DhisConvenienceTest { private final static String CONTENT = "SHOW ERROR DATA"; private final static String DATA = "2 + 2"; private final static String EVALUATED_DATA = "4.0"; private final static String ACTIVE_ENROLLMENT_ID = "ActiveEnrollmentUid"; private final static String COMPLETED_ENROLLMENT_ID = "CompletedEnrollmentUid"; private final static String ACTIVE_EVENT_ID = "EventUid"; private final static String COMPLETED_EVENT_ID = "CompletedEventUid"; private final static String PROGRAM_STAGE_ID = "ProgramStageId"; private final static String ANOTHER_PROGRAM_STAGE_ID = "AnotherProgramStageId"; private final static String DATA_ELEMENT_ID = "DataElementId"; private final static String ANOTHER_DATA_ELEMENT_ID = "AnotherDataElementId"; private ShowWarningOnCompleteValidator warningOnCompleteImplementer = new ShowWarningOnCompleteValidator(); private ShowErrorOnCompleteValidator errorOnCompleteImplementer = new ShowErrorOnCompleteValidator(); private ShowErrorValidator errorImplementer = new ShowErrorValidator(); private ShowWarningValidator warningImplementer = new ShowWarningValidator(); private TrackerBundle bundle; @Mock private TrackerPreheat preheat; private ProgramStage programStage; private ProgramStage anotherProgramStage; @Before public void setUpTest() { bundle = TrackerBundle.builder().build(); bundle.setEvents( getEvents() ); bundle.setEnrollments( getEnrollments() ); bundle.setRuleEffects( getRuleEventAndEnrollmentEffects() ); bundle.setPreheat( preheat ); programStage = createProgramStage( 'A', 0 ); programStage.setValidationStrategy( ValidationStrategy.ON_UPDATE_AND_INSERT ); DataElement dataElementA = createDataElement( 'A' ); dataElementA.setUid( DATA_ELEMENT_ID ); ProgramStageDataElement programStageDataElementA = createProgramStageDataElement( programStage, dataElementA, 0 ); programStage.setProgramStageDataElements( Sets.newHashSet( programStageDataElementA ) ); anotherProgramStage = createProgramStage( 'B', 0 ); anotherProgramStage.setValidationStrategy( ValidationStrategy.ON_UPDATE_AND_INSERT ); DataElement dataElementB = createDataElement( 'B' ); dataElementB.setUid( ANOTHER_DATA_ELEMENT_ID ); ProgramStageDataElement programStageDataElementB = createProgramStageDataElement( anotherProgramStage, dataElementB, 0 ); anotherProgramStage.setProgramStageDataElements( Sets.newHashSet( programStageDataElementB ) ); when( preheat.get( ProgramStage.class, PROGRAM_STAGE_ID ) ).thenReturn( programStage ); } @Test public void testValidateShowErrorRuleActionForEvents() { Map<String, List<ProgramRuleIssue>> errors = errorImplementer.validateEvents( bundle ); assertErrors( errors, 2 ); } @Test public void testValidateShowErrorRuleActionForEventsWithValidationStrategyOnComplete() { programStage.setValidationStrategy( ValidationStrategy.ON_COMPLETE ); bundle.setRuleEffects( getRuleEventEffectsLinkedToDataElement() ); Map<String, List<ProgramRuleIssue>> errors = errorImplementer.validateEvents( bundle ); assertErrors( errors, 1 ); assertErrorsWithDataElement( errors ); } @Test public void testValidateShowErrorForEventsInDifferentProgramStages() { bundle.setRuleEffects( getRuleEventEffectsLinkedTo2DataElementsIn2DifferentProgramStages() ); Map<String, List<ProgramRuleIssue>> errors = errorImplementer.validateEvents( bundle ); assertErrors( errors, 1 ); assertErrorsWithDataElement( errors ); } @Test public void testValidateShowErrorRuleActionForEnrollment() { Map<String, List<ProgramRuleIssue>> errors = errorImplementer.validateEnrollments( bundle ); assertErrors( errors, 2 ); } @Test public void testValidateShowWarningRuleActionForEvents() { Map<String, List<ProgramRuleIssue>> warnings = warningImplementer.validateEvents( bundle ); assertWarnings( warnings, 2 ); } @Test public void testValidateShowWarningRuleActionForEnrollment() { Map<String, List<ProgramRuleIssue>> warnings = warningImplementer.validateEnrollments( bundle ); assertWarnings( warnings, 2 ); } @Test public void testValidateShowErrorOnCompleteRuleActionForEvents() { Map<String, List<ProgramRuleIssue>> errors = errorOnCompleteImplementer.validateEvents( bundle ); assertErrors( errors, 1 ); } @Test public void testValidateShowErrorOnCompleteRuleActionForEnrollment() { Map<String, List<ProgramRuleIssue>> errors = errorOnCompleteImplementer.validateEnrollments( bundle ); assertErrors( errors, 1 ); } @Test public void testValidateShowWarningOnCompleteRuleActionForEvents() { Map<String, List<ProgramRuleIssue>> warnings = warningOnCompleteImplementer.validateEvents( bundle ); assertWarnings( warnings, 1 ); } @Test public void testValidateShowWarningOnCompleteRuleActionForEnrollment() { Map<String, List<ProgramRuleIssue>> warnings = warningOnCompleteImplementer.validateEnrollments( bundle ); assertWarnings( warnings, 1 ); } public void assertErrors( Map<String, List<ProgramRuleIssue>> errors, int numberOfErrors ) { assertIssues( errors, numberOfErrors, IssueType.ERROR ); } public void assertWarnings( Map<String, List<ProgramRuleIssue>> warnings, int numberOfWarnings ) { assertIssues( warnings, numberOfWarnings, IssueType.WARNING ); } private void assertIssues( Map<String, List<ProgramRuleIssue>> errors, int numberOfErrors, IssueType issueType ) { assertFalse( errors.isEmpty() ); assertEquals( numberOfErrors, errors.size() ); errors.forEach( ( key, value ) -> assertEquals( 1, value.size() ) ); errors .values() .stream() .flatMap( Collection::stream ) .forEach( e -> { assertEquals( "", e.getRuleUid() ); assertEquals( issueType, e.getIssueType() ); assertEquals( TrackerErrorCode.E1300, e.getIssueCode() ); assertTrue( e.getArgs().get( 0 ).contains( issueType.name() + CONTENT + " " + EVALUATED_DATA ) ); } ); } public void assertErrorsWithDataElement( Map<String, List<ProgramRuleIssue>> errors ) { errors .values() .stream() .flatMap( Collection::stream ) .forEach( e -> { assertEquals( "", e.getRuleUid() ); assertEquals( IssueType.ERROR, e.getIssueType() ); assertEquals( TrackerErrorCode.E1300, e.getIssueCode() ); assertEquals( IssueType.ERROR.name() + CONTENT + " " + EVALUATED_DATA + " (" + DATA_ELEMENT_ID + ")", e.getArgs().get( 0 ) ); } ); } private List<Event> getEvents() { Event activeEvent = new Event(); activeEvent.setEvent( ACTIVE_EVENT_ID ); activeEvent.setStatus( EventStatus.ACTIVE ); activeEvent.setProgramStage( PROGRAM_STAGE_ID ); Event completedEvent = new Event(); completedEvent.setEvent( COMPLETED_EVENT_ID ); completedEvent.setStatus( EventStatus.COMPLETED ); completedEvent.setProgramStage( PROGRAM_STAGE_ID ); return Lists.newArrayList( activeEvent, completedEvent ); } private List<Enrollment> getEnrollments() { Enrollment activeEnrollment = new Enrollment(); activeEnrollment.setEnrollment( ACTIVE_ENROLLMENT_ID ); activeEnrollment.setStatus( EnrollmentStatus.ACTIVE ); Enrollment completedEnrollment = new Enrollment(); completedEnrollment.setEnrollment( COMPLETED_ENROLLMENT_ID ); completedEnrollment.setStatus( EnrollmentStatus.COMPLETED ); return Lists.newArrayList( activeEnrollment, completedEnrollment ); } private List<RuleEffects> getRuleEventEffectsLinkedToDataElement() { List<RuleEffects> ruleEffectsByEvent = Lists.newArrayList(); ruleEffectsByEvent .add( new RuleEffects( EVENT, ACTIVE_EVENT_ID, getRuleEffectsLinkedToDataElement() ) ); ruleEffectsByEvent .add( new RuleEffects( EVENT, COMPLETED_EVENT_ID, getRuleEffectsLinkedToDataElement() ) ); return ruleEffectsByEvent; } private List<RuleEffects> getRuleEventEffectsLinkedTo2DataElementsIn2DifferentProgramStages() { List<RuleEffects> ruleEffectsByEvent = Lists.newArrayList(); ruleEffectsByEvent .add( new RuleEffects( EVENT, ACTIVE_EVENT_ID, getRuleEffectsLinkedToDataElement() ) ); ruleEffectsByEvent.add( new RuleEffects( EVENT, COMPLETED_EVENT_ID, getRuleEffectsLinkedToDataAnotherElement() ) ); return ruleEffectsByEvent; } private List<RuleEffects> getRuleEventAndEnrollmentEffects() { List<RuleEffects> ruleEffectsByEvent = Lists.newArrayList(); ruleEffectsByEvent.add( new RuleEffects( EVENT, ACTIVE_EVENT_ID, getRuleEffects() ) ); ruleEffectsByEvent.add( new RuleEffects( EVENT, COMPLETED_EVENT_ID, getRuleEffects() ) ); ruleEffectsByEvent.add( new RuleEffects( ENROLLMENT, ACTIVE_ENROLLMENT_ID, getRuleEffects() ) ); ruleEffectsByEvent .add( new RuleEffects( ENROLLMENT, COMPLETED_ENROLLMENT_ID, getRuleEffects() ) ); return ruleEffectsByEvent; } private List<RuleEffect> getRuleEffects() { RuleAction actionShowWarning = RuleActionShowWarning .create( IssueType.WARNING.name() + CONTENT, DATA, "", UNKNOWN ); RuleAction actionShowWarningOnComplete = RuleActionWarningOnCompletion .create( IssueType.WARNING.name() + CONTENT, DATA, "", UNKNOWN ); RuleAction actionShowError = RuleActionShowError .create( IssueType.ERROR.name() + CONTENT, DATA, "", UNKNOWN ); RuleAction actionShowErrorOnCompletion = RuleActionErrorOnCompletion .create( IssueType.ERROR.name() + CONTENT, DATA, "", UNKNOWN ); return Lists.newArrayList( RuleEffect.create( "", actionShowWarning, EVALUATED_DATA ), RuleEffect.create( "", actionShowWarningOnComplete, EVALUATED_DATA ), RuleEffect.create( "", actionShowError, EVALUATED_DATA ), RuleEffect.create( "", actionShowErrorOnCompletion, EVALUATED_DATA ) ); } private List<RuleEffect> getRuleEffectsLinkedToDataElement() { RuleAction actionShowWarning = RuleActionShowWarning .create( IssueType.WARNING.name() + CONTENT, DATA, DATA_ELEMENT_ID, DATA_ELEMENT ); RuleAction actionShowWarningOnComplete = RuleActionWarningOnCompletion .create( IssueType.WARNING.name() + CONTENT, DATA, DATA_ELEMENT_ID, DATA_ELEMENT ); RuleAction actionShowError = RuleActionShowError .create( IssueType.ERROR.name() + CONTENT, DATA, DATA_ELEMENT_ID, DATA_ELEMENT ); RuleAction actionShowErrorOnCompletion = RuleActionErrorOnCompletion .create( IssueType.ERROR.name() + CONTENT, DATA, DATA_ELEMENT_ID, DATA_ELEMENT ); return Lists.newArrayList( RuleEffect.create( "", actionShowWarning, EVALUATED_DATA ), RuleEffect.create( "", actionShowWarningOnComplete, EVALUATED_DATA ), RuleEffect.create( "", actionShowError, EVALUATED_DATA ), RuleEffect.create( "", actionShowErrorOnCompletion, EVALUATED_DATA ) ); } private List<RuleEffect> getRuleEffectsLinkedToDataAnotherElement() { RuleAction actionShowWarning = RuleActionShowWarning .create( IssueType.WARNING.name() + CONTENT, DATA, ANOTHER_DATA_ELEMENT_ID, DATA_ELEMENT ); RuleAction actionShowWarningOnComplete = RuleActionWarningOnCompletion .create( IssueType.WARNING.name() + CONTENT, DATA, ANOTHER_DATA_ELEMENT_ID, DATA_ELEMENT ); RuleAction actionShowError = RuleActionShowError .create( IssueType.ERROR.name() + CONTENT, DATA, ANOTHER_DATA_ELEMENT_ID, DATA_ELEMENT ); RuleAction actionShowErrorOnCompletion = RuleActionErrorOnCompletion .create( IssueType.ERROR.name() + CONTENT, DATA, ANOTHER_DATA_ELEMENT_ID, DATA_ELEMENT ); return Lists.newArrayList( RuleEffect.create( "", actionShowWarning, EVALUATED_DATA ), RuleEffect.create( "", actionShowWarningOnComplete, EVALUATED_DATA ), RuleEffect.create( "", actionShowError, EVALUATED_DATA ), RuleEffect.create( "", actionShowErrorOnCompletion, EVALUATED_DATA ) ); } }
42.848806
117
0.721617
95cfcd2926614866081fd558ceaaa2e568fabe4a
3,269
/* * Copyright 2015 Adaptris Ltd. * * 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.adaptris.http; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import com.adaptris.security.keystore.KeystoreFactory; import com.adaptris.security.keystore.KeystoreLocation; import com.adaptris.security.keystore.KeystoreProxy; import com.adaptris.security.password.Password; /** * Constants specific to HTTPS. * */ public final class Https { private Https() { } /** SSL_CONTEXT_TYPE is SSL for use with JSSE */ public static final String SSL_CONTEXT_TYPE = "SSL"; /** KEY_MANAGER_TYPE is SunX509 for use with JSSE */ public static final String KEY_MANAGER_TYPE = "SunX509"; /** Property in our adp-http.properties file */ public static final String CONFIG_PRIVATE_KEY_PW = "adp.https.privatekeypassword"; /** Property in our adp-http.properties file */ public static final String CONFIG_KEYSTORE_URL = "adp.https.keystoreurl"; /** Property in our adp-http.properties file */ public static final String CONFIG_KEYSTORE_PW = "adp.https.keystorepassword"; /** The name of the properties */ public static final String CONFIG_PROPERTY_FILE = "adp-http.properties"; private static boolean initialised = false; private static Properties httpsProperties; static char[] getPrivateKeyPassword(char[] pkpw) throws IOException { if (pkpw != null) { return pkpw; } initialise(); if (httpsProperties.getProperty(CONFIG_PRIVATE_KEY_PW) == null) { throw new IOException("Could not find private key to use in " + CONFIG_PROPERTY_FILE); } return httpsProperties.getProperty(CONFIG_PRIVATE_KEY_PW).toCharArray(); } static KeystoreProxy getKeystoreProxy(KeystoreProxy ksp) throws Exception { if (ksp != null) { return ksp; } initialise(); String url = httpsProperties.getProperty(CONFIG_KEYSTORE_URL); if (url == null) { throw new IOException("Could not a keystore url to use in " + CONFIG_PROPERTY_FILE); } String pw = httpsProperties.getProperty(CONFIG_KEYSTORE_PW); KeystoreLocation ksl = null; if (pw != null) { ksl = KeystoreFactory.getDefault().create(url, Password.decode(pw).toCharArray()); } else { ksl = KeystoreFactory.getDefault().create(url); } return KeystoreFactory.getDefault().create(ksl); } private static void initialise() throws IOException { if (initialised) { return; } httpsProperties = new Properties(); InputStream is = Https.class.getClassLoader().getResourceAsStream( CONFIG_PROPERTY_FILE); if (is != null) { httpsProperties.load(is); is.close(); } initialised = true; } }
33.357143
88
0.71245
c40c7e5ef675187126205fa6d3ce04c3856f81be
441
package som.interpreter.nodes.literals; import som.vm.constants.Nil; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.source.SourceSection; public final class NilLiteralNode extends LiteralNode { public NilLiteralNode(final SourceSection source) { super(source); assert source != null; } @Override public Object executeGeneric(final VirtualFrame frame) { return Nil.nilObject; } }
20.045455
58
0.761905
9171550f6bfd3ac0a0d37906ca3845de8c81e20a
998
package com.backbase.billpay.fiserv.payeessummary.model; import com.backbase.billpay.fiserv.common.model.AbstractResponse; import com.backbase.billpay.fiserv.common.model.ResultType; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor @XmlRootElement(name = "EbillListResponse") @XmlAccessorType(XmlAccessType.FIELD) public class EbillListResponse extends AbstractResponse { @XmlElement(name = "EbillList") private List<Ebill> ebillList; @Builder public EbillListResponse(List<Ebill> ebillList, ResultType result) { super(result); this.ebillList = ebillList; } }
27.722222
72
0.793587
4b42e98f6192c689e383447c74f86b3da96619cd
917
package com.google.refine.model.metadata.validator.checks; import org.json.JSONObject; import com.google.refine.model.Cell; import com.google.refine.model.Project; import io.frictionlessdata.tableschema.Field; public class MinimumLengthConstraint extends AbstractValidator { private int minLength; public MinimumLengthConstraint(Project project, int cellIndex, JSONObject options) { super(project, cellIndex, options); this.code = "minimum-length-constrain"; minLength = (int)column.getConstraints() .get(Field.CONSTRAINT_KEY_MIN_LENGTH); } @Override public boolean filter(Cell cell) { return true; } @Override public boolean checkCell(Cell cell) { if (cell == null || cell.value == null) return false; return cell.value.toString().length() >= minLength; } }
26.2
88
0.657579
fc99435db585330e857145096417a4612ccb12ac
5,568
package frc.robot.subsystems; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.FeedbackDevice; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; public class Intake extends SubsystemBase { // ---------------------------------------------------------- // Resources private final DigitalInput m_whiskerSensor = new DigitalInput(Constants.Intake.kWhiskerSensorDIOPort); private final WPI_TalonSRX m_feederMotor = new WPI_TalonSRX(Constants.Intake.CAN_ID.kFeeder); private final WPI_TalonFX m_retractorMotor = new WPI_TalonFX(Constants.Intake.CAN_ID.kRetractor); private double m_retractorSetDegree = 0., m_feederSetPercent = 0.; // ---------------------------------------------------------- // Constructor public Intake() { // ---------------------------------------------------------- // Feeder motor configuration m_feederMotor.configFactoryDefault(); m_feederMotor.configOpenloopRamp(Constants.Intake.kFeederRampTime); m_feederMotor.setInverted(true); // ---------------------------------------------------------- // Retractor motor configuration m_retractorMotor.configFactoryDefault(); m_retractorMotor.configOpenloopRamp(Constants.Intake.kRetractorOpenLoopRampSeconds); m_retractorMotor.configSelectedFeedbackSensor(FeedbackDevice.IntegratedSensor, Constants.Intake.kRetractorPidIdx, Constants.Intake.kTimeoutMs); // ---------------------------------------------------------- // Final setup configurePIDs(); } // ---------------------------------------------------------- // Constants-reconfiguration methods public void configurePIDs() { m_retractorMotor.config_kP(Constants.Intake.kRetractorSlotIdx, Constants.Intake.kRetractorPositionGains.kP); m_retractorMotor.config_kI(Constants.Intake.kRetractorSlotIdx, Constants.Intake.kRetractorPositionGains.kI); m_retractorMotor.config_kD(Constants.Intake.kRetractorSlotIdx, Constants.Intake.kRetractorPositionGains.kD); // m_retractorMotor.config_kF(Constants.Intake.kRetractorSlotIdx, Constants.Intake.kRetractorPositionGains.kF); } // ---------------------------------------------------------- // Scheduler methods // @Override // public void periodic() { // updateRetractorOrigin(); // } // ---------------------------------------------------------- // Ball-intake whisker sensor public boolean whiskerSensorIsActive() { return m_whiskerSensor.get(); } // ---------------------------------------------------------- // Retractor motor public void updateRetractorOrigin() { if (getRetractorDegree() < 0) { resetRetractorEncoder(); } } public void resetRetractorEncoder() { m_retractorMotor.setSelectedSensorPosition(0.); } public void brakeRetractor() { m_retractorMotor.setNeutralMode(NeutralMode.Brake); } public void coastRetractor() { m_retractorMotor.setNeutralMode(NeutralMode.Coast); } public boolean retractorIsRetracting() { return m_retractorSetDegree == Constants.Intake.kRetractorUpDegree; } public boolean retractorIsExtending() { return m_retractorSetDegree == Constants.Intake.kRetractorDownDegree; } public double getRetractorDegree() { return m_retractorMotor.getSelectedSensorPosition(Constants.Intake.kRetractorPidIdx) / Constants.Intake.kRetractorOutputDegreesToInputTicks; } private boolean withinRetractorDegreeRange(double degree) { return (degree >= Constants.Intake.kRetractorMinDegree && degree <= Constants.Intake.kRetractorMaxDegree); } public void setRetractorDegree(double degree) { if (withinRetractorDegreeRange(degree)) { m_retractorMotor.set(ControlMode.Position, degree * Constants.Intake.kRetractorOutputDegreesToInputTicks); m_retractorSetDegree = degree; } } public void retractIntakeArm() { brakeRetractor(); setRetractorDegree(Constants.Intake.kRetractorUpDegree); } // true means it is satisfiably close to the retracted-arm degree, false means it is not // false DOES NOT NECESSARILY MEAN that the intake arm is extended public boolean armIsWithinRetractedTolerance() { return Math.abs(getRetractorDegree() - Constants.Intake.kRetractorUpDegree) <= Constants.Intake.kRetractorDegreeTolerance; } public void extendIntakeArm() { brakeRetractor(); setRetractorDegree(Constants.Intake.kRetractorDownDegree); } // true means it is satisfiably close to the extended-arm degree, false means it is not // false DOES NOT NECESSARILY MEAN that the intake arm is retracted // public boolean armIsWithinExtendedTolerance() { // return Math.abs(getRetractorDegree() - Constants.Intake.kRetractorDownDegree) <= Constants.Intake.kRetractorDegreeTolerance; // } // ---------------------------------------------------------- // Feeder motor public boolean feederIsRunning() { return m_feederSetPercent == Constants.Intake.kFeederPercent; } // -1 to 1 public double getFeederPercent() { return m_feederMotor.get(); } // -1 to 1 public void setFeederPercent(double percent) { m_feederMotor.set(ControlMode.PercentOutput, percent); m_feederSetPercent = percent; } public void runFeeder() { setFeederPercent(Constants.Intake.kFeederPercent); } public void runReverseFeeder() { setFeederPercent(Constants.Intake.kReverseFeederPercent); } public void stopFeeder() { setFeederPercent(0.); } }
29.935484
145
0.699174
15ce02d02d8857462dabbe55de3299be6497169d
442
package org.mini2Dx.invaders.desktop; import org.mini2Dx.desktop.DesktopMini2DxConfig; import com.badlogic.gdx.backends.lwjgl.DesktopMini2DxGame; import org.mini2Dx.invaders.InvadersGame; public class DesktopLauncher { public static void main (String[] arg) { DesktopMini2DxConfig config = new DesktopMini2DxConfig(InvadersGame.GAME_IDENTIFIER); config.vSyncEnabled = true; new DesktopMini2DxGame(new InvadersGame(), config); } }
27.625
87
0.807692
b5c4be41001fab1fb4b595931a424323da98edc6
33,527
/************************************************************************* * * * EJBCA Community: The OpenSource Certificate Authority * * * * This software 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 2.1 of the License, or any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.ejbca.core.ejb.ra; import java.math.BigInteger; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.cesecore.authentication.tokens.AlwaysAllowLocalAuthenticationToken; import org.cesecore.authentication.tokens.AuthenticationToken; import org.cesecore.authentication.tokens.UsernamePrincipal; import org.cesecore.authorization.AuthorizationDeniedException; import org.cesecore.authorization.AuthorizationSessionLocal; import org.cesecore.authorization.control.StandardRules; import org.cesecore.certificates.ca.CADoesntExistsException; import org.cesecore.certificates.ca.CaSessionLocal; import org.cesecore.certificates.certificate.CertificateConstants; import org.cesecore.certificates.certificate.CertificateStoreSessionLocal; import org.cesecore.certificates.certificate.CertificateWrapper; import org.cesecore.certificates.endentity.EndEntityConstants; import org.cesecore.certificates.endentity.EndEntityInformation; import org.cesecore.config.GlobalCesecoreConfiguration; import org.cesecore.configuration.GlobalConfigurationSessionLocal; import org.cesecore.jndi.JndiConstants; import org.cesecore.util.CertTools; import org.cesecore.util.EJBTools; import org.cesecore.util.StringTools; import org.ejbca.config.GlobalConfiguration; import org.ejbca.core.EjbcaException; import org.ejbca.core.ejb.ra.raadmin.EndEntityProfileSessionLocal; import org.ejbca.core.model.InternalEjbcaResources; import org.ejbca.core.model.SecConst; import org.ejbca.core.model.authorization.AccessRulesConstants; import org.ejbca.core.model.ra.NotFoundException; import org.ejbca.core.model.ra.RAAuthorization; import org.ejbca.util.crypto.SupportedPasswordHashAlgorithm; import org.ejbca.util.query.BasicMatch; import org.ejbca.util.query.IllegalQueryException; import org.ejbca.util.query.Query; import org.ejbca.util.query.UserMatch; /** * @version $Id: EndEntityAccessSessionBean.java 29301 2018-06-21 10:27:38Z andresjakobs $ * */ @Stateless(mappedName = JndiConstants.APP_JNDI_PREFIX + "EndEntityAccessSessionRemote") @TransactionAttribute(TransactionAttributeType.SUPPORTS) public class EndEntityAccessSessionBean implements EndEntityAccessSessionLocal, EndEntityAccessSessionRemote { /** Columns in the database used in select. */ private static final String USERDATA_CREATED_COL = "timeCreated"; private static final Logger log = Logger.getLogger(EndEntityAccessSessionBean.class); /** Internal localization of logs and errors */ private static final InternalEjbcaResources intres = InternalEjbcaResources.getInstance(); @PersistenceContext(unitName = "ejbca") private EntityManager entityManager; @EJB private AuthorizationSessionLocal authorizationSession; @EJB private CaSessionLocal caSession; @EJB private EndEntityProfileSessionLocal endEntityProfileSession; @EJB private GlobalConfigurationSessionLocal globalConfigurationSession; @EJB private CertificateStoreSessionLocal certificateStoreSession; @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public AbstractMap.SimpleEntry<String, SupportedPasswordHashAlgorithm> getPasswordAndHashAlgorithmForUser(String username) throws NotFoundException { UserData user = findByUsername(username); if (user == null) { throw new NotFoundException("End Entity of name " + username + " not found in database"); } else { return new AbstractMap.SimpleEntry<String, SupportedPasswordHashAlgorithm>(user.getPasswordHash(), user.findHashAlgorithm()); } } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<EndEntityInformation> findUserBySubjectDN(final AuthenticationToken admin, final String subjectdn) throws AuthorizationDeniedException { if (log.isTraceEnabled()) { log.trace(">findUserBySubjectDN(" + subjectdn + ")"); } // String used in SQL so strip it final String dn = CertTools.stringToBCDNString(StringTools.strip(subjectdn)); if (log.isDebugEnabled()) { log.debug("Looking for users with subjectdn: " + dn); } final TypedQuery<UserData> query = entityManager.createQuery("SELECT a FROM UserData a WHERE a.subjectDN=:subjectDN", UserData.class); query.setParameter("subjectDN", dn); final List<UserData> dataList = query.getResultList(); if (dataList.size() == 0) { if (log.isDebugEnabled()) { log.debug("Cannot find user with subjectdn: " + dn); } } final List<EndEntityInformation> result = new ArrayList<EndEntityInformation>(); for (UserData data : dataList) { result.add(convertUserDataToEndEntityInformation(admin, data, null)); } if (log.isTraceEnabled()) { log.trace("<findUserBySubjectDN(" + subjectdn + ")"); } return result; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<UserData> findNewOrKeyrecByHardTokenIssuerId(int hardTokenIssuerId, int maxResults) { final TypedQuery<UserData> query = entityManager .createQuery("SELECT a FROM UserData a WHERE a.hardTokenIssuerId=:hardTokenIssuerId AND a.tokenType>=:tokenType AND (a.status=:status1 OR a.status=:status2)", UserData.class); query.setParameter("hardTokenIssuerId", hardTokenIssuerId); query.setParameter("tokenType", SecConst.TOKEN_HARD_DEFAULT); query.setParameter("status1", EndEntityConstants.STATUS_NEW); query.setParameter("status2", EndEntityConstants.STATUS_KEYRECOVERY); if (maxResults > 0) { query.setMaxResults(maxResults); } return query.getResultList(); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<String> findSubjectDNsByCaIdAndNotUsername(final int caId, final String username, final String serialnumber) { final TypedQuery<String> query = entityManager .createQuery("SELECT a.subjectDN FROM UserData a WHERE a.caId=:caId AND a.username!=:username AND a.subjectDN LIKE :serial", String.class); query.setParameter("caId", caId); query.setParameter("username", username); query.setParameter("serial", "%SN="+ serialnumber + "%"); return query.getResultList(); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<EndEntityInformation> findUserBySubjectAndIssuerDN(final AuthenticationToken admin, final String subjectdn, final String issuerdn) throws AuthorizationDeniedException { if (log.isTraceEnabled()) { log.trace(">findUserBySubjectAndIssuerDN(" + subjectdn + ", " + issuerdn + ")"); } // String used in SQL so strip it final String dn = CertTools.stringToBCDNString(StringTools.strip(subjectdn)); final String issuerDN = CertTools.stringToBCDNString(StringTools.strip(issuerdn)); if (log.isDebugEnabled()) { log.debug("Looking for users with subjectdn: " + dn + ", issuerdn : " + issuerDN); } final TypedQuery<UserData> query = entityManager.createQuery("SELECT a FROM UserData a WHERE a.subjectDN=:subjectDN AND a.caId=:caId", UserData.class); query.setParameter("subjectDN", dn); query.setParameter("caId", issuerDN.hashCode()); final List<UserData> dataList = query.getResultList(); if (dataList.size() == 0) { if (log.isDebugEnabled()) { log.debug("Cannot find user with subjectdn: " + dn + ", issuerdn : " + issuerDN); } } final List<EndEntityInformation> result = new ArrayList<EndEntityInformation>(); for (UserData data : dataList) { result.add(convertUserDataToEndEntityInformation(admin, data, null)); } if (log.isTraceEnabled()) { log.trace("<findUserBySubjectAndIssuerDN(" + subjectdn + ", " + issuerDN + ")"); } return result; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public EndEntityInformation findUser(final String username) { try { return findUser(new AlwaysAllowLocalAuthenticationToken(new UsernamePrincipal("Internal search for End Entity")), username); } catch (AuthorizationDeniedException e) { throw new IllegalStateException("Always allow token was denied authorization.", e); } } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public EndEntityInformation findUser(final AuthenticationToken admin, final String username) throws AuthorizationDeniedException { if (log.isTraceEnabled()) { log.trace(">findUser(" + username + ")"); } final UserData data = findByUsername(username); if (data == null) { if (log.isDebugEnabled()) { log.debug("Cannot find user with username='" + username + "'"); } } final EndEntityInformation ret = convertUserDataToEndEntityInformation(admin, data, username); if (log.isTraceEnabled()) { log.trace("<findUser(" + username + "): " + (ret == null ? "null" : ret.getDN())); } return ret; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public UserData findByUsername(String username) { if (username == null) { return null; } return entityManager.find(UserData.class, username); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<EndEntityInformation> findUserByEmail(AuthenticationToken admin, String email) throws AuthorizationDeniedException { if (log.isTraceEnabled()) { log.trace(">findUserByEmail(" + email + ")"); } if (log.isDebugEnabled()) { log.debug("Looking for user with email: " + email); } final TypedQuery<UserData> query = entityManager.createQuery("SELECT a FROM UserData a WHERE a.subjectEmail=:subjectEmail", UserData.class); query.setParameter("subjectEmail", email); final List<UserData> result = query.getResultList(); if (result.size() == 0) { if (log.isDebugEnabled()) { log.debug("Cannot find user with Email='" + email + "'"); } } final List<EndEntityInformation> returnval = new ArrayList<EndEntityInformation>(); for (final UserData data : result) { if (((GlobalConfiguration) globalConfigurationSession.getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID)) .getEnableEndEntityProfileLimitations()) { // Check if administrator is authorized to view user. if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AccessRulesConstants.VIEW_END_ENTITY)) { continue; } } if (!authorizedToCA(admin, data.getCaId())) { continue; } returnval.add(convertUserDataToEndEntityInformation(admin, data, null)); } if (log.isTraceEnabled()) { log.trace("<findUserByEmail(" + email + ")"); } return returnval; } /** * @return the userdata value object if admin is authorized. Does not leak username if auth fails. * * @throws AuthorizationDeniedException if the admin was not authorized to the end entity profile or issuing CA */ private EndEntityInformation convertUserDataToEndEntityInformation(final AuthenticationToken admin, final UserData data, final String requestedUsername) throws AuthorizationDeniedException { if (data != null) { if (((GlobalConfiguration) globalConfigurationSession.getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID)) .getEnableEndEntityProfileLimitations()) { // Check if administrator is authorized to view user. if (!authorizedToEndEntityProfile(admin, data.getEndEntityProfileId(), AccessRulesConstants.VIEW_END_ENTITY)) { if (requestedUsername == null) { final String msg = intres.getLocalizedMessage("ra.errorauthprofile", Integer.valueOf(data.getEndEntityProfileId()), admin.toString()); throw new AuthorizationDeniedException(msg); } else { final String msg = intres.getLocalizedMessage("ra.errorauthprofileexist", Integer.valueOf(data.getEndEntityProfileId()), requestedUsername, admin.toString()); throw new AuthorizationDeniedException(msg); } } } if (!authorizedToCA(admin, data.getCaId())) { if (requestedUsername == null) { final String msg = intres.getLocalizedMessage("ra.errorauthca", Integer.valueOf(data.getCaId()), admin.toString()); throw new AuthorizationDeniedException(msg); } else { final String msg = intres.getLocalizedMessage("ra.errorauthcaexist", Integer.valueOf(data.getCaId()), requestedUsername, admin.toString()); throw new AuthorizationDeniedException(msg); } } return data.toEndEntityInformation(); } return null; } private boolean authorizedToEndEntityProfile(AuthenticationToken admin, int profileid, String rights) { boolean returnval = false; if (profileid == EndEntityConstants.EMPTY_END_ENTITY_PROFILE && (rights.equals(AccessRulesConstants.CREATE_END_ENTITY) || rights.equals(AccessRulesConstants.EDIT_END_ENTITY))) { if (authorizationSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) { returnval = true; } else { log.info("Admin " + admin.toString() + " was not authorized to resource " + StandardRules.ROLE_ROOT); } } else { returnval = authorizationSession.isAuthorizedNoLogging(admin, AccessRulesConstants.ENDENTITYPROFILEPREFIX + profileid + rights, AccessRulesConstants.REGULAR_RAFUNCTIONALITY + rights); } return returnval; } private boolean authorizedToCA(AuthenticationToken admin, int caid) { boolean returnval = false; returnval = authorizationSession.isAuthorizedNoLogging(admin, StandardRules.CAACCESS.resource() + caid); if (!returnval) { log.info("Admin " + admin.toString() + " not authorized to resource " + StandardRules.CAACCESS.resource() + caid); } return returnval; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public Collection<EndEntityInformation> findAllUsersByStatus(AuthenticationToken admin, int status) { if (log.isTraceEnabled()) { log.trace(">findAllUsersByStatus(" + status + ")"); } if (log.isDebugEnabled()) { log.debug("Looking for users with status: " + status); } Query query = new Query(Query.TYPE_USERQUERY); query.add(UserMatch.MATCH_WITH_STATUS, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(status)); Collection<EndEntityInformation> returnval = null; try { returnval = query(admin, query, null, null, 0, AccessRulesConstants.VIEW_END_ENTITY); } catch (IllegalQueryException e) { } if (log.isDebugEnabled()) { log.debug("found " + returnval.size() + " user(s) with status=" + status); } if (log.isTraceEnabled()) { log.trace("<findAllUsersByStatus(" + status + ")"); } return returnval; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public Collection<EndEntityInformation> findAllUsersByCaId(AuthenticationToken admin, int caid) { if (log.isTraceEnabled()) { log.trace(">findAllUsersByCaId(" + caid + ")"); } if (log.isDebugEnabled()) { log.debug("Looking for users with caid: " + caid); } Query query = new Query(Query.TYPE_USERQUERY); query.add(UserMatch.MATCH_WITH_CA, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(caid)); Collection<EndEntityInformation> returnval = null; try { returnval = query(admin, query, null, null, 0, AccessRulesConstants.VIEW_END_ENTITY); } catch (IllegalQueryException e) { // Ignore ?? log.debug("Illegal query", e); returnval = new ArrayList<EndEntityInformation>(); } if (log.isDebugEnabled()) { log.debug("found " + returnval.size() + " user(s) with caid=" + caid); } if (log.isTraceEnabled()) { log.trace("<findAllUsersByCaId(" + caid + ")"); } return returnval; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public long countByCaId(int caId) { final javax.persistence.Query query = entityManager.createQuery("SELECT COUNT(a) FROM UserData a WHERE a.caId=:caId"); query.setParameter("caId", caId); return ((Long) query.getSingleResult()).longValue(); // Always returns a result } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public long countByCertificateProfileId(int certificateProfileId) { final javax.persistence.Query query = entityManager.createQuery("SELECT COUNT(a) FROM UserData a WHERE a.certificateProfileId=:certificateProfileId"); query.setParameter("certificateProfileId", certificateProfileId); return ((Long) query.getSingleResult()).longValue(); // Always returns a result } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public long countByHardTokenIssuerId(int hardTokenIssuerId) { final javax.persistence.Query query = entityManager.createQuery("SELECT COUNT(a) FROM UserData a WHERE a.hardTokenIssuerId=:hardTokenIssuerId"); query.setParameter("hardTokenIssuerId", hardTokenIssuerId); return ((Long) query.getSingleResult()).longValue(); // Always returns a result } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public long countByHardTokenProfileId(int hardTokenProfileId) { final javax.persistence.Query query = entityManager.createQuery("SELECT COUNT(a) FROM UserData a WHERE a.tokenType=:tokenType"); query.setParameter("tokenType", hardTokenProfileId); return ((Long) query.getSingleResult()).longValue(); // Always returns a result } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public long countNewOrKeyrecByHardTokenIssuerId(int hardTokenIssuerId) { final javax.persistence.Query query = entityManager .createQuery("SELECT COUNT(a) FROM UserData a WHERE a.hardTokenIssuerId=:hardTokenIssuerId AND a.tokenType>=:tokenType AND (a.status=:status1 OR a.status=:status2)"); query.setParameter("hardTokenIssuerId", hardTokenIssuerId); query.setParameter("tokenType", SecConst.TOKEN_HARD_DEFAULT); query.setParameter("status1", EndEntityConstants.STATUS_NEW); query.setParameter("status2", EndEntityConstants.STATUS_KEYRECOVERY); return ((Long) query.getSingleResult()).longValue(); // Always returns a result } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<EndEntityInformation> findAllBatchUsersByStatusWithLimit(int status) { if (log.isTraceEnabled()) { log.trace(">findAllUsersByStatusWithLimit()"); } final javax.persistence.Query query = entityManager .createQuery("SELECT a FROM UserData a WHERE a.status=:status AND (clearPassword IS NOT NULL)"); query.setParameter("status", status); query.setMaxResults(getGlobalCesecoreConfiguration().getMaximumQueryCount()); @SuppressWarnings("unchecked") final List<UserData> userDataList = query.getResultList(); final List<EndEntityInformation> returnval = new ArrayList<EndEntityInformation>(userDataList.size()); for (UserData ud : userDataList) { EndEntityInformation endEntityInformation = ud.toEndEntityInformation(); if (endEntityInformation.getPassword() != null && endEntityInformation.getPassword().length() > 0) { returnval.add(endEntityInformation); } } if (log.isTraceEnabled()) { log.trace("<findAllUsersByStatusWithLimit()"); } return returnval; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public Collection<EndEntityInformation> query(final AuthenticationToken admin, final Query query, final String caauthorizationstr, final String endentityprofilestr, final int numberofrows, final String endentityAccessRule) throws IllegalQueryException { boolean authorizedtoanyprofile = true; final String caauthorizationstring = StringTools.strip(caauthorizationstr); final String endentityprofilestring = StringTools.strip(endentityprofilestr); final ArrayList<EndEntityInformation> returnval = new ArrayList<EndEntityInformation>(); int fetchsize = getGlobalCesecoreConfiguration().getMaximumQueryCount(); if (numberofrows != 0) { fetchsize = numberofrows; } // Check if query is legal. if (query != null && !query.isLegalQuery()) { throw new IllegalQueryException(); } String sqlquery = ""; if (query != null) { sqlquery += query.getQueryString(); } final GlobalConfiguration globalconfiguration = getGlobalConfiguration(); String caauthstring = caauthorizationstring; String endentityauth = endentityprofilestring; RAAuthorization raauthorization = null; if (caauthorizationstring == null || endentityprofilestring == null) { raauthorization = new RAAuthorization(admin, globalConfigurationSession, authorizationSession, caSession, endEntityProfileSession); caauthstring = raauthorization.getCAAuthorizationString(); if (globalconfiguration.getEnableEndEntityProfileLimitations()) { endentityauth = raauthorization.getEndEntityProfileAuthorizationString(true, endentityAccessRule); } else { endentityauth = ""; } } if (!StringUtils.isBlank(caauthstring)) { if (StringUtils.isBlank(sqlquery)) { sqlquery += caauthstring; } else { sqlquery = "(" + sqlquery + ") AND " + caauthstring; } } if (globalconfiguration.getEnableEndEntityProfileLimitations()) { if (endentityauth == null || StringUtils.isBlank(endentityauth)) { authorizedtoanyprofile = false; } else { if (StringUtils.isEmpty(sqlquery)) { sqlquery += endentityauth; } else { sqlquery = "(" + sqlquery + ") AND " + endentityauth; } } } // Finally order the return values sqlquery += " ORDER BY " + USERDATA_CREATED_COL + " DESC"; if (log.isDebugEnabled()) { log.debug("generated query: " + sqlquery); } if (authorizedtoanyprofile) { final javax.persistence.Query dbQuery = entityManager.createQuery("SELECT a FROM UserData a WHERE " + sqlquery); if (fetchsize > 0) { dbQuery.setMaxResults(fetchsize); } @SuppressWarnings("unchecked") final List<UserData> userDataList = dbQuery.getResultList(); for (UserData userData : userDataList) { returnval.add(userData.toEndEntityInformation()); } } else { if (log.isDebugEnabled()) { log.debug("authorizedtoanyprofile=false"); } } if (log.isTraceEnabled()) { log.trace("<query(): " + returnval.size()); } return returnval; } private GlobalCesecoreConfiguration getGlobalCesecoreConfiguration() { return (GlobalCesecoreConfiguration) globalConfigurationSession.getCachedConfiguration(GlobalCesecoreConfiguration.CESECORE_CONFIGURATION_ID); } /** Gets the Global Configuration from ra admin session bean */ private GlobalConfiguration getGlobalConfiguration() { return (GlobalConfiguration) globalConfigurationSession.getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public Collection<EndEntityInformation> findAllUsersWithLimit(AuthenticationToken admin) { if (log.isTraceEnabled()) { log.trace(">findAllUsersWithLimit()"); } Collection<EndEntityInformation> returnval = null; try { returnval = query(admin, null, null, null, 0, AccessRulesConstants.VIEW_END_ENTITY); } catch (IllegalQueryException e) { } if (log.isTraceEnabled()) { log.trace("<findAllUsersWithLimit()"); } return returnval; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<EndEntityInformation> findAllUsersByCaIdNoAuth(int caid) { if (log.isTraceEnabled()) { log.trace(">findAllUsersByCaIdNoAuth()"); } final TypedQuery<UserData> query = entityManager.createQuery("SELECT a FROM UserData a WHERE a.caId=:caId", UserData.class); query.setParameter("caId", caid); final List<UserData> userDataList = query.getResultList(); final List<EndEntityInformation> returnval = new ArrayList<EndEntityInformation>(userDataList.size()); for (UserData ud : userDataList) { returnval.add(ud.toEndEntityInformation()); } if (log.isTraceEnabled()) { log.trace("<findAllUsersByCaIdNoAuth()"); } return returnval; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<UserData> findByEndEntityProfileId(int endentityprofileid) { if (log.isTraceEnabled()) { log.trace(">findByEndEntityProfileId(" + endentityprofileid + ")"); } final TypedQuery<UserData> query = entityManager.createQuery("SELECT a FROM UserData a WHERE a.endEntityProfileId=:endEntityProfileId", UserData.class); query.setParameter("endEntityProfileId", endentityprofileid); List<UserData> found = query.getResultList(); if (log.isTraceEnabled()) { log.trace("<findByEndEntityProfileId(" + endentityprofileid + "), found: " + found.size()); } return found; } @TransactionAttribute(TransactionAttributeType.SUPPORTS) @Override public List<String> findByCertificateProfileId(int certificateprofileid) { if (log.isTraceEnabled()) { log.trace(">checkForCertificateProfileId("+certificateprofileid+")"); } final javax.persistence.Query query = entityManager.createQuery("SELECT a FROM UserData a WHERE a.certificateProfileId=:certificateProfileId"); query.setParameter("certificateProfileId", certificateprofileid); List<String> result = new ArrayList<String>(); for(Object userDataObject : query.getResultList()) { result.add(((UserData) userDataObject).getUsername()); } if (log.isTraceEnabled()) { log.trace("<checkForCertificateProfileId("+certificateprofileid+"): "+result.size()); } return result; } @Override public CertificateWrapper getCertificate(AuthenticationToken authenticationToken, String certSNinHex, String issuerDN) throws AuthorizationDeniedException, CADoesntExistsException, EjbcaException { final String bcString = CertTools.stringToBCDNString(issuerDN); final int caId = bcString.hashCode(); caSession.verifyExistenceOfCA(caId); final String[] rules = {StandardRules.CAFUNCTIONALITY.resource()+"/view_certificate", StandardRules.CAACCESS.resource() + caId}; if(!authorizationSession.isAuthorizedNoLogging(authenticationToken, rules)) { final String msg = intres.getLocalizedMessage("authorization.notauthorizedtoresource", Arrays.toString(rules), null); throw new AuthorizationDeniedException(msg); } final Certificate result = certificateStoreSession.findCertificateByIssuerAndSerno(issuerDN, new BigInteger(certSNinHex,16)); if (log.isDebugEnabled()) { log.debug("Found certificate for issuer '" + issuerDN + "' and SN " + certSNinHex + " for admin " + authenticationToken.getUniqueId()); } return EJBTools.wrap(result); } @Override public Collection<CertificateWrapper> findCertificatesByUsername(final AuthenticationToken authenticationToken, final String username, final boolean onlyValid, final long now) throws AuthorizationDeniedException, CertificateEncodingException { if (log.isDebugEnabled()) { log.debug( "Find certificates by username requested by " + authenticationToken.getUniqueId()); } // Check authorization on current CA and profiles and view_end_entity by looking up the end entity. if (findUser(authenticationToken, username) == null) { if (log.isDebugEnabled()) { log.debug(intres.getLocalizedMessage("ra.errorentitynotexist", username)); } } // Even if there is no end entity, it might be the case that we don't store UserData, so we still need to check CertificateData. Collection<CertificateWrapper> searchResults; if (onlyValid) { // We will filter out not yet valid certificates later on, but we as the database to not return any expired certificates searchResults = EJBTools.wrapCertCollection(certificateStoreSession.findCertificatesByUsernameAndStatusAfterExpireDate(username, CertificateConstants.CERT_ACTIVE, now)); } else { searchResults = certificateStoreSession.findCertificatesByUsername(username); } // Assume the user may have certificates from more than one CA. Certificate certificate = null; int caId = -1; Boolean authorized = null; final Map<Integer, Boolean> authorizationCache = new HashMap<>(); final List<CertificateWrapper> result = new ArrayList<>(); for (Object searchResult: searchResults) { certificate = ((CertificateWrapper) searchResult).getCertificate(); caId = CertTools.getIssuerDN(certificate).hashCode(); authorized = authorizationCache.get(caId); if (authorized == null) { authorized = authorizationSession.isAuthorizedNoLogging(authenticationToken, StandardRules.CAACCESS.resource() + caId); authorizationCache.put(caId, authorized); } if (authorized.booleanValue()) { result.add((CertificateWrapper) searchResult); } } if (log.isDebugEnabled()) { log.debug( "Found " + result.size() + " certificate(s) by username requested by " + authenticationToken.getUniqueId()); } return result; } }
48.873178
191
0.661258
f82372a29b6bf3d9c71623b613c6102f3249fbcd
696
package net.canarymod.util; import net.canarymod.api.nbt.BaseTag; import net.canarymod.api.nbt.CanaryBaseTag; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; /** * JSON NBT Utility implementation * * @author Jason Jones (darkdiplomat) */ public class CanaryJsonNBTUtility implements JsonNBTUtility { @Override public BaseTag jsonToNBT(String rawJson) { try { return CanaryBaseTag.wrap(JsonToNBT.a(rawJson)); } catch (NBTException nbtex) { throw new RuntimeException(nbtex); } } @Override public String baseTagToJSON(BaseTag baseTag) { return baseTag.toString(); // WAT } }
23.2
61
0.679598
241272befce1f9ad4663d6a36e4806be9c74cd48
1,138
package pacote.tutorial.orientacao.oo.java; public class PassagemParametros { // Variável da classe static int classeVar = 0; public static void main(String[] args) { // Variáveis para teste int a = 1; int b = 2; int[] vet = new int[2]; vet[0] = 1; vet[1] = 2; System.out.println("Print FORA do método: a = " + a + "; b = " + b); soma(a, b); System.out.println("Print FORA do método: a = " + a + "; b = " + b); System.out.println("\n\n"); System.out.println("Print FORA do método: a = " + vet[0] + "; b = " + vet[1]); soma(vet); System.out.println("Print FORA do método: a = " + vet[0] + "; b = " + vet[1]); System.out.println(classeVar); classeVar = 9; System.out.println(classeVar); PassagemParametros.classeVar = 10; } // Método soma static void soma (int a, int b) { int temp = a; a = b; b = temp; System.out.println("Print DENTRO do método: a = " + a + "; b = " + b); } static void soma (int[] vet) { int temp = vet[0]; vet[0] = vet[1]; vet[1] = temp; System.out.println("Print DENTRO do método: a = " + vet[0] + "; b = " + vet[1]); } }
22.76
82
0.56239
343019256773296579c5f864c06e967135c148bd
1,861
package org.jdc.template.prefs.base; import android.content.SharedPreferences; @SuppressWarnings("unused") public abstract class PrefsBase { public abstract SharedPreferences getPreferences(); public void saveString(String key, String value) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putString(key, value); editor.apply(); } public void saveLong(String key, long value) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(key, value); editor.apply(); } public void saveInt(String key, int value) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putInt(key, value); editor.apply(); } public void saveFloat(String key, float value) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putFloat(key, value); editor.apply(); } public void saveBoolean(String key, boolean value) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putBoolean(key, value); editor.apply(); } public void remove(String key) { SharedPreferences.Editor editor = getPreferences().edit(); editor.remove(key); editor.apply(); } public void reset() { // clear ALL preferences SharedPreferences.Editor editor = getPreferences().edit(); editor.clear(); editor.apply(); } public void registerChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { getPreferences().registerOnSharedPreferenceChangeListener(listener); } public void unregisterChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { getPreferences().unregisterOnSharedPreferenceChangeListener(listener); } }
31.016667
103
0.676518
9045f3655d80e4f2983f7549fa4e7150583a4a79
5,055
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.testsuites; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.internal.processors.cache.persistence.IgnitePdsCacheConfigurationFileConsistencyCheckTest; import org.apache.ignite.internal.processors.cache.persistence.IgnitePdsCacheObjectBinaryProcessorOnDiscoveryTest; import org.apache.ignite.internal.processors.cache.persistence.IgnitePdsDestroyCacheTest; import org.apache.ignite.internal.processors.cache.persistence.IgnitePdsDestroyCacheWithoutCheckpointsTest; import org.apache.ignite.internal.processors.cache.persistence.db.IgnitePdsDataRegionMetricsTest; import org.apache.ignite.internal.processors.cache.persistence.db.file.DefaultPageSizeBackwardsCompatibilityTest; import org.apache.ignite.internal.processors.cache.persistence.db.file.IgnitePdsCheckpointSimulationWithRealCpDisabledTest; import org.apache.ignite.internal.processors.cache.persistence.db.file.IgnitePdsPageReplacementTest; import org.apache.ignite.internal.processors.cache.persistence.metastorage.IgniteMetaStorageBasicTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.BPlusTreePageMemoryImplTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.BPlusTreeReuseListPageMemoryImplTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.FillFactorMetricTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.IndexStoragePageMemoryImplTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImplNoLoadTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImplTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryNoStoreLeakTest; import org.apache.ignite.internal.processors.cache.persistence.pagemem.PagesWriteThrottleSmokeTest; import org.apache.ignite.internal.processors.cache.persistence.wal.SegmentedRingByteBufferTest; import org.apache.ignite.internal.processors.cache.persistence.wal.aware.SegmentAwareTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; /** * */ @RunWith(IgnitePdsMvccTestSuite.DynamicSuite.class) public class IgnitePdsMvccTestSuite { /** * @return Suite. */ public static List<Class<?>> suite() { System.setProperty(IgniteSystemProperties.IGNITE_FORCE_MVCC_MODE_IN_TESTS, "true"); Set<Class> ignoredTests = new HashSet<>(); // Skip classes that already contains Mvcc tests. ignoredTests.add(IgnitePdsCheckpointSimulationWithRealCpDisabledTest.class); // Atomic tests. ignoredTests.add(IgnitePdsDataRegionMetricsTest.class); // Non-relevant tests. ignoredTests.add(IgnitePdsCacheConfigurationFileConsistencyCheckTest.class); ignoredTests.add(DefaultPageSizeBackwardsCompatibilityTest.class); ignoredTests.add(IgniteMetaStorageBasicTest.class); ignoredTests.add(IgnitePdsPageReplacementTest.class); ignoredTests.add(PageMemoryImplNoLoadTest.class); ignoredTests.add(PageMemoryNoStoreLeakTest.class); ignoredTests.add(IndexStoragePageMemoryImplTest.class); ignoredTests.add(PageMemoryImplTest.class); ignoredTests.add(BPlusTreePageMemoryImplTest.class); ignoredTests.add(BPlusTreeReuseListPageMemoryImplTest.class); ignoredTests.add(SegmentedRingByteBufferTest.class); ignoredTests.add(PagesWriteThrottleSmokeTest.class); ignoredTests.add(FillFactorMetricTest.class); ignoredTests.add(IgnitePdsCacheObjectBinaryProcessorOnDiscoveryTest.class); ignoredTests.add(SegmentAwareTest.class); ignoredTests.add(IgnitePdsDestroyCacheTest.class); ignoredTests.add(IgnitePdsDestroyCacheWithoutCheckpointsTest.class); return new ArrayList<>(IgnitePdsTestSuite.suite(ignoredTests)); } /** */ public static class DynamicSuite extends Suite { /** */ public DynamicSuite(Class<?> cls) throws InitializationError { super(cls, suite().toArray(new Class<?>[] {null})); } } }
50.55
123
0.79822
cdc8d35c7279a6ea61d44c8e90727cb7ea9d8e6c
8,378
package ECDuelist.Characters; import ECDuelist.Cards.Card; import ECDuelist.ModStartup; import ECDuelist.Utils.Constants; import ECDuelist.Utils.Path; import basemod.abstracts.CustomPlayer; import basemod.animations.SpriterAnimation; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.math.MathUtils; import com.esotericsoftware.spine.AnimationState; import com.evacipated.cardcrawl.modthespire.lib.SpireEnum; import com.google.gson.Gson; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.EnergyManager; import com.megacrit.cardcrawl.helpers.CardLibrary; import com.megacrit.cardcrawl.helpers.FontHelper; import com.megacrit.cardcrawl.helpers.ScreenShake; import com.megacrit.cardcrawl.localization.CharacterStrings; import com.megacrit.cardcrawl.relics.Kunai; import com.megacrit.cardcrawl.screens.CharSelectInfo; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; public class Inigo extends CustomPlayer { public static class Enums { @SpireEnum public static AbstractPlayer.PlayerClass ECDuelistPlayerClass; @SpireEnum(name = "ECDuelist_Color") // These two HAVE to have the same absolutely identical name. public static AbstractCard.CardColor CardColor; @SpireEnum(name = "ECDuelist_Color") public static CardLibrary.LibraryType LibraryColor; } public static final String CharacterName = "Inigo"; private static CharacterStrings localization; private Settings settings; private ModStartup.ColorSettings colorSettings; public Inigo(ModStartup.ColorSettings colorSettings) { this(loadSettings(), colorSettings); } private Inigo(Settings settings, ModStartup.ColorSettings colorSettings) { super("ECDuelist", Enums.ECDuelistPlayerClass, settings.orbs, settings.orbVfx, new SpriterAnimation(settings.animation)); this.settings = settings; this.colorSettings = colorSettings; // Text bubble location dialogX = (drawX + 0.0F * com.megacrit.cardcrawl.core.Settings.scale); dialogY = (drawY + 220.0F * com.megacrit.cardcrawl.core.Settings.scale); } public void postConstructorSetup() { initializeClass(null, settings.campfire1, settings.campfire2, settings.corpse, getLoadout(), settings.hitBoxX, settings.hitBoxY, settings.hitBoxWidth, settings.hitBoxHeight, new EnergyManager(settings.energyPerTurn)); loadAnimation( settings.skeletonAtlas, settings.skeletonJson, settings.skeletonScale); AnimationState.TrackEntry e = state.setAnimation(0, "animation", true); e.setTime(e.getEndTime() * MathUtils.random()); } public static void initializeStatics() { localization = CardCrawlGame.languagePack.getCharacterString(Constants.ModPrefix + CharacterName); } private static Settings loadSettings() { Settings s; try (InputStream in = Inigo.class.getResourceAsStream(Path.SettingsPath + "character/" + CharacterName + ".json")) { Gson reader = new Gson(); s = reader.fromJson(new InputStreamReader(in, StandardCharsets.UTF_8), Settings.class); } catch (IOException e) { throw new RuntimeException(e); } for (int i = 0; i < s.orbs.length; i++) { s.orbs[i] = Path.ImagesPath + s.orbs[i]; } s.orbVfx = Path.ImagesPath + s.orbVfx; s.animation = Path.ImagesPath + s.animation; s.portrait = Path.ImagesPath + s.portrait; s.skeletonAtlas = Path.ImagesPath + s.skeletonAtlas; s.skeletonJson = Path.ImagesPath + s.skeletonJson; s.mainMenuButton = Path.ImagesPath + s.mainMenuButton; s.campfire1 = Path.ImagesPath + s.campfire1; s.campfire2 = Path.ImagesPath + s.campfire2; s.corpse = Path.ImagesPath + s.corpse; return s; } public String getButtonArtPath() { return settings.mainMenuButton; } public String getPortraitPath() { return settings.portrait; } @Override public ArrayList<String> getStartingDeck() { ArrayList<String> cards = new ArrayList<String>(); for (String cardId : settings.startingHand) { cards.add(Constants.ModPrefix + cardId); } return cards; } @Override public ArrayList<String> getStartingRelics() { ArrayList<String> relics = new ArrayList<String>(); relics.add(Kunai.ID); return relics; } @Override public CharSelectInfo getLoadout() { return new CharSelectInfo( localization.NAMES[0], localization.TEXT[0], settings.startingHP, settings.maxHP, 0, settings.startingGold, settings.cardDraw, this, getStartingRelics(), getStartingDeck(), false); } // The class name as it appears next to your player name in-game @Override public String getTitle(PlayerClass playerClass) { return localization.NAMES[1]; } @Override public AbstractCard.CardColor getCardColor() { return Enums.CardColor; } @Override public Color getCardRenderColor() { return colorSettings.cardRenderColor; } //Which card should be obtainable from the Match and Keep event? @Override public AbstractCard getStartCardForEvent() { // TODO How should this be handled? return new Card(settings.startingHand[0]); } @Override public Color getCardTrailColor() { return colorSettings.cardTrailColor; } // Should return how much HP your maximum HP reduces by when starting a run at // Ascension 14 or higher. (ironclad loses 5, defect and silent lose 4 hp respectively) @Override public int getAscensionMaxHPLoss() { return 0; } // Should return a BitmapFont object that you can use to customize how your // energy is displayed from within the energy orb. @Override public BitmapFont getEnergyNumFont() { return FontHelper.energyNumFontRed; } // Effects to do during character select @Override public void doCharSelectScreenSelectEffect() { CardCrawlGame.sound.playA("ATTACK_DAGGER_1", 1.25f); // Sound Effect CardCrawlGame.screenShake.shake(ScreenShake.ShakeIntensity.LOW, ScreenShake.ShakeDur.SHORT, false); // Screen Effect } // character Select on-button-press sound effect @Override public String getCustomModeCharacterButtonSoundKey() { return "ATTACK_DAGGER_1"; } // Should return class name as it appears in run history screen. @Override public String getLocalizedCharacterName() { return localization.NAMES[0]; } @Override public AbstractPlayer newInstance() { Inigo i = new Inigo(colorSettings); i.postConstructorSetup(); return i; } // Should return a string containing what text is shown when your character is // about to attack the heart. For example, the defect is "NL You charge your // core to its maximum..." @Override public String getSpireHeartText() { return localization.TEXT[1]; } @Override public Color getSlashAttackColor() { return colorSettings.slashAttackColor; } @Override public AbstractGameAction.AttackEffect[] getSpireHeartSlashEffect() { // TODO Add at least one effect or the game crashes when approaching the heart. return new AbstractGameAction.AttackEffect[]{ AbstractGameAction.AttackEffect.SLASH_DIAGONAL, AbstractGameAction.AttackEffect.SLASH_HORIZONTAL, AbstractGameAction.AttackEffect.SLASH_VERTICAL, AbstractGameAction.AttackEffect.SLASH_DIAGONAL }; } // The vampire events refer to the base game characters as "brother", "sister", // and "broken one" respectively.This method should return a String containing // the full text that will be displayed as the first screen of the vampires event. @Override public String getVampireText() { return localization.TEXT[2]; } private class Settings { public String[] orbs; public String orbVfx; public String animation; public String portrait; public String skeletonAtlas; public String skeletonJson; public float skeletonScale; public String mainMenuButton; public String campfire1; public String campfire2; public String corpse; public float hitBoxX; public float hitBoxY; public float hitBoxWidth; public float hitBoxHeight; public int energyPerTurn; public int startingHP; public int maxHP; public int startingGold; public int cardDraw; public String[] startingHand; } }
30.028674
118
0.757699
d11c5a32d22e271b85c33ca5495f29814da4cf88
179
package com.hzh.webx.services; import com.hzh.webx.model.Order; /** * Created by huangzehai on 2017/3/31. */ public interface OrderService { void saveOrder(Order order); }
17.9
38
0.72067
29df4806cc2fc6394add04c1dcff8843e4948efb
808
package top.codecrab.gulimall.auth.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import top.codecrab.common.response.R; import top.codecrab.gulimall.auth.vo.LoginVo; import top.codecrab.gulimall.auth.vo.RegisterVo; import top.codecrab.gulimall.auth.vo.SocialUserVo; /** * @author codecrab * @since 2021年06月21日 18:38 */ @FeignClient("gulimall-member") public interface MemberFeignClient { @PostMapping("/member/member/register") R register(@RequestBody RegisterVo vo); @PostMapping("/member/member/login") R login(@RequestBody LoginVo vo); @PostMapping("/member/member/oauth2/login") R oauth2Login(@RequestBody SocialUserVo socialUser); }
29.925926
59
0.779703
a3973b3f4de4828b409080438c95613fdc6642cd
5,161
package com.bookmarkanator.util; import java.util.*; import org.apache.logging.log4j.*; /** * This class associates words with id's, enabling the ability to look up an item by word, or Id. * <p> * For example you could have a set of UUID's that that are associated with strings that represent tags. * You could get a list of all strings associated with a particular Id, or a list of Id's associated with a particular * string. * * @param <T> The object to associate with words. */ public class TextAssociator<T> { private static final Logger logger = LogManager.getLogger(TextAssociator.class.getCanonicalName()); private Set<String> words;//All words present private Map<T, Set<String>> itemToText;//<Id of item, set of text words associated with it> private Map<String, Set<T>> textToItem;//<Word, set of id's that contain this word> public TextAssociator() { words = new HashSet<>(); itemToText = new HashMap<>(); textToItem = new HashMap<>(); } /** * Adds a given word to the supplied item object. If the itemId doesn't exist, it will add it. * * @param itemId The item to associate a word with. * @param word The word to associate with the item. */ public void add(T itemId, String word) { logger.trace("Associating item \"" + itemId.toString() + "\" with word \"" + word + "\""); words.add(word); Set<String> items = itemToText.get(itemId); if (items == null) { items = new HashSet<>(); itemToText.put(itemId, items); } items.add(word); Set<T> ids = textToItem.get(word); if (ids == null) { ids = new HashSet<>(); textToItem.put(word, ids); } ids.add(itemId); } /** * Removes a word from the given itemId. If the itemId no longer has associations it will also be removed. * * @param itemId The thing to remove the word from. * @param word The word to remove. */ public void remove(T itemId, String word) { logger.trace("Un-associating item \"" + itemId.toString() + "\" from \"" + word + "\""); Set<String> items = itemToText.get(itemId); if (items != null) { items.remove(word); } Set<T> ids = textToItem.get(word); if (ids != null) { ids.remove(itemId); } // remove the word from the master list when all other items that have it are gone. if (ids.isEmpty()) { words.remove(word); } } /** * Remove this word from all objects. * * @param word The word to remove from all items. */ public void remove(String word) { logger.trace("Removing \"" + word + "\" from all associations."); words.remove(word); Set<T> items = textToItem.get(word); // remove the word from individual lists for (T i : items) { Set<String> theWords = itemToText.get(i); theWords.remove(word); if (theWords.isEmpty()) { itemToText.remove(i); } } textToItem.remove(word); } /** * Remove this item and all associations it had. * * @param itemId The item to remove, and unassociate. */ public void remove(T itemId) { logger.trace("Removing this item \"" + itemId.toString() + "\" and all associated words it had."); if (itemId == null) { return; } Set<String> itemWords = itemToText.get(itemId); if (itemWords == null) { return; } Set<String> wordsToRemove = new HashSet<>(); // remove this id from the list of words. for (String s : itemWords) { Set<T> items = textToItem.get(s); items.remove(itemId); // remove word if no more items. if (items.isEmpty()) { textToItem.remove(s); wordsToRemove.add(s); } } for (String s : wordsToRemove) { words.remove(s); } itemToText.remove(itemId); } /** * Returns a list of words that are associated with a particular ID. * * @param itemId The ID that has words associated with it. * @return A set of words that are associated with the ID supplied. */ public Set<String> getWords(T itemId) { return itemToText.get(itemId); } /** * Returns a list of ID's that have the supplied word associated with them. * * @param word The word used to get a list of ID's it is in. * @return A set of ID's that contain the supplied word. */ public Set<T> getIDs(String word) { return textToItem.get(word); } public Set<String> getAllWords() { return Collections.unmodifiableSet(words); } public Set<T> getAllIds() { return Collections.unmodifiableSet(itemToText.keySet()); } }
26.603093
118
0.557838
6885a4420beee8b1a5984b8b76439dbff4767037
1,687
package org.jamocha.sample.im; import java.io.Serializable; import org.jamocha.rete.BoundParam; import org.jamocha.rete.Constants; import org.jamocha.rete.DefaultReturnVector; import org.jamocha.rete.Function; import org.jamocha.rete.Parameter; import org.jamocha.rete.Rete; import org.jamocha.rete.ReturnVector; /** * ReturnMessage is a dummy function and isn't implemented. It's here so that * people can run the sample rules in Jamocha. To make it work for real, * the executeFunction method needs to be implemented. * * @author Peter Lin * */ public class ReturnMessage implements Function, Serializable { /** * */ private static final long serialVersionUID = 1L; public static final String RETURN_MESSAGE = "return-msg"; public ReturnMessage() { super(); } /** * the method is not implemented. to get it to work for real, the method * needs to get a JMS client and send the message to a return queue. */ public ReturnVector executeFunction(Rete engine, Parameter[] params) { DefaultReturnVector rv = new DefaultReturnVector(); if (params != null && params.length == 1) { if (params[0] instanceof BoundParam) { BoundParam bp = (BoundParam)params[0]; Message msg = (Message)bp.getObjectRef(); msg.setMessageStatus(Message.RETURNED); System.out.println("Message returned, user does not exist"); } } return rv; } public String getName() { return RETURN_MESSAGE; } public Class<?>[] getParameter() { return new Class[]{Object.class}; } public int getReturnType() { return Constants.RETURN_VOID_TYPE; } public String toPPString(Parameter[] params, int indents) { return "(return-msg <Object>)"; } }
24.808824
77
0.719028
c40a2a48e2d8bfe1eb713006847efa4d22ad8a2b
2,502
package ru.liner.wallpapertheming.views; import android.content.Context; import android.content.res.Resources; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.FrameLayout; import androidx.annotation.LayoutRes; import androidx.annotation.Nullable; import ru.liner.wallpapertheming.themer.IThemer; public abstract class BaseView extends FrameLayout implements IThemer { protected Context context; protected LayoutInflater inflater; @Nullable protected AttributeSet attributeSet; public BaseView(Context context) { super(context); inflater = LayoutInflater.from(context); this.context = context; onStart(); } public BaseView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); inflater = LayoutInflater.from(context); this.context = context; this.attributeSet = attrs; onStart(); } protected void onStart() { inflater.inflate(getLayoutRes(), this); onCreate(); } protected void onCreate() { } @LayoutRes public abstract int getLayoutRes(); public int dpToPx(int dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().density); } public int dpToPx(float dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().density); } public int pxToDp(int px) { return (int) (px / Resources.getSystem().getDisplayMetrics().density); } public int pxToDp(float px) { return (int) (px / Resources.getSystem().getDisplayMetrics().density); } public int pxToSp(float px) { return (int) (px / Resources.getSystem().getDisplayMetrics().scaledDensity); } public int pxToSp(int px) { return (int) (px / Resources.getSystem().getDisplayMetrics().scaledDensity); } public int dpToSp(int dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().scaledDensity); } public int dpToSp(float dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().scaledDensity); } public void setMargins(int left, int top, int right, int bottom) { if (getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) getLayoutParams(); p.setMargins(left, top, right, bottom); requestLayout(); } } }
28.11236
94
0.667866
42eaaeefe1058df0260006be9974bae0369b2e87
94
package com.lovemesomecoding.pizzaria.entity.product.deal; public interface DealService { }
15.666667
58
0.819149
a46956b3f4545a4392613f99133206dccddc54eb
15,865
/* Copyright 2004-2019 Jim Voris * * 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.qumasoft.guitools.qwin.operation; import com.qumasoft.guitools.qwin.QWinFrame; import static com.qumasoft.guitools.qwin.QWinUtility.logProblem; import static com.qumasoft.guitools.qwin.QWinUtility.warnProblem; import com.qumasoft.qvcslib.InfoForMerge; import com.qumasoft.qvcslib.MergeType; import com.qumasoft.qvcslib.MergedInfoInterface; import com.qumasoft.qvcslib.QVCSException; import com.qumasoft.qvcslib.ResolveConflictResults; import com.qumasoft.qvcslib.UserLocationProperties; import com.qumasoft.qvcslib.Utility; import java.io.IOException; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.SwingUtilities; /** * Operation resolve conflict from parent branch for a feature branch. This operation wrappers the work that needs to be done in order to merge changes that have been made on * the parent branch (typically the trunk) into the current feature branch. The operation should only be called when the set of files are all current, marked as <b>overlapped * (a.k.a. conflict).</b> * * @author Jim Voris */ public class OperationResolveConflictFromParentBranchForFeatureBranch extends OperationBaseClass { /** * Create a resolve conflict from parent branch for a feature branch operation. * @param fileTable the file table. * @param serverName the server name. * @param projectName the project name. * @param branchName the branch name. * @param userLocationProperties user location properties. */ public OperationResolveConflictFromParentBranchForFeatureBranch(JTable fileTable, String serverName, String projectName, String branchName, UserLocationProperties userLocationProperties) { super(fileTable, serverName, projectName, branchName, userLocationProperties); } @Override public void executeOperation() { if (getFileTable() != null) { final List<MergedInfoInterface> mergedInfoArray = getSelectedFiles(); // Run the update on the Swing thread. Runnable later = () -> { for (MergedInfoInterface mergedInfo : mergedInfoArray) { if (mergedInfo.getStatusIndex() != MergedInfoInterface.CURRENT_STATUS_INDEX) { warnProblem("Invalid status for resolve conflict."); continue; } if (!mergedInfo.getIsOverlap()) { warnProblem("No conflict found for [" + mergedInfo.getShortWorkfileName() + "]. You cannot resolve a conflict that does not exist."); continue; } if (!mergedInfo.getAttributes().getIsBinaryfile()) { try { resolveConflictFromParentBranch(mergedInfo); } catch (IOException | QVCSException e) { warnProblem(Utility.expandStackTraceToString(e)); } } else { // TODO -- A binary file. We should ask the user if it is okay to just take the latest from the trunk... basically, there is no way for us // to perform the merge. All we can do is have the user take the latest from the trunk and then perform a manual merge based on what is there. // For example, suppose we're dealing with a Word document. We can't merge the trunk changes to our branch, but the user can do that. What we // should do is copy the trunk version of the binary file, check that in as the 'tip' of the branch and re-anchor the file to the trunk's tip // revision, and then (actually before we do the trunk work) rename the branch copy of the file so that is not lost. The net result will be two // files -- or maybe I should have 3 files: the correctly named file would be the copy from the trunk; one other workfile only would be the // trunk's common ancestor file; the 2nd workfile would be the branch's tip file. The user would then need to manually edit the trunk copy // to apply the edits from the branch. They would also have the common ancestor for comparison to help them decide what the valid changes // are.... alternately, we could have the same effect without doing a checkin by simply removing the branch label from the file -- in that absent // the branch label, the feature branch treats the trunk tip as the tip revision of the branch. We would still need the 3 files: // 1 from trunk tip; 1 from trunk common ancestor (workfile only), 1 from branch tip (workfile only). // // What to do for binary files that have: // 1. Been renamed? // 2. Been moved? // 3. Been moved and renamed? // 4. Been deleted? logProblem("There is no support for merging binary files."); } } }; SwingUtilities.invokeLater(later); } } /** * <p> * Merge the changes from the parent branch to the file on this branch. The file on this branch <i>must</i> have a status of current. If all goes well, the result of the merge * will move the branch label for this file to the tip of the parent branch, apply the edits from the parent branch to this branch's workfile, and leave that workfile ready to * be checked in. Note that we do * <i>not</i> check-in the results of the merge -- we leave that to the user, presumably after they verify the results of the merge.</p> * <p> * This routine does have the effect of altering the archive file so that the branch label is removed from archive so that a check-in will re-anchor the branch to a * branch-point off the tip of the parent branch, and as a result of that, the 'overlap' (a.k.a. conflict) should disappear, since there are no longer any edits on the parent * branch that have not been applied to the child branch.</p> * * @param mergedInfo the merged info for the file we are working with. This mergedInfo is the one for the feature branch, i.e. the one that show overlap. It is <i>not</i> * the mergedInfo from the parent branch! * @throws IOException thrown if we have problems reading/writing files. * @throws QVCSException if we cannot figure out the merge type. */ private void resolveConflictFromParentBranch(MergedInfoInterface mergedInfo) throws IOException, QVCSException { // First, need to decide kind of merge we will have to perform. MergeType typeOfMerge = deduceTypeOfMerge(mergedInfo); switch (typeOfMerge) { // 0000 -- no renames or moves. case SIMPLE_MERGE_TYPE: performSimpleMerge(mergedInfo); break; // 0001 -- parent rename case PARENT_RENAMED_MERGE_TYPE: performParentRenamedMerge(mergedInfo); break; // 0010 -- parent move case PARENT_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent moved merge. break; // 0011 -- parent rename && parent move case PARENT_RENAMED_AND_PARENT_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent renamed and parent moved merge. break; // 0100 -- branch rename case CHILD_RENAMED_MERGE_TYPE: // TODO -- resolve conflict for child renamed merge. break; // 0101 -- branch rename && parent rename case PARENT_RENAMED_AND_CHILD_RENAMED_MERGE_TYPE: // TODO -- resolve conflict for parent renamed and child renamed merge. break; // 0110 -- parent move && branch rename case PARENT_MOVED_AND_CHILD_RENAMED_MERGE_TYPE: // TODO -- resolve conflict for parent moved and child renamed merge. break; // 0111 -- parent rename && parent move && branch rename case PARENT_RENAMED_AND_PARENT_MOVED_AND_CHILD_RENAMED_MERGE_TYPE: // TODO -- resolve conflict for parent renamed and child renamed merge. break; // 1000 -- branch move case CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for child moved merge. break; // 1001 -- branch move && parent rename case PARENT_RENAMED_AND_CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent renamed child moved merge. break; // 1010 -- branch move && parent move case PARENT_MOVED_AND_CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent moved child moved merge. break; // 1011 -- branch move && parent move && parent rename case PARENT_MOVED_AND_PARENT_RENAMED_AND_CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent moved and parent renamed and child moved merge. break; // 1100 -- branch move && branch rename case CHILD_RENAMED_AND_CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for child renamed and child moved merge. break; // 1101 -- branch move && branch rename && parent rename case PARENT_RENAMED_AND_CHILD_RENAMED_AND_CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent renamed and child renamed and child moved merge. break; // 1110 -- branch move && branch rename && parent move case PARENT_MOVED_AND_CHILD_RENAMED_AND_CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent moved and child renamed and child moved merge. break; // 1111 -- branch move && branch rename && parent move && parent rename case PARENT_RENAMED_AND_PARENT_MOVED_AND_CHILD_RENAMED_AND_CHILD_MOVED_MERGE_TYPE: // TODO -- resolve conflict for parent renamed and parent moved and child renamed and child moved merge. break; case PARENT_DELETED_MERGE_TYPE: // TODO -- resolve conflict for parent deleted merge. break; case CHILD_DELETED_MERGE_TYPE: // TODO -- resolve conflict for child deleted merge. break; default: break; } } /** * Deduce the type of merge we need to perform. * * @param mergedInfo the merged info for the feature branch's file. * @return the type of merge. */ private MergeType deduceTypeOfMerge(MergedInfoInterface mergedInfo) throws QVCSException { InfoForMerge infoForMerge = mergedInfo.getInfoForMerge(getProjectName(), getBranchName(), mergedInfo.getArchiveDirManager().getAppendedPath()); MergeType typeOfMerge = Utility.deduceTypeOfMerge(infoForMerge, mergedInfo.getShortWorkfileName()); return typeOfMerge; } /** * <p> * The 'happy' path case where the parent branch's file is a text file, and we can just do a merge of the trunk to the branch. To do that, we should:</p> <ol> <li>Request the * server to perform the merge, passing the branch info, and file id, etc.</li> <li>The server tries an auto-merge in a scratch area. If it succeeds, it takes care of updating * the archive by removing the branch label, and sends the merged result file back to the client, where it should produce a status of 'Your copy changed'. The client will have * to expand keywords if needed.</li> <li>If the auto-merge fails, the server can still update the archive by removing the branch label, but it sends 4 files back to the * client: the common ancestor, the branch parent tip, the branch tip, and the merged result with the overlap markers in place. The user will have to manually edit the files in * order to produce the merged file the file should show a status of 'Your copy changed'. (Alternately, it could cause the client to display the merge file gui frame where the * user _must_ produce a merged result).</li> </ol> * * @param mergedInfo the file on which the simple merge is performed. */ private void performSimpleMerge(MergedInfoInterface mergedInfo) { // This is a synchronous call. ResolveConflictResults resolveConflictResults = mergedInfo.resolveConflictFromParentBranch(getProjectName(), getBranchName()); if (resolveConflictResults != null) { boolean overlapDetectedFlag = false; String workfileBase = getUserLocationProperties().getWorkfileLocation(getServerName(), getProjectName(), getBranchName()); if (resolveConflictResults.getMergedResultBuffer() != null) { // Write this to the workfile location for this file, as it is our best guess at a merged result writeMergedResultToWorkfile(mergedInfo, workfileBase, resolveConflictResults.getMergedResultBuffer()); } if (resolveConflictResults.getBranchTipRevisionBuffer() != null) { writeConflictFile(mergedInfo, "branchTip", workfileBase, resolveConflictResults.getBranchTipRevisionBuffer()); overlapDetectedFlag = true; } if (resolveConflictResults.getCommonAncestorBuffer() != null) { writeConflictFile(mergedInfo, "commonAncestor", workfileBase, resolveConflictResults.getCommonAncestorBuffer()); overlapDetectedFlag = true; } if (overlapDetectedFlag) { writeConflictFile(mergedInfo, "branchParentTip", workfileBase, resolveConflictResults.getBranchParentTipRevisionBuffer()); } QWinFrame.getQWinFrame().refreshCurrentBranch(); if (overlapDetectedFlag) { // TODO -- Ideally, we should automatically launch the visual merge tool here. StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append("Overlap detected when merging [").append(mergedInfo.getShortWorkfileName()).append("]. You will need to perform a manual merge."); final String message = stringBuffer.toString(); logProblem(message); Runnable later = () -> { // Let the user know they'll need to perform the merge manually. JOptionPane.showConfirmDialog(QWinFrame.getQWinFrame(), message, "Merge Overlap Detected", JOptionPane.PLAIN_MESSAGE); }; SwingUtilities.invokeLater(later); } } } private void performParentRenamedMerge(MergedInfoInterface mergedInfo) { throw new UnsupportedOperationException("Not yet implemented"); } }
60.323194
180
0.64179
c4467f3c6d3096141f52282c06c379a68a6f16b1
2,413
package com.skycaster.hellobase.bean; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * Created by 廖华凯 on 2017/10/10. */ public class UserBean implements Parcelable { private String userName; private String password; private String host; private String dataBaseName; private ArrayList<String> tokens; public UserBean() { } public UserBean(String userName, String password, String host, String dataBaseName, ArrayList<String> tokens) { this.userName = userName; this.password = password; this.host = host; this.dataBaseName = dataBaseName; this.tokens = tokens; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getDataBaseName() { return dataBaseName; } public void setDataBaseName(String dataBaseName) { this.dataBaseName = dataBaseName; } public ArrayList<String> getTokens() { return tokens; } public void setTokens(ArrayList<String> tokens) { this.tokens = tokens; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.userName); dest.writeString(this.password); dest.writeString(this.host); dest.writeString(this.dataBaseName); dest.writeStringList(this.tokens); } protected UserBean(Parcel in) { this.userName = in.readString(); this.password = in.readString(); this.host = in.readString(); this.dataBaseName = in.readString(); this.tokens = in.createStringArrayList(); } public static final Creator<UserBean> CREATOR = new Creator<UserBean>() { @Override public UserBean createFromParcel(Parcel source) { return new UserBean(source); } @Override public UserBean[] newArray(int size) { return new UserBean[size]; } }; }
23.201923
115
0.625363
64bd74c260e1bba5225bf9d79d805e84adf40beb
8,740
///////////////////////////////////////////////////////////// // QuoteServiceImpl.java // gooru-api // Created by Gooru on 2014 // Copyright (c) 2014 Gooru. All rights reserved. // http://www.goorulearning.org/ // 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.ednovo.gooru.domain.service.quote; import java.net.URL; import java.util.List; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.axis.utils.StringUtils; import org.ednovo.gooru.application.util.ResourceImageUtil; import org.ednovo.gooru.core.api.model.Annotation; import org.ednovo.gooru.core.api.model.Content; import org.ednovo.gooru.core.api.model.License; import org.ednovo.gooru.core.api.model.Quote; import org.ednovo.gooru.core.api.model.Resource; import org.ednovo.gooru.core.api.model.ResourceType; import org.ednovo.gooru.core.api.model.Sharing; import org.ednovo.gooru.core.api.model.ShelfType; import org.ednovo.gooru.core.api.model.User; import org.ednovo.gooru.core.api.model.UserToken; import org.ednovo.gooru.core.application.util.StringUtil; import org.ednovo.gooru.core.constant.ParameterProperties; import org.ednovo.gooru.domain.service.annotation.AnnotationService; import org.ednovo.gooru.domain.service.resource.ResourceService; import org.ednovo.gooru.domain.service.shelf.ShelfService; import org.ednovo.gooru.infrastructure.messenger.IndexProcessor; import org.ednovo.gooru.infrastructure.persistence.hibernate.BaseRepository; import org.ednovo.gooru.infrastructure.persistence.hibernate.UserTokenRepository; import org.ednovo.gooru.infrastructure.persistence.hibernate.annotation.QuoteRepository; import org.ednovo.gooru.infrastructure.persistence.hibernate.resource.ResourceRepository; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Service; import org.springframework.validation.BindException; import org.springframework.validation.Errors; @Service("quoteService") public class QuoteServiceImpl implements QuoteService,ParameterProperties { @Autowired private UserTokenRepository userTokenRepository; @Autowired private ResourceRepository resourceRepository; @Autowired private BaseRepository baseRepository; @Autowired private IndexProcessor indexProcessor; @Autowired private ResourceService resourceService; @Autowired private ShelfService shelfService; @Autowired private QuoteRepository quoteRepository; @Autowired private AnnotationService annotationService; @Autowired private ResourceImageUtil resourceImageUtil; @Override public JSONObject createQuote(String title, String description, String url, String category, String shelfId, String licenseName, String pinToken, String sessionToken, User user) throws Exception { JSONObject resultJson = new JSONObject(); URL urlObj = new URL(url); String urlAuth = urlObj.getAuthority(); String urlArr[] = urlAuth.split("\\."); String urlHost = urlArr[0]; if (urlHost.equals(DEVBS1) || urlHost.equals("pearsonbluesky")) { throw new RuntimeException("You can't add a BlueSky URL as a resource."); } if (StringUtils.isEmpty(description.trim())) { throw new RuntimeException("Description should not be blank."); } description = StringUtil.stripSpecialCharacters(description); UserToken userToken; if (pinToken != null) { userToken = this.userTokenRepository.findByToken(pinToken); } else { userToken = this.userTokenRepository.findByToken(sessionToken); } if (userToken == null) { throw new AccessDeniedException("You are not authorized to perform this action."); } Resource resource = null; /* JSONObject resultJson = new JSONObject(); */ resource = this.resourceRepository.findWebResource(url); if (resource != null) { resultJson.put(STATUS, STATUS_200); resultJson.put(MESSAGE, "It looks like this resource already exists in \nGooru! We've gone ahead and added it to \nyour Shelf."); } else { resource = new Resource(); resource.setGooruOid(UUID.randomUUID().toString()); ResourceType resourceType = null; if (this.getYoutubeVideoId(url) != null) { if (category == null) { category = VIDEO; } resourceType = (ResourceType) baseRepository.get(ResourceType.class, ResourceType.Type.VIDEO.getType()); } else { if (category == null) { category = WEB_SITE; } resourceType = (ResourceType) this.baseRepository.get(ResourceType.class, ResourceType.Type.RESOURCE.getType()); } resource.setResourceType(resourceType); resource.setUrl(url); resource.setTitle(title); resource.setCategory(category); resource.setDescription(description); resource.setSharing(Sharing.PRIVATE.getSharing()); resource.setUser(user); resource.setRecordSource(Resource.RecordSource.QUOTED.getRecordSource()); License license = null; if (licenseName != null) { license = (License) this.baseRepository.get(License.class, licenseName); } resource.setLicense(license); Errors errors = new BindException(Resource.class, RESOURCE); this.resourceService.saveResource(resource, errors, false); // this.getResourceImageUtil().downloadAndSendMsgToGenerateThumbnails(resource, // url); this.getResourceImageUtil().setDefaultThumbnailImageIfFileNotExist(resource); this.resourceService.updateResourceInstanceMetaData(resource, user); Quote quote = new Quote(); quote.setTitle(title); quote.setLicense(license); quote.setAnchor(url); quote.setFreetext(description); quote.setUser(user); quote.setSharing(Sharing.PRIVATE.getSharing()); quote.setResource(resource); annotationService.create(quote, QUOTE, errors); // Auto-subscribe the user to the quoted resource Annotation annotation = new Annotation(); annotation.setUser(user); annotation.setResource(resource); annotationService.create(annotation, SUBSCRIPTION, errors); resultJson.put(STATUS, STATUS_200); resultJson.put(MESSAGE, "This resource has been added to your Shelf"); if (resource != null && resource.getContentId() != null) { indexProcessor.index(resource.getGooruOid(), IndexProcessor.INDEX, RESOURCE); } } try { this.shelfService.addResourceToSelf(shelfId, resource.getGooruOid(), ShelfType.AddedType.SUBSCRIBED.getAddedType(), null, user); } catch (Exception e) { resultJson.put(STATUS, STATUS_4011); resultJson.put(MESSAGE, e.getMessage()); } return resultJson; } private String getYoutubeVideoId(String url) { String pattern = "youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)"; String videoId = null; Pattern compiledPattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); Matcher matcher = compiledPattern.matcher(url); while (matcher.find()) { videoId = matcher.group(1); } return videoId; } @Override public Integer findNotesCount(String tag, User user) { return quoteRepository.findNotesCount(tag, user); } @Override public List<Quote> findNotes(String tag, User user, int start, int stop) { return quoteRepository.findNotes(tag, user, start, stop); } @Override public List<Quote> findNotes(Content context, String mode, User user, int count) { return quoteRepository.findNotes(context, mode, user, count); } @Override public List<Quote> findByUser(String userId) { return quoteRepository.findByUser(userId); } @Override public Quote findByContent(String gooruContentId) { return quoteRepository.findByContent(gooruContentId); } public ResourceImageUtil getResourceImageUtil() { return resourceImageUtil; } }
37.835498
197
0.756293
d84e0af8e86c477c062a7749ca44192fc3cd83e6
2,314
package ksu.cs5000.spring17; import java.util.Scanner; public class Feb27_LoopExamples { public static int readAndSum(Scanner in) { int sum=0; int input; do { System.out.println("Please enter a number (0 to stop)"); input=in.nextInt(); sum+=input; } while(input!=0); return sum; } public static int readAndSumNegatives(Scanner in) { int sum=0; int input; for( ; ; ) { System.out.println("Please enter a number (0 to stop)"); input=in.nextInt(); if(input==0) break; if(input>0) { continue; } sum += input; } return sum; } public static boolean containsDigit(int number, int digit) { do { if (number % 10 == digit) return true; number = number / 10; } while (number!=0); return false; } static boolean stringContains(String s, char c) { for ( int i=0; i<s.length(); ++i ) { if(s.charAt(i)==c) { return true; } } return false; } public static int factorial(int n) { int fac=1; for(int i=1; i<=n; ++i) { fac*=i; } return fac; } static String stringTimes(String s, int n, String separator) { String ans=""; for(int i=1; i<=n; ++i) { ans+=s+separator; } return ans; } static int power(int base, int exponent) { int pow=1; while(exponent>0) { pow*=base; --exponent; } return pow; } static int power2(int base, int exponent) { int pow=1; for(int i=0; i<exponent ; ++i) { pow*=base; } return pow; } static int fibo(int n) { int prev=0; int fib=1; for(int i=0; i<n; ++i) { int tmp=fib; fib=prev+fib; prev=tmp; } return fib; } public static void main(String args[]) { Scanner in=new Scanner(System.in); for(int i=0; i<10; ++i) System.out.println(i + " -> "+fibo(i)); } }
20.846847
68
0.44987
e52b700ecdac9d209c88ab0adea097e5d3ceb837
1,232
import java.util.List; //too many iterations but works public class DirReduction { public static String[] dirReduc(String[] arr) { List<String> stringList = new java.util.ArrayList<>(List.of(arr)); while (isThereAWasteOfDirections(stringList)) { for (int i = 0; i < stringList.size() - 1; i++) { if (isOpposite(stringList.get(i), stringList.get(i + 1))) { stringList.remove(i); stringList.remove(i); } } } return stringList.toArray(new String[0]); } private static boolean isThereAWasteOfDirections(List<String> stringList) { for (int i = 0; i < stringList.size() - 1; i++) { if (isOpposite(stringList.get(i), stringList.get(i + 1))) { return true; } } return false; } private static boolean isOpposite(String direction1, String direction2) { return direction1.equals("NORTH") && direction2.equals("SOUTH") || direction1.equals("SOUTH") && direction2.equals("NORTH") || direction1.equals("EAST") && direction2.equals("WEST") || direction1.equals("WEST") && direction2.equals("EAST"); } }
37.333333
134
0.573864
1e277dfb0a992e3aa92c746848d06f8ff5030147
1,064
package mage.cards.c; import java.util.UUID; import mage.abilities.effects.Effect; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.discard.DiscardControllerEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; /** * * @author fireshoes */ public final class ControlOfTheCourt extends CardImpl { public ControlOfTheCourt(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{1}{R}"); // Draw four cards, then discard three cards at random. this.getSpellAbility().addEffect(new DrawCardSourceControllerEffect(4)); Effect effect = new DiscardControllerEffect(3, true); effect.setText("then discard three cards at random"); this.getSpellAbility().addEffect(effect); } public ControlOfTheCourt(final ControlOfTheCourt card) { super(card); } @Override public ControlOfTheCourt copy() { return new ControlOfTheCourt(this); } }
29.555556
80
0.728383
35119f046bb8e0c31f8694e4a4369e5cba90837a
4,577
/** * 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.falcon.resource; import org.apache.falcon.entity.v0.EntityType; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Map; /** * Test cases for Entity operations using Falcon Native Scheduler. */ public class EntitySchedulerManagerJerseyIT extends AbstractSchedulerManagerJerseyIT { @Test public void testEntitySubmitAndSchedule() throws Exception { UnitTestContext context = new UnitTestContext(); Map<String, String> overlay = context.getUniqueOverlay(); String colo = overlay.get(COLO); String cluster = overlay.get(CLUSTER); submitCluster(colo, cluster, null); context.prepare(); submitProcess(overlay); String processName = overlay.get(PROCESS_NAME); APIResult result = falconUnitClient.getStatus(EntityType.PROCESS, overlay.get(PROCESS_NAME), cluster, null); assertStatus(result); Assert.assertEquals(AbstractEntityManager.EntityStatus.SUBMITTED.name(), result.getMessage()); scheduleProcess(processName, cluster, START_INSTANCE, 1); result = falconUnitClient.getStatus(EntityType.PROCESS, processName, cluster, null); assertStatus(result); Assert.assertEquals(AbstractEntityManager.EntityStatus.RUNNING.name(), result.getMessage()); } @Test public void testEntitySuspendResume() throws Exception { UnitTestContext context = new UnitTestContext(); Map<String, String> overlay = context.getUniqueOverlay(); String colo = overlay.get(COLO); String cluster = overlay.get(CLUSTER); submitCluster(colo, cluster, null); context.prepare(); submitProcess(overlay); String processName = overlay.get(PROCESS_NAME); APIResult result = falconUnitClient.getStatus(EntityType.PROCESS, processName, cluster, null); assertStatus(result); Assert.assertEquals(AbstractEntityManager.EntityStatus.SUBMITTED.name(), result.getMessage()); scheduleProcess(processName, cluster, START_INSTANCE, 1); result = falconUnitClient.suspend(EntityType.PROCESS, processName, cluster, null); assertStatus(result); result = falconUnitClient.getStatus(EntityType.PROCESS, processName, cluster, null); assertStatus(result); Assert.assertEquals(AbstractEntityManager.EntityStatus.SUSPENDED.name(), result.getMessage()); result = falconUnitClient.resume(EntityType.PROCESS, processName, cluster, null); assertStatus(result); result = falconUnitClient.getStatus(EntityType.PROCESS, processName, cluster, null); assertStatus(result); Assert.assertEquals(AbstractEntityManager.EntityStatus.RUNNING.name(), result.getMessage()); } @Test public void testProcessDelete() throws Exception { UnitTestContext context = new UnitTestContext(); Map<String, String> overlay = context.getUniqueOverlay(); String colo = overlay.get(COLO); String cluster = overlay.get(CLUSTER); submitCluster(colo, cluster, null); context.prepare(); submitProcess(overlay); String processName = overlay.get(PROCESS_NAME); APIResult result = falconUnitClient.getStatus(EntityType.PROCESS, processName, cluster, null); assertStatus(result); Assert.assertEquals(AbstractEntityManager.EntityStatus.SUBMITTED.name(), result.getMessage()); scheduleProcess(processName, cluster, START_INSTANCE, 1); result = falconUnitClient.getStatus(EntityType.PROCESS, processName, cluster, null); assertStatus(result); result = falconUnitClient.delete(EntityType.PROCESS, processName, cluster); assertStatus(result); } }
38.788136
116
0.71619
d2551935eeb28140f4d3c63fa8f126ff1ab462a2
3,215
package com.uber.jenkins.phabricator.tasks; import com.uber.jenkins.phabricator.conduit.ConduitAPIException; import com.uber.jenkins.phabricator.conduit.DifferentialClient; import com.uber.jenkins.phabricator.lint.LintResults; import com.uber.jenkins.phabricator.unit.UnitResults; import com.uber.jenkins.phabricator.utils.Logger; import net.sf.json.JSONNull; import net.sf.json.JSONObject; import java.io.IOException; import java.util.Map; public class SendHarbormasterResultTask extends Task { private final DifferentialClient diffClient; private final String phid; private final boolean harbormasterSuccess; private final Map<String, String> coverage; private final LintResults lintResults; private UnitResults unitResults; public SendHarbormasterResultTask( Logger logger, DifferentialClient diffClient, String phid, boolean harbormasterSuccess, UnitResults unitResults, Map<String, String> harbormasterCoverage, LintResults lintResults) { super(logger); this.diffClient = diffClient; this.phid = phid; this.harbormasterSuccess = harbormasterSuccess; this.unitResults = unitResults; this.coverage = harbormasterCoverage; this.lintResults = lintResults; } /** * {@inheritDoc} */ @Override protected String getTag() { return "send-harbormaster-result"; } /** * {@inheritDoc} */ @Override protected void setup() { // Do nothing } /** * {@inheritDoc} */ @Override protected void execute() { try { if (!sendMessage(unitResults, coverage, lintResults)) { info("Error sending Harbormaster unit results, trying again without unit data (you may have an old Phabricator?)."); sendMessage(null, null, null); } } catch (ConduitAPIException e) { printStackTrace(e); failTask(); } catch (IOException e) { printStackTrace(e); failTask(); } } /** * {@inheritDoc} */ @Override protected void tearDown() { // Do nothing } /** * Try to send a message to harbormaster * * @param unitResults the unit testing results to send * @param coverage the coverage data to send * @return false if an error was encountered */ private boolean sendMessage(UnitResults unitResults, Map<String, String> coverage, LintResults lintResults) throws IOException, ConduitAPIException { JSONObject result = diffClient.sendHarbormasterMessage(phid, harbormasterSuccess, unitResults, coverage, lintResults); if (result.containsKey("error_info") && !(result.get("error_info") instanceof JSONNull)) { info(String.format("Error from Harbormaster: %s", result.getString("error_info"))); failTask(); return false; } else { this.result = Result.SUCCESS; } return true; } private void failTask() { info("Unable to post to Harbormaster"); result = result.FAILURE; } }
29.768519
132
0.637947
c0de9777f6a7c08ab6b1de86e79ba58da1014dea
801
package net.sf.cram.encoding.factory; import net.sf.cram.encoding.BitCodec; import net.sf.cram.encoding.Encoding; public class DefaultBitCodecFactory implements BitCodecFactory{ @Override public BitCodec<Long> buildLongCodec(Encoding encoding) { // TODO Auto-generated method stub return null; } @Override public BitCodec<Integer> buildIntegerCodec(Encoding encoding) { // TODO Auto-generated method stub return null; } @Override public BitCodec<Byte> buildByteCodec(Encoding encoding) { // TODO Auto-generated method stub return null; } @Override public BitCodec<byte[]> buildByteArrayCodec(Encoding encoding) { // TODO Auto-generated method stub return null; } @Override public ByteArrayBitCodec buildByteArrayCodec2(Encoding encoding) { return null; } }
20.538462
67
0.762797
630b8da640036be339ae8adc2c7df48c1ff68ae9
370
package dc.longshot.parts; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import dc.longshot.models.Alliance; @XmlRootElement public final class AlliancePart { @XmlElement private Alliance alliance; public AlliancePart() { } public final Alliance getAlliance() { return alliance; } }
16.818182
49
0.727027
08ee13b246cb29f6ab55659812c7a9aaa1a4cd7a
2,022
package com.in28minutes.microservices.currencyconversionservice.resource; import java.math.BigDecimal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.in28minutes.microservices.currencyconversionservice.util.environment.InstanceInformationService; @RestController @RefreshScope public class CurrencyConversionController { private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyConversionController.class); @Autowired private InstanceInformationService instanceInformationService; @Autowired private CurrencyExchangeServiceProxy proxy; @Value("${CONVERSION_PROFIT_PERCENTAGE:5}") private int conversionProfitPercentage; @GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}") public CurrencyConversionBean convertCurrency(@PathVariable String from, @PathVariable String to, @PathVariable BigDecimal quantity) { LOGGER.info("Received Request to convert from {} {} to {}. Profit is {} ", quantity, from, to, conversionProfitPercentage); CurrencyConversionBean response = proxy.retrieveExchangeValue(from, to); BigDecimal conversionMultiple = BigDecimal.valueOf(100) .subtract(BigDecimal.valueOf(conversionProfitPercentage)).divide(BigDecimal.valueOf(100)); BigDecimal convertedValue = quantity.multiply(response.getConversionMultiple()).multiply(conversionMultiple); String conversionEnvironmentInfo = instanceInformationService.retrieveInstanceInfo(); return new CurrencyConversionBean(response.getId(), from, to, response.getConversionMultiple(), quantity, convertedValue, response.getExchangeEnvironmentInfo(), conversionEnvironmentInfo); } }
40.44
125
0.830861
79747d3e22f65db5176f04a107c1bd069a2f7db1
1,564
package com.cruzj6.mha.models; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; /** * Created by Joey on 7/11/16. * */ public class TimesPerDayManagerItem implements Comparable<TimesPerDayManagerItem>{ private Days day; private List<SimpleTimeItem> timesList; public TimesPerDayManagerItem(Days day, long[] times) { this.day = day; Calendar c = Calendar.getInstance(); Date d = new Date(); this.timesList = new ArrayList<>(); if(times != null) { for (long time : times) { d.setTime(time*1000); SimpleDateFormat f = new SimpleDateFormat(); f.applyPattern("HH"); int hours = Integer.parseInt(f.format(d)); f.applyPattern("mm"); int mins = Integer.parseInt(f.format(d)); SimpleTimeItem tItem = new SimpleTimeItem(hours, mins); timesList.add(tItem); } } //Sort the times Collections.sort(timesList); } public Days getDay() { return day; } public List<SimpleTimeItem> getTimesList() { return timesList; } @Override public int compareTo(TimesPerDayManagerItem another) { int aDayNum = another.getDay().getNumVal(); int thisDayNum = this.day.getNumVal(); return Integer.compare(thisDayNum, aDayNum); } }
26.965517
82
0.603581
e6a4e7760e24ed466b8389e2813cc3136c5cbb49
133
package an.samples.bridge; import java.util.List; public interface TypeScriptCompiler { List<String> compile(String filePath); }
14.777778
39
0.781955
ef28b741d284dc8621fbe2f10ebab0ea770aef07
6,874
package ua.gov.dp.econtact.view; import android.graphics.Rect; import android.support.annotation.NonNull; import android.text.Layout; import android.text.StaticLayout; import android.text.TextUtils; import android.text.TextWatcher; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import ua.gov.dp.econtact.App; import ua.gov.dp.econtact.R; import ua.gov.dp.econtact.listeners.SimpleTextWatcher; /** * As TextView (and EditText as a subclass) * can show error if it is in focus only * (many thanks to person who added this if condition to Android source code) - * we have to create own popup window and style it with custom styles * (internal styles are unavailable for developers). * This is helper to show / hide popup errors and drawable icons for TextView. */ public class ErrorPopupHelper { private ErrorPopup mErrorPopup; private TextView mLastTextView; private ImageView mLastImageView; /** * Hide error if user starts to write in this view */ private TextWatcher textWatcher = new SimpleTextWatcher() { @Override public void onTextChanged(@NonNull final CharSequence charSequence, final int i, final int i1, final int i2) { if (mErrorPopup != null && mErrorPopup.isShowing()) { cancel(); } } }; public void setError(final TextView mTextView, final int stringResId, ImageView imageView) { setError(mTextView, mTextView.getContext().getString(stringResId), imageView); } public void setError(final TextView mTextView, final int stringResId) { setError(mTextView, mTextView.getContext().getString(stringResId), null); } public void setError(final TextView mTextView, final CharSequence error, ImageView imageView) { cancel(); CharSequence mError = TextUtils.stringOrSpannedString(error); if (mError != null) { showError(mTextView, error.toString(), imageView); } if (imageView == null) { mTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, mError == null ? 0 : R.drawable.ic_error, 0); } else { imageView.setVisibility(mError == null ? View.INVISIBLE : View.VISIBLE); } mTextView.addTextChangedListener(textWatcher); mLastTextView = mTextView; mLastImageView = imageView; } public void cancel() { if (mLastTextView != null && mLastTextView.getWindowToken() != null) { hideError(); mLastTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); mLastTextView.removeTextChangedListener(textWatcher); mLastTextView = null; if (mLastImageView != null) { mLastImageView.setVisibility(View.INVISIBLE); mLastImageView = null; } } } private void showError(final TextView mTextView, final String error, ImageView imageView) { if (mTextView.getWindowToken() == null) { return; } if (mErrorPopup == null) { LayoutInflater inflater = LayoutInflater.from(mTextView.getContext()); final TextView err = (TextView) inflater.inflate(R.layout.view_error_hint, null); mErrorPopup = new ErrorPopup(err, 0, 0); mErrorPopup.setFocusable(false); // The user is entering text, so the input method is needed. We // don't want the popup to be displayed on top of it. mErrorPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } Rect location = locateView(imageView); TextView tv = (TextView) mErrorPopup.getContentView(); chooseSize(mErrorPopup, error, tv, imageView, mTextView); tv.setText(error); if (imageView == null) { mErrorPopup.showAsDropDown(mTextView, getErrorX(mTextView), -mTextView.getContext().getResources().getDimensionPixelSize(R.dimen.textview_error_popup_margin)); mErrorPopup.fixDirection(mErrorPopup.isAboveAnchor()); } else { if (location != null) { mErrorPopup.showAtLocation(imageView, Gravity.TOP | Gravity.RIGHT, mTextView.getWidth() - imageView.getRight(), location.bottom); } } } private void hideError() { if (mErrorPopup != null) { if (mErrorPopup.isShowing()) { mErrorPopup.dismiss(); } mErrorPopup = null; } } private Rect locateView(View v) { int[] locations = new int[2]; if (v == null) return null; try { v.getLocationOnScreen(locations); } catch (NullPointerException npe) { //Happens when the view doesn't exist on screen anymore. return null; } Rect location = new Rect(); location.left = locations[0]; location.top = locations[1]; location.right = location.left + v.getWidth(); location.bottom = location.top + v.getHeight(); return location; } private int getErrorX(final TextView mTextView) { return mTextView.getWidth() - mErrorPopup.getWidth(); // - mTextView.getPaddingRight(); } private void chooseSize(final PopupWindow pop, final CharSequence text, final TextView tv, ImageView imageView, TextView mTextView) { final int wid = tv.getPaddingLeft() + tv.getPaddingRight(); final int ht = tv.getPaddingTop() + tv.getPaddingBottom(); int defaultWidthInPixels = tv.getResources().getDimensionPixelSize( R.dimen.textview_error_popup_default_width); Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, Layout.Alignment.ALIGN_NORMAL, 1, 0, true); float max = 0; for (int i = 0; i < l.getLineCount(); i++) { max = Math.max(max, l.getLineWidth(i)); } /* * Now set the popup size to be big enough for the text plus the border capped * to DEFAULT_MAX_POPUP_WIDTH */ int height = ht + l.getHeight(); int width = wid + (int) Math.ceil(max); //adjusting width if it is bigger than screen can take if (imageView != null) { int popupWithOffset = width + (mTextView.getWidth() - imageView.getRight()); if (popupWithOffset > App.getScreenWidth()) { pop.setWidth(width - (popupWithOffset - App.getScreenWidth())); pop.setHeight(height + popupWithOffset - App.getScreenWidth()); } }else { pop.setWidth(width); pop.setHeight(height); } } }
36.759358
145
0.62831
6649425e9d54aa30e6e2b3d64965b15b0e18241c
1,832
/* Copyright 2009-2013 SpringSource. * * 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 grails.plugin.springsecurity.acl; import grails.plugin.springsecurity.acl.util.ProxyUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; /** * CGLIB proxies confuse parameter name discovery since the classes aren't compiled with * debug, so find the corresponding method or constructor in the target and use that. * * @author <a href='mailto:[email protected]'>Burt Beckwith</a> */ public class ProxyAwareParameterNameDiscoverer extends LocalVariableTableParameterNameDiscoverer { /** * {@inheritDoc} * @see org.springframework.core.LocalVariableTableParameterNameDiscoverer#getParameterNames( * java.lang.reflect.Method) */ @Override public String[] getParameterNames(final Method method) { return super.getParameterNames(ProxyUtils.unproxy(method)); } /** * {@inheritDoc} * @see org.springframework.core.LocalVariableTableParameterNameDiscoverer#getParameterNames( * java.lang.reflect.Constructor) */ @Override public String[] getParameterNames(@SuppressWarnings("rawtypes") final Constructor constructor) { return super.getParameterNames(ProxyUtils.unproxy(constructor)); } }
35.230769
98
0.775655
bf96e06c1ae10a31825e00b4224fd8669aca329d
914
package com.github.skjolber.packing.test.generator.egy; import java.math.BigDecimal; import org.apache.commons.math3.random.RandomDataGenerator; public enum Category { K1(new BigDecimal("2.72"), new BigDecimal("12.04")), K2(new BigDecimal("12.05"), new BigDecimal("20.23")), K3(new BigDecimal("20.28"), new BigDecimal("32.42")), K4(new BigDecimal("32.44"), new BigDecimal("54.08")), K5(new BigDecimal("54.31"), new BigDecimal("100.21")); private final BigDecimal min; private final BigDecimal max; private Category(BigDecimal min, BigDecimal max) { this.min = min; this.max = max; } public BigDecimal getMax() { return max; } public BigDecimal getMin() { return min; } public double getVolume(RandomDataGenerator r) { // https://stackoverflow.com/questions/3680637/generate-a-random-double-in-a-range/3680648 return r.nextUniform(min.doubleValue(), max.doubleValue()); } }
25.388889
92
0.715536
300cc96501df61aaa796df4ea95255c6d39c10f1
37,531
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation 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: * IBM Corporation - initial API and implementation * Serge Beauchamp (Freescale Semiconductor) - [229633] Project Path Variable Support * Markus Schorn (Wind River) - [306575] Save snapshot location with project * James Blackburn (Broadcom Corp.) - ongoing development *******************************************************************************/ package org.eclipse.core.internal.resources; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import javax.xml.parsers.*; import org.eclipse.core.filesystem.URIUtil; import org.eclipse.core.internal.events.BuildCommand; import org.eclipse.core.internal.localstore.SafeFileInputStream; import org.eclipse.core.internal.utils.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.osgi.util.NLS; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; @SuppressWarnings("unchecked") public class ProjectDescriptionReader extends DefaultHandler implements IModelObjectConstants { //states protected static final int S_BUILD_COMMAND = 0; protected static final int S_BUILD_COMMAND_ARGUMENTS = 1; protected static final int S_BUILD_COMMAND_NAME = 2; protected static final int S_BUILD_COMMAND_TRIGGERS = 3; protected static final int S_BUILD_SPEC = 4; protected static final int S_DICTIONARY = 5; protected static final int S_DICTIONARY_KEY = 6; protected static final int S_DICTIONARY_VALUE = 7; protected static final int S_INITIAL = 8; protected static final int S_LINK = 9; protected static final int S_LINK_LOCATION = 10; protected static final int S_LINK_LOCATION_URI = 11; protected static final int S_LINK_PATH = 12; protected static final int S_LINK_TYPE = 13; protected static final int S_LINKED_RESOURCES = 14; protected static final int S_NATURE_NAME = 15; protected static final int S_NATURES = 16; protected static final int S_PROJECT_COMMENT = 17; protected static final int S_PROJECT_DESC = 18; protected static final int S_PROJECT_NAME = 19; protected static final int S_PROJECTS = 20; protected static final int S_REFERENCED_PROJECT_NAME = 21; protected static final int S_FILTERED_RESOURCES = 23; protected static final int S_FILTER = 24; protected static final int S_FILTER_ID = 25; protected static final int S_FILTER_PATH = 26; protected static final int S_FILTER_TYPE = 27; protected static final int S_MATCHER = 28; protected static final int S_MATCHER_ID = 29; protected static final int S_MATCHER_ARGUMENTS = 30; protected static final int S_VARIABLE_LIST = 31; protected static final int S_VARIABLE = 32; protected static final int S_VARIABLE_NAME = 33; protected static final int S_VARIABLE_VALUE = 34; protected static final int S_SNAPSHOT_LOCATION = 35; /** * Singleton sax parser factory */ private static SAXParserFactory singletonParserFactory; /** * Singleton sax parser */ private static SAXParser singletonParser; protected final StringBuffer charBuffer = new StringBuffer(); protected Stack<Object> objectStack; protected MultiStatus problems; /** * The project we are reading the description for, or null if unknown. */ private final IProject project; // The project description we are creating. ProjectDescription projectDescription = null; protected int state = S_INITIAL; /** * Returns the SAXParser to use when parsing project description files. * @throws ParserConfigurationException * @throws SAXException */ private static synchronized SAXParser createParser() throws ParserConfigurationException, SAXException{ //the parser can't be used concurrently, so only use singleton when workspace is locked if (!isWorkspaceLocked()) return createParserFactory().newSAXParser(); if (singletonParser == null) { singletonParser = createParserFactory().newSAXParser(); } return singletonParser; } /** * Returns the SAXParserFactory to use when parsing project description files. * @throws ParserConfigurationException */ private static synchronized SAXParserFactory createParserFactory() throws ParserConfigurationException{ if (singletonParserFactory == null) { singletonParserFactory = SAXParserFactory.newInstance(); singletonParserFactory.setNamespaceAware(true); try { singletonParserFactory.setFeature("http://xml.org/sax/features/string-interning", true); //$NON-NLS-1$ } catch (SAXException e) { // In case support for this feature is removed } } return singletonParserFactory; } private static boolean isWorkspaceLocked() { try { return ((Workspace) ResourcesPlugin.getWorkspace()).getWorkManager().isLockAlreadyAcquired(); } catch (CoreException e) { return false; } } public ProjectDescriptionReader() { this.project = null; } public ProjectDescriptionReader(IProject project) { this.project = project; } /** * @see ContentHandler#characters(char[], int, int) */ public void characters(char[] chars, int offset, int length) { //accumulate characters and process them when endElement is reached charBuffer.append(chars, offset, length); } /** * End of an element that is part of a build command */ private void endBuildCommandElement(String elementName) { if (elementName.equals(BUILD_COMMAND)) { // Pop this BuildCommand off the stack. BuildCommand command = (BuildCommand) objectStack.pop(); // Add this BuildCommand to a array list of BuildCommands. ArrayList<BuildCommand> commandList = (ArrayList<BuildCommand>) objectStack.peek(); commandList.add(command); state = S_BUILD_SPEC; } } /** * End of an element that is part of a build spec */ private void endBuildSpecElement(String elementName) { if (elementName.equals(BUILD_SPEC)) { // Pop off the array list of BuildCommands and add them to the // ProjectDescription which is the next thing on the stack. ArrayList<ICommand> commands = (ArrayList<ICommand>) objectStack.pop(); state = S_PROJECT_DESC; if (commands.isEmpty()) return; ICommand[] commandArray = commands.toArray(new ICommand[commands.size()]); projectDescription.setBuildSpec(commandArray); } } /** * End a build triggers element and set the triggers for the current * build command element. */ private void endBuildTriggersElement(String elementName) { if (elementName.equals(BUILD_TRIGGERS)) { state = S_BUILD_COMMAND; BuildCommand command = (BuildCommand) objectStack.peek(); //presence of this element indicates the builder is configurable command.setConfigurable(true); //clear all existing values command.setBuilding(IncrementalProjectBuilder.AUTO_BUILD, false); command.setBuilding(IncrementalProjectBuilder.CLEAN_BUILD, false); command.setBuilding(IncrementalProjectBuilder.FULL_BUILD, false); command.setBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD, false); //set new values according to value in the triggers element StringTokenizer tokens = new StringTokenizer(charBuffer.toString(), ","); //$NON-NLS-1$ while (tokens.hasMoreTokens()) { String next = tokens.nextToken(); if (next.toLowerCase().equals(TRIGGER_AUTO)) { command.setBuilding(IncrementalProjectBuilder.AUTO_BUILD, true); } else if (next.toLowerCase().equals(TRIGGER_CLEAN)) { command.setBuilding(IncrementalProjectBuilder.CLEAN_BUILD, true); } else if (next.toLowerCase().equals(TRIGGER_FULL)) { command.setBuilding(IncrementalProjectBuilder.FULL_BUILD, true); } else if (next.toLowerCase().equals(TRIGGER_INCREMENTAL)) { command.setBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD, true); } } } } /** * End of a dictionary element */ private void endDictionary(String elementName) { if (elementName.equals(DICTIONARY)) { // Pick up the value and then key off the stack and add them // to the HashMap which is just below them on the stack. // Leave the HashMap on the stack to pick up more key/value // pairs if they exist. String value = (String) objectStack.pop(); String key = (String) objectStack.pop(); ((HashMap<String, String>) objectStack.peek()).put(key, value); state = S_BUILD_COMMAND_ARGUMENTS; } } private void endDictionaryKey(String elementName) { if (elementName.equals(KEY)) { // There is a value place holder on the top of the stack and // a key place holder just below it. String value = (String) objectStack.pop(); String oldKey = (String) objectStack.pop(); String newKey = charBuffer.toString(); if (oldKey != null && oldKey.length() != 0) { parseProblem(NLS.bind(Messages.projRead_whichKey, oldKey, newKey)); objectStack.push(oldKey); } else { objectStack.push(newKey); } //push back the dictionary value objectStack.push(value); state = S_DICTIONARY; } } private void endDictionaryValue(String elementName) { if (elementName.equals(VALUE)) { String newValue = charBuffer.toString(); // There is a value place holder on the top of the stack String oldValue = (String) objectStack.pop(); if (oldValue != null && oldValue.length() != 0) { parseProblem(NLS.bind(Messages.projRead_whichValue, oldValue, newValue)); objectStack.push(oldValue); } else { objectStack.push(newValue); } state = S_DICTIONARY; } } /** * @see ContentHandler#endElement(String, String, String) */ public void endElement(String uri, String elementName, String qname) { switch (state) { case S_PROJECT_DESC : // Don't think we need to do anything here. break; case S_PROJECT_NAME : if (elementName.equals(NAME)) { // Project names cannot have leading/trailing whitespace // as they are IResource names. projectDescription.setName(charBuffer.toString().trim()); state = S_PROJECT_DESC; } break; case S_PROJECTS : if (elementName.equals(PROJECTS)) { endProjectsElement(elementName); state = S_PROJECT_DESC; } break; case S_DICTIONARY : endDictionary(elementName); break; case S_BUILD_COMMAND_ARGUMENTS : if (elementName.equals(ARGUMENTS)) { // There is a hashmap on the top of the stack with the // arguments (if any). HashMap<String, String> dictionaryArgs = (HashMap<String, String>) objectStack.pop(); state = S_BUILD_COMMAND; if (dictionaryArgs.isEmpty()) break; // Below the hashMap on the stack, there is a BuildCommand. ((BuildCommand) objectStack.peek()).setArguments(dictionaryArgs); } break; case S_BUILD_COMMAND : endBuildCommandElement(elementName); break; case S_BUILD_SPEC : endBuildSpecElement(elementName); break; case S_BUILD_COMMAND_TRIGGERS : endBuildTriggersElement(elementName); break; case S_NATURES : endNaturesElement(elementName); break; case S_LINK : endLinkElement(elementName); break; case S_LINKED_RESOURCES : endLinkedResourcesElement(elementName); break; case S_VARIABLE : endVariableElement(elementName); break; case S_FILTER: endFilterElement(elementName); break; case S_FILTERED_RESOURCES : endFilteredResourcesElement(elementName); break; case S_VARIABLE_LIST : endVariableListElement(elementName); break; case S_PROJECT_COMMENT : if (elementName.equals(COMMENT)) { projectDescription.setComment(charBuffer.toString()); state = S_PROJECT_DESC; } break; case S_REFERENCED_PROJECT_NAME : if (elementName.equals(PROJECT)) { //top of stack is list of project references // Referenced projects are just project names and, therefore, // are also IResource names and cannot have leading/trailing // whitespace. ((ArrayList<String>) objectStack.peek()).add(charBuffer.toString().trim()); state = S_PROJECTS; } break; case S_BUILD_COMMAND_NAME : if (elementName.equals(NAME)) { //top of stack is the build command // A build command name is an extension id and // cannot have leading/trailing whitespace. ((BuildCommand) objectStack.peek()).setName(charBuffer.toString().trim()); state = S_BUILD_COMMAND; } break; case S_DICTIONARY_KEY : endDictionaryKey(elementName); break; case S_DICTIONARY_VALUE : endDictionaryValue(elementName); break; case S_NATURE_NAME : if (elementName.equals(NATURE)) { //top of stack is list of nature names // A nature name is an extension id and cannot // have leading/trailing whitespace. ((ArrayList<String>) objectStack.peek()).add(charBuffer.toString().trim()); state = S_NATURES; } break; case S_LINK_PATH : endLinkPath(elementName); break; case S_LINK_TYPE : endLinkType(elementName); break; case S_LINK_LOCATION : endLinkLocation(elementName); break; case S_LINK_LOCATION_URI : endLinkLocationURI(elementName); break; case S_FILTER_ID : endFilterId(elementName); break; case S_FILTER_PATH : endFilterPath(elementName); break; case S_FILTER_TYPE : endFilterType(elementName); break; case S_MATCHER : endMatcherElement(elementName); break; case S_MATCHER_ID : endMatcherID(elementName); break; case S_MATCHER_ARGUMENTS: endMatcherArguments(elementName); break; case S_VARIABLE_NAME : endVariableName(elementName); break; case S_VARIABLE_VALUE : endVariableValue(elementName); break; case S_SNAPSHOT_LOCATION : endSnapshotLocation(elementName); break; } charBuffer.setLength(0); } /** * End this group of linked resources and add them to the project description. */ private void endLinkedResourcesElement(String elementName) { if (elementName.equals(LINKED_RESOURCES)) { HashMap<IPath, LinkDescription> linkedResources = (HashMap<IPath, LinkDescription>) objectStack.pop(); state = S_PROJECT_DESC; if (linkedResources.isEmpty()) return; projectDescription.setLinkDescriptions(linkedResources); } } /** * End this group of linked resources and add them to the project description. */ private void endFilteredResourcesElement(String elementName) { if (elementName.equals(FILTERED_RESOURCES)) { HashMap<IPath, LinkedList<FilterDescription>> filteredResources = (HashMap<IPath, LinkedList<FilterDescription>>) objectStack.pop(); state = S_PROJECT_DESC; if (filteredResources.isEmpty()) return; projectDescription.setFilterDescriptions(filteredResources); } } /** * End this group of group resources and add them to the project * description. */ private void endVariableListElement(String elementName) { if (elementName.equals(VARIABLE_LIST)) { HashMap<String, VariableDescription> variableList = (HashMap<String, VariableDescription>) objectStack.pop(); state = S_PROJECT_DESC; if (variableList.isEmpty()) return; projectDescription.setVariableDescriptions(variableList); } } /** * End a single linked resource and add it to the HashMap. */ private void endLinkElement(String elementName) { if (elementName.equals(LINK)) { state = S_LINKED_RESOURCES; // Pop off the link description LinkDescription link = (LinkDescription) objectStack.pop(); // Make sure that you have something reasonable IPath path = link.getProjectRelativePath(); int type = link.getType(); URI location = link.getLocationURI(); if (location == null) { parseProblem(NLS.bind(Messages.projRead_badLinkLocation, path, Integer.toString(type))); return; } if ((path == null) || path.segmentCount() == 0) { parseProblem(NLS.bind(Messages.projRead_emptyLinkName, Integer.toString(type), location)); return; } if (type == -1) { parseProblem(NLS.bind(Messages.projRead_badLinkType, path, location)); return; } // The HashMap of linked resources is the next thing on the stack ((HashMap<IPath, LinkDescription>) objectStack.peek()).put(link.getProjectRelativePath(), link); } } private void endMatcherElement(String elementName) { if (elementName.equals(MATCHER)) { // Pop off an array (Object[2]) containing the matcher id and arguments. Object[] matcher = (Object[]) objectStack.pop(); // Make sure that you have something reasonable String id = (String) matcher[0]; // the id can't be null if (id == null) { parseProblem(NLS.bind(Messages.projRead_badFilterID, id)); return; } if (objectStack.peek() instanceof ArrayList) { state = S_MATCHER_ARGUMENTS; // The ArrayList of matchers is the next thing on the stack ArrayList<FileInfoMatcherDescription> list = ((ArrayList<FileInfoMatcherDescription>) objectStack.peek()); list.add(new FileInfoMatcherDescription((String) matcher[0], matcher[1])); } if (objectStack.peek() instanceof FilterDescription) { state = S_FILTER; FilterDescription d = ((FilterDescription) objectStack.peek()); d.setFileInfoMatcherDescription(new FileInfoMatcherDescription((String) matcher[0], matcher[1])); } } } /** * End a single filtered resource and add it to the HashMap. */ private void endFilterElement(String elementName) { if (elementName.equals(FILTER)) { // Pop off the filter description FilterDescription filter = (FilterDescription) objectStack.pop(); if (project != null) { // Make sure that you have something reasonable IPath path = filter.getResource().getProjectRelativePath(); int type = filter.getType(); // arguments can be null if (path == null) { parseProblem(NLS.bind(Messages.projRead_emptyFilterName, Integer.toString(type))); return; } if (type == -1) { parseProblem(NLS.bind(Messages.projRead_badFilterType, path)); return; } // The HashMap of filtered resources is the next thing on the stack HashMap<IPath, LinkedList<FilterDescription>> map = ((HashMap<IPath, LinkedList<FilterDescription>>) objectStack.peek()); LinkedList<FilterDescription>list = map.get(filter.getResource().getProjectRelativePath()); if (list == null) { list = new LinkedList<FilterDescription>(); map.put(filter.getResource().getProjectRelativePath(), list); } list.add(filter); } else { // if the project is null, that means that we're loading a project description to retrieve // some meta data only. String key = new String(); // an empty key; HashMap<String, LinkedList<FilterDescription>> map = ((HashMap<String, LinkedList<FilterDescription>>) objectStack.peek()); LinkedList<FilterDescription>list = map.get(key); if (list == null) { list = new LinkedList<FilterDescription>(); map.put(key, list); } list.add(filter); } state = S_FILTERED_RESOURCES; } } /** * End a single group resource and add it to the HashMap. */ private void endVariableElement(String elementName) { if (elementName.equals(VARIABLE)) { state = S_VARIABLE_LIST; // Pop off the link description VariableDescription desc = (VariableDescription) objectStack.pop(); // Make sure that you have something reasonable if (desc.getName().length() == 0) { parseProblem(NLS.bind(Messages.projRead_emptyVariableName, project.getName())); return; } // The HashMap of variables is the next thing on the stack ((HashMap<String, VariableDescription>) objectStack.peek()).put(desc.getName(), desc); } } /** * For backwards compatibility, link locations in the local file system are represented * in the project description under the "location" tag. * @param elementName */ private void endLinkLocation(String elementName) { if (elementName.equals(LOCATION)) { // A link location is an URI. URIs cannot have leading/trailing whitespace String newLocation = charBuffer.toString().trim(); // objectStack has a LinkDescription on it. Set the type on this LinkDescription. URI oldLocation = ((LinkDescription) objectStack.peek()).getLocationURI(); if (oldLocation != null) { parseProblem(NLS.bind(Messages.projRead_badLocation, oldLocation, newLocation)); } else { ((LinkDescription) objectStack.peek()).setLocationURI(URIUtil.toURI(Path.fromPortableString(newLocation))); } state = S_LINK; } } /** * Link locations that are not stored in the local file system are represented * in the project description under the "locationURI" tag. * @param elementName */ private void endLinkLocationURI(String elementName) { if (elementName.equals(LOCATION_URI)) { // A link location is an URI. URIs cannot have leading/trailing whitespace String newLocation = charBuffer.toString().trim(); // objectStack has a LinkDescription on it. Set the type on this LinkDescription. URI oldLocation = ((LinkDescription) objectStack.peek()).getLocationURI(); if (oldLocation != null) { parseProblem(NLS.bind(Messages.projRead_badLocation, oldLocation, newLocation)); } else { try { ((LinkDescription) objectStack.peek()).setLocationURI(new URI(newLocation)); } catch (URISyntaxException e) { String msg = Messages.projRead_failureReadingProjectDesc; problems.add(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, msg, e)); } } state = S_LINK; } } private void endLinkPath(String elementName) { if (elementName.equals(NAME)) { IPath newPath = new Path(charBuffer.toString()); // objectStack has a LinkDescription on it. Set the name // on this LinkDescription. IPath oldPath = ((LinkDescription) objectStack.peek()).getProjectRelativePath(); if (oldPath.segmentCount() != 0) { parseProblem(NLS.bind(Messages.projRead_badLinkName, oldPath, newPath)); } else { ((LinkDescription) objectStack.peek()).setPath(newPath); } state = S_LINK; } } private void endMatcherID(String elementName) { if (elementName.equals(ID)) { // The matcher id is String. String newID = charBuffer.toString().trim(); // objectStack has an array (Object[2]) on it for the matcher id and arguments. String oldID = (String)((Object[])objectStack.peek())[0]; if (oldID != null) { parseProblem(NLS.bind(Messages.projRead_badID, oldID, newID)); } else { ((Object[]) objectStack.peek())[0] = newID; } state = S_MATCHER; } } private void endMatcherArguments(String elementName) { if (elementName.equals(ARGUMENTS)) { ArrayList<FileInfoMatcherDescription> matchers = (ArrayList<FileInfoMatcherDescription>) objectStack.pop(); Object newArguments = charBuffer.toString(); if (matchers.size() > 0) newArguments = matchers.toArray(new FileInfoMatcherDescription[matchers.size()]); // objectStack has an array (Object[2]) on it for the matcher id and arguments. String oldArguments = (String)((Object[])objectStack.peek())[1]; if (oldArguments != null) { parseProblem(NLS.bind(Messages.projRead_badArguments, oldArguments, newArguments)); } else ((Object[]) objectStack.peek())[1] = newArguments; state = S_MATCHER; } } private void endFilterId(String elementName) { if (elementName.equals(ID)) { Long newId = new Long(charBuffer.toString()); // objectStack has a FilterDescription on it. Set the name // on this FilterDescription. long oldId = ((FilterDescription) objectStack.peek()).getId(); if (oldId != 0) { parseProblem(NLS.bind(Messages.projRead_badFilterName, new Long(oldId), newId)); } else { ((FilterDescription) objectStack.peek()).setId(newId.longValue()); } state = S_FILTER; } } private void endFilterPath(String elementName) { if (elementName.equals(NAME)) { IPath newPath = new Path(charBuffer.toString()); // objectStack has a FilterDescription on it. Set the name // on this FilterDescription. IResource oldResource = ((FilterDescription) objectStack.peek()).getResource(); if (oldResource != null) { parseProblem(NLS.bind(Messages.projRead_badFilterName, oldResource.getProjectRelativePath(), newPath)); } else { if (project != null) { ((FilterDescription) objectStack.peek()).setResource(newPath.isEmpty() ? (IResource) project : project.getFolder(newPath)); } else { // if the project is null, that means that we're loading a project description to retrieve // some meta data only. ((FilterDescription) objectStack.peek()).setResource(null); } } state = S_FILTER; } } private void endFilterType(String elementName) { if (elementName.equals(TYPE)) { int newType = -1; try { // parseInt expects a string containing only numerics // or a leading '-'. Ensure there is no leading/trailing // whitespace. newType = Integer.parseInt(charBuffer.toString().trim()); } catch (NumberFormatException e) { log(e); } // objectStack has a FilterDescription on it. Set the type // on this FilterDescription. int oldType = ((FilterDescription) objectStack.peek()).getType(); if (oldType != -1) { parseProblem(NLS.bind(Messages.projRead_badFilterType2, Integer.toString(oldType), Integer.toString(newType))); } else { ((FilterDescription) objectStack.peek()).setType(newType); } state = S_FILTER; } } private void endVariableName(String elementName) { if (elementName.equals(NAME)) { String value = charBuffer.toString(); // objectStack has a VariableDescription on it. Set the value // on this ValueDescription. ((VariableDescription) objectStack.peek()).setName(value); state = S_VARIABLE; } } private void endVariableValue(String elementName) { if (elementName.equals(VALUE)) { String value = charBuffer.toString(); // objectStack has a VariableDescription on it. Set the value // on this ValueDescription. ((VariableDescription) objectStack.peek()).setValue(value); state = S_VARIABLE; } } private void endLinkType(String elementName) { if (elementName.equals(TYPE)) { //FIXME we should handle this case by removing the entire link //for now we default to a file link int newType = IResource.FILE; try { // parseInt expects a string containing only numerics // or a leading '-'. Ensure there is no leading/trailing // whitespace. newType = Integer.parseInt(charBuffer.toString().trim()); } catch (NumberFormatException e) { log(e); } // objectStack has a LinkDescription on it. Set the type // on this LinkDescription. int oldType = ((LinkDescription) objectStack.peek()).getType(); if (oldType != -1) { parseProblem(NLS.bind(Messages.projRead_badLinkType2, Integer.toString(oldType), Integer.toString(newType))); } else { ((LinkDescription) objectStack.peek()).setType(newType); } state = S_LINK; } } /** * End of an element that is part of a nature list */ private void endNaturesElement(String elementName) { if (elementName.equals(NATURES)) { // Pop the array list of natures off the stack ArrayList<String> natures = (ArrayList<String>) objectStack.pop(); state = S_PROJECT_DESC; if (natures.size() == 0) return; String[] natureNames = natures.toArray(new String[natures.size()]); projectDescription.setNatureIds(natureNames); } } /** * End of an element that is part of a project references list */ private void endProjectsElement(String elementName) { // Pop the array list that contains all the referenced project names ArrayList<String> referencedProjects = (ArrayList<String>) objectStack.pop(); if (referencedProjects.size() == 0) // Don't bother adding an empty group of referenced projects to the // project descriptor. return; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject[] projects = new IProject[referencedProjects.size()]; for (int i = 0; i < projects.length; i++) { projects[i] = root.getProject(referencedProjects.get(i)); } projectDescription.setReferencedProjects(projects); } private void endSnapshotLocation(String elementName) { if (elementName.equals(SNAPSHOT_LOCATION)) { String location = charBuffer.toString().trim(); try { projectDescription.setSnapshotLocationURI(new URI(location)); } catch (URISyntaxException e) { String msg = NLS.bind(Messages.projRead_badSnapshotLocation, location); problems.add(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, msg, e)); } state = S_PROJECT_DESC; } } /** * @see ErrorHandler#error(SAXParseException) */ public void error(SAXParseException error) { log(error); } /** * @see ErrorHandler#fatalError(SAXParseException) */ public void fatalError(SAXParseException error) throws SAXException { // ensure a null value is not passed as message to Status constructor (bug 42782) String message = error.getMessage(); if (project != null) message = NLS.bind(Messages.resources_readMeta, project.getName()); problems.add(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, message == null ? "" : message, error)); //$NON-NLS-1$ throw error; } protected void log(Exception ex) { String message = ex.getMessage(); if (project != null) message = NLS.bind(Messages.resources_readMeta, project.getName()); problems.add(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, message == null ? "" : message, ex)); //$NON-NLS-1$ } private void parseProblem(String errorMessage) { problems.add(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, errorMessage, null)); } private void parseProjectDescription(String elementName) { if (elementName.equals(NAME)) { state = S_PROJECT_NAME; return; } if (elementName.equals(COMMENT)) { state = S_PROJECT_COMMENT; return; } if (elementName.equals(PROJECTS)) { state = S_PROJECTS; // Push an array list on the object stack to hold the name // of all the referenced projects. This array list will be // popped off the stack, massaged into the right format // and added to the project description when we hit the // end element for PROJECTS. objectStack.push(new ArrayList<String>()); return; } if (elementName.equals(BUILD_SPEC)) { state = S_BUILD_SPEC; // Push an array list on the object stack to hold the build commands // for this build spec. This array list will be popped off the stack, // massaged into the right format and added to the project's build // spec when we hit the end element for BUILD_SPEC. objectStack.push(new ArrayList<ICommand>()); return; } if (elementName.equals(NATURES)) { state = S_NATURES; // Push an array list to hold all the nature names. objectStack.push(new ArrayList<String>()); return; } if (elementName.equals(LINKED_RESOURCES)) { // Push a HashMap to collect all the links. objectStack.push(new HashMap<IPath, LinkDescription>()); state = S_LINKED_RESOURCES; return; } if (elementName.equals(FILTERED_RESOURCES)) { // Push a HashMap to collect all the filters. objectStack.push(new HashMap<IPath, LinkedList<FilterDescription>>()); state = S_FILTERED_RESOURCES; return; } if (elementName.equals(VARIABLE_LIST)) { // Push a HashMap to collect all the variables. objectStack.push(new HashMap<String, VariableDescription>()); state = S_VARIABLE_LIST; return; } if (elementName.equals(SNAPSHOT_LOCATION)) { state = S_SNAPSHOT_LOCATION; return; } } public ProjectDescription read(InputSource input) { problems = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, Messages.projRead_failureReadingProjectDesc, null); objectStack = new Stack<Object>(); state = S_INITIAL; try { createParser().parse(input, this); } catch (ParserConfigurationException e) { log(e); } catch (IOException e) { log(e); } catch (SAXException e) { log(e); } switch (problems.getSeverity()) { case IStatus.ERROR : Policy.log(problems); return null; case IStatus.WARNING : case IStatus.INFO : Policy.log(problems); case IStatus.OK : default : return projectDescription; } } /** * Reads and returns a project description stored at the given location */ public ProjectDescription read(IPath location) throws IOException { BufferedInputStream file = null; try { file = new BufferedInputStream(new FileInputStream(location.toFile())); return read(new InputSource(file)); } finally { FileUtil.safeClose(file); } } /** * Reads and returns a project description stored at the given location, or * temporary location. */ public ProjectDescription read(IPath location, IPath tempLocation) throws IOException { SafeFileInputStream file = new SafeFileInputStream(location.toOSString(), tempLocation.toOSString()); try { return read(new InputSource(file)); } finally { file.close(); } } /** * @see ContentHandler#startElement(String, String, String, Attributes) */ public void startElement(String uri, String elementName, String qname, Attributes attributes) throws SAXException { //clear the character buffer at the start of every element charBuffer.setLength(0); switch (state) { case S_INITIAL : if (elementName.equals(PROJECT_DESCRIPTION)) { state = S_PROJECT_DESC; projectDescription = new ProjectDescription(); } else { throw (new SAXException(NLS.bind(Messages.projRead_notProjectDescription, elementName))); } break; case S_PROJECT_DESC : parseProjectDescription(elementName); break; case S_PROJECTS : if (elementName.equals(PROJECT)) { state = S_REFERENCED_PROJECT_NAME; } break; case S_BUILD_SPEC : if (elementName.equals(BUILD_COMMAND)) { state = S_BUILD_COMMAND; objectStack.push(new BuildCommand()); } break; case S_BUILD_COMMAND : if (elementName.equals(NAME)) { state = S_BUILD_COMMAND_NAME; } else if (elementName.equals(BUILD_TRIGGERS)) { state = S_BUILD_COMMAND_TRIGGERS; } else if (elementName.equals(ARGUMENTS)) { state = S_BUILD_COMMAND_ARGUMENTS; // Push a HashMap to hold all the key/value pairs which // will become the argument list. objectStack.push(new HashMap<String, String>()); } break; case S_BUILD_COMMAND_ARGUMENTS : if (elementName.equals(DICTIONARY)) { state = S_DICTIONARY; // Push 2 strings for the key/value pair to be read objectStack.push(new String()); // key objectStack.push(new String()); // value } break; case S_DICTIONARY : if (elementName.equals(KEY)) { state = S_DICTIONARY_KEY; } else if (elementName.equals(VALUE)) { state = S_DICTIONARY_VALUE; } break; case S_NATURES : if (elementName.equals(NATURE)) { state = S_NATURE_NAME; } break; case S_LINKED_RESOURCES : if (elementName.equals(LINK)) { state = S_LINK; // Push place holders for the name, type and location of // this link. objectStack.push(new LinkDescription()); } break; case S_VARIABLE_LIST: if (elementName.equals(VARIABLE)) { state = S_VARIABLE; // Push place holders for the name, type and location of // this link. objectStack.push(new VariableDescription()); } break; case S_LINK : if (elementName.equals(NAME)) { state = S_LINK_PATH; } else if (elementName.equals(TYPE)) { state = S_LINK_TYPE; } else if (elementName.equals(LOCATION)) { state = S_LINK_LOCATION; } else if (elementName.equals(LOCATION_URI)) { state = S_LINK_LOCATION_URI; } break; case S_FILTERED_RESOURCES : if (elementName.equals(FILTER)) { state = S_FILTER; // Push place holders for the name, type, id and arguments of // this filter. objectStack.push(new FilterDescription()); } break; case S_FILTER: if (elementName.equals(ID)) { state = S_FILTER_ID; }else if (elementName.equals(NAME)) { state = S_FILTER_PATH; } else if (elementName.equals(TYPE)) { state = S_FILTER_TYPE; } else if (elementName.equals(MATCHER)) { state = S_MATCHER; // Push an array for the matcher id and arguments objectStack.push(new Object[2]); } break; case S_MATCHER: if (elementName.equals(ID)) { state = S_MATCHER_ID; } else if (elementName.equals(ARGUMENTS)) { state = S_MATCHER_ARGUMENTS; objectStack.push(new ArrayList<FileInfoMatcherDescription>()); } break; case S_MATCHER_ARGUMENTS: if (elementName.equals(MATCHER)) { state = S_MATCHER; // Push an array for the matcher id and arguments objectStack.push(new Object[2]); } break; case S_VARIABLE: if (elementName.equals(NAME)) { state = S_VARIABLE_NAME; } else if (elementName.equals(VALUE)) { state = S_VARIABLE_VALUE; } break; } } /** * @see ErrorHandler#warning(SAXParseException) */ public void warning(SAXParseException error) { log(error); } }
33.872744
163
0.707282
fae9605caa07baab78883c63b06025c9dbdae5a9
1,503
package com.tecky.awsimageupload.profile; import java.util.Objects; import java.util.Optional; import java.util.UUID; public class UserProfile { private UUID userProfileId; private String username; private String userProfileImageLink; //S3 Key public UserProfile(UUID userProfileId, String username, String userProfileImageLink) { super(); this.userProfileId = userProfileId; this.username = username; this.userProfileImageLink = userProfileImageLink; } public UUID getUserProfileId() { return userProfileId; } public void setUserProfileId(UUID userProfileId) { this.userProfileId = userProfileId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Optional<String> getUserProfileImageLink() { return Optional.ofNullable(userProfileImageLink); } public void setUserProfileImageLink(String userProfileImageLink) { this.userProfileImageLink = userProfileImageLink; } @Override public int hashCode() { return Objects.hash(userProfileId, userProfileImageLink, username); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserProfile other = (UserProfile) obj; return Objects.equals(userProfileId, other.userProfileId) && Objects.equals(userProfileImageLink, other.userProfileImageLink) && Objects.equals(username, other.username); } }
25.05
87
0.756487
c3872e73e5ecaa5704123368d4bcc112abfe4940
58
package com.project.android; public class ExampleMock { }
14.5
28
0.793103
20a24a52f67b81d3e2c1ccff6f6217d3ef79cee8
2,250
package com.goaleaf.entities; import javax.persistence.*; @Entity @Table(name = "members") public class Member { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private Integer userID; private Integer habitID; private String userLogin; @Lob private String imageCode; private Integer points; private Boolean banned; public Member(Integer userID /*, Set<LeafDate> doneDates*/) { this.userID = userID; // this.doneDates = doneDates; } public Member() { this.banned = false; } public Member(Integer userID, Integer habitID) { this.userID = userID; this.habitID = habitID; this.banned = false; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserID() { return userID; } public void setUserID(Integer userID) { this.userID = userID; } public Integer getHabitID() { return habitID; } public void setHabitID(Integer habitID) { this.habitID = habitID; } // public Set<LeafDate> getDoneDates() { // return doneDates; // } // // public void setDoneDates(Set<LeafDate> doneDates) { // this.doneDates = doneDates; // } // // public void addDate(Date date) { // this.doneDates.add(new LeafDate(id, new Date())); // } public String getUserLogin() { return userLogin; } public void setUserLogin(String userLogin) { this.userLogin = userLogin; } public String getImageCode() { return imageCode; } public void setImageCode(String imageCode) { this.imageCode = imageCode; } public Integer getPoints() { return points; } public void setPoints(Integer points) { this.points = points; } public void addPoints(Integer increaseNr) { this.points += increaseNr; } public void decreasePoints(Integer decreaseNr) { this.points -= decreaseNr; } public Boolean getBanned() { return banned; } public void setBanned(Boolean banned) { this.banned = banned; } }
19.067797
65
0.597333
7620d4edc841ddc53bac35a43e3b2fec30474244
1,444
package de.idos.updates.install; import de.idos.updates.Version; import de.idos.updates.store.Installation; import de.idos.updates.store.ProgressReport; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class FileInstallerTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); Version version = mock(Version.class); ProgressReport report = mock(ProgressReport.class); Installation installation = mock(Installation.class); private FileInstaller fileInstaller; @Before public void setUp() throws Exception { File sourceFolder = folder.newFolder(); fileInstaller = new FileInstaller(report, sourceFolder, installation); } @Test public void reportsInstallation() throws Exception { File element = folder.newFile(); fileInstaller.installElement(element, version); verify(report).installingFile(element.getName()); } @Test public void abortsInstallationIfAnErrorOccurs() throws Exception { fileInstaller.handleException(); verify(installation).abort(); } @Test public void forwardsFinalizationCallToInstallationInstance() throws Exception { fileInstaller.finalizeInstallation(); verify(installation).finish(); } }
29.469388
83
0.729224
d9534a002e90f904a47a3d135fd04eb9a4f56852
1,273
package ch.uzh.ifi.hase.soprafs22.game.units; import ch.uzh.ifi.hase.soprafs22.game.units.interfaces.IUnitBuilder; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; public class UnitDirector { private final IUnitBuilder unitBuilder; public UnitDirector(IUnitBuilder unitBuilder) { this.unitBuilder = unitBuilder; } public void make(@NotNull Map<String, Object> unitStream, int column, int row) { this.unitBuilder.setType((String) unitStream.get("type")); this.unitBuilder.setHealth((int) unitStream.get("health")); this.unitBuilder.setMaxHealth((int) unitStream.get("maxHealth")); this.unitBuilder.setDefense((List<Double>)unitStream.get("defense")); this.unitBuilder.setAttackDamage((List<Double>)unitStream.get("attackDamage")); this.unitBuilder.setAttackRange((int) unitStream.get("attackRange")); this.unitBuilder.setMovementRange((int) unitStream.get("movementRange")); this.unitBuilder.setCommandList((List<String>)unitStream.get("commands")); this.unitBuilder.setTeamId((int)unitStream.get("teamId")); this.unitBuilder.setUserId((int)unitStream.get("userId")); this.unitBuilder.setPosition(column, row); } }
42.433333
87
0.721131
7f6c3686bffb50d87c21605f7a21cf008586b932
747
package com.uc4.ara.feature.discovery; import com.automic.actions.discovery.DiscoveryManager; import com.uc4.ara.feature.discovery.goals.HomeDirectory; import com.uc4.ara.feature.discovery.goals.HostAndPortGoal; import com.uc4.ara.feature.discovery.goals.ManagerConnection; public class Jboss7DiscoveryManager { private DiscoveryManager manager; public Jboss7DiscoveryManager() { manager = new DiscoveryManager(new Jboss7Result()); manager.addGoal(new HomeDirectory()); manager.addGoal(new HostAndPortGoal()); manager.addGoal(new ManagerConnection()); } public void run() throws Exception { manager.printGoals(); manager.run(); manager.printGoals(); manager.printReport(); manager.getResult().printResult(); } }
24.9
61
0.773762
8a3062c8b66ac14e5613ca1303cb5800ebfa9243
856
package org.interledger.connector.routing; import org.interledger.core.InterledgerAddressPrefix; import org.zalando.problem.Status; import java.net.URI; import java.util.Objects; /** * Thrown when a data inconsistency prevents processing (for example, when the prefix in the url doesn't match the * prefix of the static route passed in the body) */ public class StaticRouteUnprocessableProblem extends StaticRouteProblem { public StaticRouteUnprocessableProblem(String urlPrefix, InterledgerAddressPrefix entityPrefix) { super( URI.create(TYPE_PREFIX + STATIC_ROUTES_PATH + "/static-route-unprocessable"), "Static Route Unprocessable [entityPrefix: `" + entityPrefix.getValue() + "`, urlPrefix: `" + urlPrefix + "`]", Status.UNPROCESSABLE_ENTITY, Objects.requireNonNull(entityPrefix) ); } }
31.703704
114
0.740654
abe18b20edbc69d8a24af478ae54924217045d69
722
package com.lara; import java.util.Arrays; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; public class Manager4 { public static void main(String args[]) { Session s1=Util.openSession(); Criteria ctr=s1.createCriteria(Person.class); List<Person> list=ctr.list(); ctr.add(Restrictions.eq("firstName", "lara")); ctr.add(Restrictions.gt("age", 15)); ctr.add(Restrictions.like("lastName", "%s%")); for(Person p1:list) { System.out.println(p1.getId()+"-"+p1.getFirstName()+"-"+p1.getLastName()+"-"+p1.getAge()); } System.out.println("done"); } }
26.740741
93
0.713296
12c679fb48a64f5a83809c1e34d7f3f8a3091c2f
2,454
package com.codetaylor.mc.artisanworktables.modules.tools.material; import com.codetaylor.mc.artisanworktables.api.tool.ICustomToolMaterial; public class CustomMaterialValidator { public void validate(ICustomToolMaterial data) throws CustomMaterialValidationException { if (data.getName() == null || data.getName().isEmpty()) { throw new CustomMaterialValidationException("Missing or empty material name"); } if (data.getHarvestLevel() < 0) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [harvestLevel] harvest level can't be < 0"); } if (data.getMaxUses() < 1) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [maxUses] max uses can't be < 1"); } if (data.getEfficiency() < 0) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [efficiency] efficiency can't be < 0"); } if (data.getDamage() < 0) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [damage] damage can't be < 0"); } if (data.getEnchantability() < 0) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [enchantability] enchantability can't be < 0"); } if (data.getColor() == null || data.getColor().isEmpty() || data.getColor().length() != 6) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [color] invalid color, must be 6 characters"); } try { Integer.decode("0x" + data.getColor()); } catch (Exception e) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [shiny] invalid color string: " + data .getColor()); } if (data.getIngredientString() == null || data.getIngredientString().isEmpty()) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [ingredient] missing or empty ingredient"); } if (data.getLangKey() == null || data.getLangKey().isEmpty()) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [langKey] missing or empty lang key"); } if (data.getOreDictKey() == null || data.getOreDictKey().isEmpty()) { throw new CustomMaterialValidationException("Material: [" + data.getName() + "], key: [oreDictKey] missing or empty ore dict key"); } } }
41.59322
139
0.657702
8ed008831077b36bd873c76589d29c2ccfb61ca3
2,864
package com.terraforged.cereal.value; import com.terraforged.cereal.serial.DataWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class DataList extends DataValue implements Iterable<DataValue> { public static final DataList NULL_LIST = new DataList(Collections.emptyList(), false); private final boolean nullable; private final List<DataValue> data; protected DataList(List<DataValue> data, boolean nullable) { super(data); this.data = data; this.nullable = nullable; } public DataList() { this(false); } public DataList(int size) { this(size, false); } public DataList(boolean nullable) { this(16, nullable); } public DataList(int size, boolean nullable) { this(new ArrayList<>(size), nullable); } public int size() { return data.size(); } public boolean contains(Object value) { for (DataValue v : this) { if (value.equals(v.value)) { return true; } } return false; } public DataValue get(int index) { if (index < data.size()) { DataValue value = data.get(index); if (value != null) { return value; } } return DataValue.NULL; } public DataObject getObj(int index) { return get(index).asObj(); } public DataList getList(int index) { return get(index).asList(); } public DataList add(Object value) { return add(DataValue.of(value)); } public DataList add(DataValue value) { if (value.isNonNull() || nullable) { data.add(value); } return this; } public DataValue set(int index, Object value) { return set(index, DataValue.of(value)); } public DataValue set(int index, DataValue value) { if (value.isNonNull() || nullable) { DataValue removed = data.set(index, value); if (removed != null) { return removed; } } return DataValue.NULL; } public DataValue remove(int index) { if (index < size()) { DataValue value = data.remove(index); if (value != null) { return value; } } return DataValue.NULL; } public List<DataValue> getBacking() { return data; } @Override public void appendTo(DataWriter writer) throws IOException { writer.beginList(); for (DataValue value : data) { writer.value(value); } writer.endList(); } @Override public Iterator<DataValue> iterator() { return data.iterator(); } }
23.096774
90
0.564944
273a93922d046dc8ee791df807b8bea9104fdf7a
3,111
/** * alert-common * * Copyright (c) 2020 Synopsys, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.synopsys.integration.alert.common.channel; import java.util.List; import com.google.gson.Gson; import com.synopsys.integration.alert.common.descriptor.DescriptorKey; import com.synopsys.integration.alert.common.descriptor.accessor.AuditUtility; import com.synopsys.integration.alert.common.event.DistributionEvent; import com.synopsys.integration.alert.common.message.model.MessageResult; import com.synopsys.integration.exception.IntegrationException; import com.synopsys.integration.issuetracker.common.config.IssueTrackerContext; import com.synopsys.integration.issuetracker.common.message.IssueTrackerRequest; import com.synopsys.integration.issuetracker.common.message.IssueTrackerResponse; import com.synopsys.integration.issuetracker.common.service.IssueTrackerService; public abstract class IssueTrackerChannel extends DistributionChannel { private final DescriptorKey descriptorKey; public IssueTrackerChannel(Gson gson, AuditUtility auditUtility, DescriptorKey descriptorKey) { super(gson, auditUtility); this.descriptorKey = descriptorKey; } protected abstract IssueTrackerService<?> getIssueTrackerService(); protected abstract IssueTrackerContext<?> getIssueTrackerContext(DistributionEvent event); protected abstract List<IssueTrackerRequest> createRequests(IssueTrackerContext<?> context, DistributionEvent event) throws IntegrationException; @Override public MessageResult sendMessage(DistributionEvent event) throws IntegrationException { IssueTrackerContext context = getIssueTrackerContext(event); IssueTrackerService service = getIssueTrackerService(); List<IssueTrackerRequest> requests = createRequests(context, event); String statusMessage; if (requests.isEmpty()) { statusMessage = String.format("No requests to send to issue tracker: %s", descriptorKey.getDisplayName()); } else { IssueTrackerResponse result = service.sendRequests(context, requests); statusMessage = result.getStatusMessage(); } return new MessageResult(statusMessage); } @Override public String getDestinationName() { return descriptorKey.getUniversalKey(); } }
43.208333
149
0.77242
6d9cbddfdb5f560d9a9ec562f8e1b86c63444834
76,226
package rusting.content; import arc.graphics.Color; import arc.graphics.g2d.Draw; import arc.struct.*; import mindustry.content.*; import mindustry.ctype.ContentList; import mindustry.entities.Effect; import mindustry.entities.bullet.BulletType; import mindustry.gen.Sounds; import mindustry.graphics.CacheLayer; import mindustry.graphics.Pal; import mindustry.type.*; import mindustry.world.Block; import mindustry.world.blocks.defense.Wall; import mindustry.world.blocks.defense.turrets.*; import mindustry.world.blocks.environment.*; import mindustry.world.blocks.power.LightBlock; import mindustry.world.blocks.production.GenericCrafter; import mindustry.world.blocks.storage.CoreBlock; import mindustry.world.blocks.units.Reconstructor; import mindustry.world.blocks.units.UnitFactory; import mindustry.world.meta.*; import rusting.core.holder.PanelHolder; import rusting.core.holder.ShootingPanelHolder; import rusting.entities.bullet.BounceBulletType; import rusting.entities.bullet.BulletSpawnBulletType; import rusting.world.blocks.OverrideColourStaticWall; import rusting.world.blocks.PlayerCore; import rusting.world.blocks.capsules.CapsuleBlockResearchCenter; import rusting.world.blocks.defense.ProjectileAttackWall; import rusting.world.blocks.defense.turret.*; import rusting.world.blocks.defense.turret.healer.*; import rusting.world.blocks.defense.turret.power.LightningTurret; import rusting.world.blocks.defense.turret.power.PanelTurret; import rusting.world.blocks.distribution.FrictionConveyor; import rusting.world.blocks.environment.*; import rusting.world.blocks.logic.UnbreakableMessageBlock; import rusting.world.blocks.logic.WaveAlarm; import rusting.world.blocks.power.AttributeBurnerGenerator; import rusting.world.blocks.production.ConditionalDrill; import rusting.world.blocks.pulse.PulseBlock; import rusting.world.blocks.pulse.PulseBoulder; import rusting.world.blocks.pulse.crafting.*; import rusting.world.blocks.pulse.defense.*; import rusting.world.blocks.pulse.distribution.*; import rusting.world.blocks.pulse.production.*; import rusting.world.blocks.pulse.unit.*; import rusting.world.blocks.pulse.utility.*; import rusting.world.draw.*; import static mindustry.type.ItemStack.with; public class RustingBlocks implements ContentList{ public static Block capsuleCenterTest, //environment //liquids melainLiquae, coroLiquae, impurenBurneLiquae, impurenBurneLiquaeDeep, classemLiquae, //sunken metal floor sunkenMetalFloor, sunkenMetalFloor2, sunkenMetalFloor3, sunkenBasalt, sunkenHotrock, sunkenMagmarock, //floor //frae plating fraePlating, fraePlatingHorizontal, fraePlatingVertical, fraePlating2, fraePlating3, fraePlating4, fraePlating5, fraePlating6, fraePlating7, fraePlating8, fraeAgedMetal, fraePulseCapedWall, //mhem plating mhemPlating, mhemPlating3, mhemPlating4, mhemPlating5, mhemAgedFraeBlock, mhemAgedMetal, //pailean paileanStolnen, paileanSanden, paileanPathen, paileanWallen, paileanBarreren, //ebrin, drier pailean blocks ebrinDrylon, //saline, slaty blocks salineStolnene, salineBarreren, //classem classemStolnene, classemSanden, classemPathen, classemPulsen, classemWallen, classemBarrreren, classemTree, classemTreeDead, classemTreeCrystalline, melonaleumGeodeSmall, melonaleumGeodeLarge, //impuren impurenSanden, //moisten moistenStolnene, moistenLushen, moistenWallen, moistenVinen, //dripive dripiveGrassen, dripiveWallen, //volen, drier variants of normal stone, could be used for warmer looking maps. Not resprited stone floors, I promise volenStolnene, volenWallen, //ore blocks melonaleum, taconite, cameoShardling, //crafting bulasteltForgery, desalinationMixer, cameoCrystallisingBasin, cameoPaintMixer, camaintAmalgamator, cameoHarvestingBasin, //defense terraMound, terraMoundLarge, hailsiteBarrier, hailsiteBarrierLarge, decilitaCyst, decilitaCystLarge, wol, //power waterBoilerGenerator, //drill terraPulveriser, //distribution terraConveyor, //pulse //Natural Sources melonaleumGeode, largeMelonaleumGeode, hugeMelonaleumGeode, giganticMelonaleumGeode, humungousMelonaleumGeond, amogusMelonaledumDio, //Pulse collection pulseInceptionPoint, pulseCollector, pulseGenerator, infectedsGeneratorCore, //Nodes pulseNode, pulseTesla, //Storage pulseResonator, //Siphon pulseSiphon, //crafting pulseGraphiteForge, pulseGlassFoundry, pulseCondensary, pulseMelomaeMixer, pulseGelPress, //Walls pulseBarrier, pulseBarrierLarge, //Research pulseResearchCenter, //Suport pulseUpkeeper, //teleporter multiblock structure pulseTeleporterController, pulseFlowSplitter, pulseCanal, pulseInputTerminal, pulseCanalTunnel, //particle spawning smallParticleSpawner, //storage fraeCore, craeCore, //endregion storage //turrets //environment/turrets archangel, contingent, pulseMotar, pulseFieldGen, //landmines pulseLandmine, //units pulseCommandCenter, pulseFactory, enlightenmentReconstructor, ascendanceReconstructor, pulseDistributor, //controll pulseDirectionalController, pulseContactSender, //sandbox pulseSource, pulseVoid, //frae fraeResarchCenter, //healer turrets thrum, spikent, conserve, //flamethrower kindle, plasmae, photosphere, //harpoons pilink, tether, //pannel turrets prikend, prsimdeome, prefraecon, rangi, pafleaver, //drylon spraien, glare, //platonic elements represented by four turrets. octain, triagon, cuin, icosahen, //other elemental turrets, wiht names relating to gemstones pulver, //turrets relating almost directly to Pixelcraft with their name but change things up a bit. Classified under elemental in the turret's sprite folder horaNoctis, holocaust, //bomerang related turrets refract, diffract, reflect, //region unit hotSpringSprayer, coldSpringSprayer, fraeFactory, antiquaeGuardianBuilder, absentReconstructor, dwindlingReconstructor, //logic waveAlarm, halsinteLamp, gelBasin, mhemLog, raehLog, fraeLog; public static void addLiquidAmmo(Block turret, Liquid liquid, BulletType bullet){ ((LiquidTurret) turret).ammoTypes.put(liquid, bullet); } public static void addLiquidAmmoes(Block turret, ObjectMap<Liquid, BulletType> map){ map.each((liquid, bullet) -> { ((LiquidTurret) turret).ammoTypes.put(liquid, bullet); }); } public void load(){ //region environment melainLiquae = new Floor("melain-liquae"){{ speedMultiplier = 0.5f; variants = 0; status = RustingStatusEffects.macotagus; statusDuration = 350f; liquidDrop = RustingLiquids.melomae; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.5f; drawLiquidLight = true; emitLight = true; lightColor = new Color(Palr.pulseChargeStart).a(0.15f); lightRadius = 16; }}; coroLiquae = new DamagingFloor("coro-liquae"){{ speedMultiplier = 0.86f; variants = 0; status = StatusEffects.corroded; statusDuration = 1250; liquidDrop = RustingLiquids.cameaint; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.35f; }}; impurenBurneLiquae = new DamagingFloor("impuren-burnen-liquae"){{ speedMultiplier = 1.34f; variants = 0; status = StatusEffects.burning; statusDuration = 15; liquidDrop = null; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.65f; damage = 0.055f; }}; impurenBurneLiquaeDeep = new DamagingFloor("impuren-burnen-liquae-deep"){{ speedMultiplier = 1.34f; variants = 0; status = StatusEffects.burning; statusDuration = 15; liquidDrop = null; isLiquid = true; drownTime = 350; cacheLayer = CacheLayer.water; albedo = 0.65f; damage = 0.075f; }}; classemLiquae = new Floor("classem-liquae"){{ speedMultiplier = 1.16f; variants = 0; status = StatusEffects.wet; statusDuration = 1250; liquidDrop = Liquids.water; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.25f; }}; sunkenMetalFloor = new Floor("sunken-metal-floor"){{ speedMultiplier = 0.85f; variants = 0; status = StatusEffects.wet; statusDuration = 90f; liquidDrop = Liquids.water; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.5f; }}; sunkenMetalFloor2 = new Floor("sunken-metal-floor2"){{ speedMultiplier = 0.85f; variants = 0; status = StatusEffects.wet; statusDuration = 90f; liquidDrop = Liquids.water; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.5f; }}; sunkenMetalFloor3 = new Floor("sunken-metal-floor3"){{ speedMultiplier = 0.85f; variants = 0; status = StatusEffects.wet; statusDuration = 90f; liquidDrop = Liquids.water; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.5f; }}; sunkenBasalt = new Floor("sunken-basalt"){{ status = StatusEffects.wet; statusDuration = 90f; liquidDrop = Liquids.water; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.5f; }}; sunkenHotrock = new EffectFloor("sunken-hotrock"){{ status = StatusEffects.wet; statusDuration = 90f; liquidDrop = Liquids.water; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.5f; attributes.set(Attribute.heat, 0.15f); }}; sunkenMagmarock = new EffectFloor("sunken-magmarock"){{ status = StatusEffects.wet; statusDuration = 90f; liquidDrop = Liquids.water; isLiquid = true; cacheLayer = CacheLayer.water; albedo = 0.5f; attributes.set(Attribute.heat, 0.35f); }}; fraePlating = new Floor("frae-aged-plating"){{ variants = 0; }}; fraePlatingHorizontal = new Floor("frae-aged-plating-horizontalin"){{ variants = 0; blendGroup = fraePlating; }}; fraePlatingVertical = new Floor("frae-aged-plating-verticalin"){{ variants = 0; blendGroup = fraePlating; }}; fraePlating2 = new Floor("frae-aged-plating2"){{ variants = 0; blendGroup = fraePlating; }}; fraePlating3 = new Floor("frae-aged-plating3"){{ variants = 0; blendGroup = fraePlating; }}; fraePlating4 = new Floor("frae-aged-plating4"){{ variants = 0; blendGroup = fraePlating; }}; fraePlating5 = new Floor("frae-aged-plating5"){{ variants = 0; blendGroup = fraePlating; }}; fraePlating6 = new Floor("frae-aged-plating6"){{ variants = 0; blendGroup = fraePlating; }}; fraePlating7 = new Floor("frae-aged-plating7"){{ variants = 0; blendGroup = fraePlating; }}; fraePlating8 = new Floor("frae-aged-plating8"){{ variants = 0; blendGroup = fraePlating; }}; fraeAgedMetal = new StaticWall("frae-aged-metal-block"){{ variants = 2; }}; mhemPlating = new Floor("mhem-aged-plating"){{ variants = 0; }}; mhemPlating3 = new Floor("mhem-aged-plating3"){{ variants = 0; blendGroup = mhemPlating; }}; mhemPlating4 = new Floor("mhem-aged-plating4"){{ variants = 0; blendGroup = mhemPlating; }}; mhemPlating5 = new Floor("mhem-aged-plating5"){{ variants = 0; blendGroup = mhemPlating; }}; mhemAgedFraeBlock = new StaticWall("mhem-aged-frae-block"){{ variants = 1; }}; mhemAgedMetal = new StaticWall("mhem-aged-metal-block"){{ variants = 3; }}; paileanStolnen = new Floor("pailean-stolnen"){{ speedMultiplier = 0.95f; variants = 3; attributes.set(Attribute.water, -0.85f); wall = paileanWallen; }}; paileanSanden = new Floor("pailean-sanden"){{ speedMultiplier = 0.75f; variants = 3; wall = paileanWallen; }}; paileanPathen = new Floor("pailean-pathen"){{ speedMultiplier = 0.8f; variants = 2; attributes.set(Attribute.water, -0.85f); attributes.set(Attribute.heat, 0.075f); blendGroup = paileanStolnen; wall = paileanWallen; }}; ebrinDrylon = new Floor("ebrin-drylon"){{ itemDrop = Items.sand; speedMultiplier = 0.75f; variants = 6; attributes.set(Attribute.water, -1f); attributes.set(Attribute.spores, -0.15f); attributes.set(Attribute.heat, 0.025f); wall = paileanBarreren; }}; salineStolnene = new Floor("saline-stolnene"){{ speedMultiplier = 0.85f; variants = 3; status = RustingStatusEffects.hailsalilty; attributes.set(Attribute.water, -1f); attributes.set(Attribute.spores, -0.35f); wall = salineBarreren; }}; classemStolnene = new Floor("classem-stolnene"){{ speedMultiplier = 0.85f; variants = 3; emitLight = true; lightColor = new Color(Palr.pulseChargeStart).a(0.05f); lightRadius = 10; attributes.set(Attribute.water, 0.15f); attributes.set(Attribute.heat, -0.15f); wall = classemBarrreren; }}; classemSanden = new Floor("classem-sanden"){{ speedMultiplier = 0.85f; variants = 3; itemDrop = Items.sand; emitLight = true; lightColor = new Color(Palr.pulseChargeStart).a(0.05f); lightRadius = 10; attributes.set(Attribute.water, 0.125f); attributes.set(Attribute.heat, -0.05f); wall = classemBarrreren; }}; classemPulsen = new Floor("classem-pulsen"){{ speedMultiplier = 0.85f; variants = 6; status = RustingStatusEffects.fuesin; emitLight = true; lightColor = new Color(Palr.pulseChargeStart).a(0.09f); lightRadius = 25; attributes.set(Attribute.water, 0.75f); attributes.set(Attribute.heat, -0.55f); attributes.set(Attribute.spores, -0.15f); wall = classemPulsen; }}; classemPathen = new Floor("classem-pathen"){{ speedMultiplier = 0.85f; variants = 2; status = RustingStatusEffects.macrosis; emitLight = true; lightColor = new Color(Palr.pulseChargeStart).a(0.12f); lightRadius = 25; attributes.set(Attribute.water, 1.35f); attributes.set(Attribute.heat, -0.35f); wall = classemBarrreren; }}; impurenSanden = new DamagingFloor("impuren-sanden"){{ speedMultiplier = 1.15f; variants = 3; itemDrop = Items.sand; status = StatusEffects.burning; attributes.set(Attribute.heat, 0.15f); wall = volenWallen; damage = 0.005f; }}; moistenStolnene = new Floor("moisten-stolnene"){{ variants = 6; status = StatusEffects.muddy; attributes.set(Attribute.water, 0.25f); wall = moistenWallen; }}; moistenLushen = new Floor("moisten-lushen"){{ variants = 4; attributes.set(Attribute.water, 0.35f); wall = moistenVinen; }}; dripiveGrassen = new Floor("dripive-grassen"){{ speedMultiplier = 0.95f; attributes.set(Attribute.water, 1.14f); attributes.set(Attribute.spores, -0.25f); attributes.set(Attribute.heat, -0.35f); wall = dripiveWallen; }}; volenStolnene = new Floor("volen-stolnene"){{ variants = 3; wall = volenStolnene; }}; paileanWallen = new StaticWall("pailean-wallen"){{ variants = 2; }}; paileanBarreren = new StaticWall("pailean-barreren"){{ variants = 2; }}; salineBarreren = new StaticWall("saline-barreren"){{ variants = 3; }}; classemWallen = new StaticWall("classem-wallen"){{ variants = 3; }}; classemBarrreren = new OverrideColourStaticWall("classem-barreren"){{ variants = 5; overrideMapColour = Color.valueOf("#2c2f3b"); }}; classemTree = new TreeBlock("classem-tree"){{ }}; moistenWallen = new OverrideColourStaticWall("moisten-wallen"){{ variants = 3; overrideMapColour = Color.valueOf("#716765"); }}; moistenVinen = new StaticWall("moisten-vinen"){{ variants = 2; }}; dripiveWallen = new StaticWall("dripive-wallen"){{ variants = 2; }}; volenWallen = new StaticWall("volen-wallen"){{ variants = 2; }}; melonaleum = new FixedOreBlock("melonaleum"){{ itemDrop = RustingItems.melonaleum; overrideMapColor = itemDrop.color; variants = 2; }}; taconite = new FixedOreBlock("taconite"){{ itemDrop = RustingItems.taconite; overrideMapColor = itemDrop.color; variants = 3; }}; cameoShardling = new FixedOreBlock("cameo-shardling"){{ itemDrop = RustingItems.cameoShardling; overrideMapColor = itemDrop.color; variants = 3; }}; //endregion fraePulseCapedWall = new PulseBlock("pulse-capped-frae-wall"){{ requirements(Category.defense, with(Items.titanium, 35, RustingItems.bulastelt, 15, RustingItems.cameoShardling, 25)); buildVisibility = BuildVisibility.editorOnly; researchTypes.add(RustingResearchTypes.capsule); }}; capsuleCenterTest = new CapsuleBlockResearchCenter("etst"){{ requirements(Category.effect, with()); }}; //region crafting bulasteltForgery = new GenericCrafter("bulastelt-forgery"){{ requirements(Category.crafting, with(Items.lead, 35, Items.coal, 25, RustingItems.taconite, 65)); craftEffect = Fx.smeltsmoke; outputItem = new ItemStack(RustingItems.bulastelt, 6); craftTime = 425f; size = 2; hasPower = false; hasLiquids = true; drawer = new DrawLiquidSmelter(); consumes.items(with(Items.coal, 3, RustingItems.taconite, 5)); }}; desalinationMixer = new GenericCrafter("desalination-mixer"){{ requirements(Category.crafting, with(Items.lead, 65, Items.graphite, 15, Items.silicon, 35, Items.sand, 85)); craftEffect = Fxr.salty; outputItem = new ItemStack(RustingItems.halsinte, 3); craftTime = 125; size = 2; hasPower = true; hasLiquids = true; drawer = new DrawItemLiquid(); consumes.power(7.2f); consumes.liquid(Liquids.water, 0.1235f); }}; cameoPaintMixer = new ResearchableCrafter("cameo-paint-mixer"){{ requirements(Category.crafting, with(Items.lead, 145, Items.graphite, 75, Items.titanium, 45, RustingItems.bulastelt, 65)); centerResearchRequirements(true, ItemStack.with(Items.silicon, 355, RustingItems.halsinte, 135, RustingItems.bulastelt, 65)); researchTypes.add(RustingResearchTypes.capsule); buildVisibility = BuildVisibility.hidden; craftEffect = Fx.none; outputLiquid = new LiquidStack(RustingLiquids.cameaint, 7.5f); craftTime = 50; size = 3; drawer = new DrawRotorTop(); consumes.power(0.72f); consumes.items(with(Items.lead, 1, Items.copper, 3, RustingItems.halsinte, 2)); consumes.liquid(Liquids.water, 0.25f); }}; cameoCrystallisingBasin = new ResearchableCrafter("cameo-crystallising-basin"){{ requirements(Category.crafting, with(Items.lead, 65, Items.graphite, 85, Items.silicon, 145, RustingItems.bulastelt, 55)); centerResearchRequirements(true, ItemStack.with(Items.silicon, 355, RustingItems.halsinte, 135, RustingItems.bulastelt, 65)); researchTypes.add(RustingResearchTypes.capsule); craftEffect = Fx.none; outputItem = new ItemStack(RustingItems.cameoShardling, 6); craftTime = 325; size = 4; hasPower = true; hasLiquids = true; drawer = new DrawItemLiquid(); consumes.power(7.2f); consumes.liquid(RustingLiquids.cameaint, 0.447f); }}; camaintAmalgamator = new ResearchableCrafter( "camaint-amalgamator"){{ requirements(Category.crafting, with(RustingItems.taconite, 95, RustingItems.bulastelt, 75, RustingItems.cameoShardling, 55)); centerResearchRequirements(true, ItemStack.with(Items.silicon, 650, RustingItems.gelChip, 150, RustingItems.bulastelt, 165, RustingItems.cameoShardling, 150)); researchTypes.add(RustingResearchTypes.capsule); craftEffect = Fx.none; outputItem = new ItemStack(RustingItems.camaintAmalgam, 8); craftTime = 150; size = 2; hasPower = true; hasLiquids = true; consumes.power(3.25f); consumes.liquid(RustingLiquids.cameaint, 0.635f); consumes.items(with(Items.titanium, 3, RustingItems.bulastelt, 4, RustingItems.cameoShardling, 2)); }}; cameoHarvestingBasin = new GenericCrafter("cameo-harvesting-basin"){{ requirements(Category.crafting, with(RustingItems.taconite, 95, RustingItems.bulastelt, 75, RustingItems.cameoShardling, 55)); //centerResearchRequirements(false, ItemStack.with(Items.silicon, 650, RustingItems.gelChip, 150, RustingItems.bulastelt, 165, RustingItems.cameoShardling, 150)); craftEffect = Fx.none; craftTime = 950; size = 3; hasPower = true; hasLiquids = true; consumes.power(3.25f); consumes.liquid(RustingLiquids.cameaint, 0.0635f); consumes.items(with(Items.titanium, 3, RustingItems.bulastelt, 4, RustingItems.cameoShardling, 2)); }}; //endregion crafting //region defense terraMound = new Wall("terra-mound"){{ requirements(Category.defense, with(Items.coal, 6, RustingItems.taconite, 3, RustingItems.bulastelt, 1)); size = 1; health = 420 * size * size; insulated = true; }}; terraMoundLarge = new Wall("terra-mound-large"){{ requirements(Category.defense, with(Items.coal, 24, RustingItems.taconite, 12, RustingItems.bulastelt, 4)); size = 2; health = 420 * size * size; insulated = true; }}; hailsiteBarrier = new ProjectileAttackWall("hailsite-barrier"){{ requirements(Category.defense, with(RustingItems.taconite, 3, RustingItems.halsinte, 7)); size = 1; health = 355 * size * size; variants = 2; absorbLasers = true; }}; hailsiteBarrierLarge = new ProjectileAttackWall("hailsite-barrier-large"){{ requirements(Category.defense, with(RustingItems.taconite, 12, RustingItems.halsinte, 28)); size = 2; health = 355 * size * size; variants = 2; absorbLasers = true; deathProjectiles = 23; }}; decilitaCyst = new ProjectileAttackWall("decilita-cyst"){{ requirements(Category.defense, with(RustingItems.decilita, 4, RustingItems.bulastelt, 6)); size = 1; health = 150 * size * size; variants = 2; deathProjectiles = 3; bullet = deathBullet = RustingBullets.fossilShard; }}; decilitaCystLarge = new ProjectileAttackWall("decilita-cyst-large"){{ requirements(Category.defense, with(RustingItems.decilita, 16, RustingItems.bulastelt, 24)); size = 2; health = 150 * size * size; deathProjectiles = 12; bullet = deathBullet = RustingBullets.fossilShard; }}; wol = new Wall("wol"){{ requirements(Category.defense, with(Items.coal, 24, RustingItems.taconite, 12, RustingItems.bulastelt, 4)); size = 1; health = 420 * size * size; }}; //endregion defense //region power waterBoilerGenerator = new AttributeBurnerGenerator("water-boiler-generator"){{ requirements(Category.power, with(Items.copper, 40, Items.graphite, 35, Items.lead, 50, Items.silicon, 35, Items.metaglass, 40)); powerProduction = 3.25f; generateEffect = Fx.redgeneratespark; size = 3; minItemEfficiency = 0.15f; consumes.liquid(Liquids.water, 0.12f).optional(false, false); }}; //endregion //region drill terraPulveriser = new ConditionalDrill("terra-pulveriser"){{ requirements(Category.production, with(Items.copper, 25, Items.coal, 15, RustingItems.taconite, 15)); size = 2; tier = 2; drops = Seq.with( new ItemDrop(){{ item = RustingItems.taconite; floors = Seq.with(Blocks.stone.asFloor(), Blocks.craters.asFloor(), Blocks.basalt.asFloor()); }}, new ItemDrop(){{ item = Items.sand; floors = Seq.with(Blocks.sand.asFloor(), Blocks.darksand.asFloor(), Blocks.sandWater.asFloor(), Blocks.darksandWater.asFloor()); }}, new ItemDrop(){{ item = Items.coal; floors = Seq.with(Blocks.charr.asFloor()); }}, new ItemDrop(){{ item = RustingItems.halsinte; floors = Seq.with(Blocks.salt.asFloor(), salineStolnene.asFloor()); }} ); consumes.liquid(Liquids.water, 0.05f).boost(); }}; //endregion //region distribution terraConveyor = new FrictionConveyor("terra-conveyor"){{ requirements(Category.distribution, with(Items.copper, 2, RustingItems.taconite, 1)); health = 95; speed = 0.05f; displayedSpeed = 5.5f; floating = true; Draw.mixcol(); }}; //endregion distribution //region pulse //a small geode containing a lot of Pulse. Destroyable for it's Melonaleum crystals (the less Pulse is siphoned the more crystals drop on the floor for collection) but the more volatile the Geode is melonaleumGeode = new PulseBoulder("melonaleum-geode"){{ category = Category.power; buildVisibility = BuildVisibility.sandboxOnly; health = 250; pulseCapacity = 650; selfDamage = 0.25f; pulseProduction = 0.075f; passiveEffect = Fxr.craeWeaversResidue; effectChance = 0.08f; hideFromUI(); }}; //region collection pulseInceptionPoint = new PulseSapper("pulse-inception-point") {{ requirements(Category.power, with(Items.lead, 10, Items.titanium, 5, Items.graphite, 4)); centerResearchRequirements(false, with()); health = 250; collectSpeed = 0.1f; pulseCapacity = 15; pulsePressure = 10; }}; //Collects pulse. Requires some sort of Siphon to collect the pulse. pulseCollector = new PulseGenerator("pulse-collector"){{ requirements(Category.power, with(Items.copper, 35, Items.coal, 15, Items.titanium, 10)); centerResearchRequirements(false, with()); size = 1; canOverload = false; configurable = false; productionTime = 50; pulseAmount = 7.5f; connectionsPotential = 0; connectable = false; pulseCapacity = 55; resistance = 0.75f; laserOffset = 4; }}; //Rapidly collects pulse. Quite good at storing pulse. Needs Pulse to kickstart the process. pulseGenerator = new PulseGenerator("pulse-generator"){{ requirements(Category.power, with(Items.copper, 90, Items.silicon, 55, Items.titanium, 45)); centerResearchRequirements(true, with(Items.copper, 350, Items.coal, 125, Items.graphite, 95, Items.titanium, 225, RustingItems.melonaleum, 85)); consumes.item(RustingItems.melonaleum, 1); size = 3; canOverload = true; overloadCapacity = 125; productionTime = 30; pulseAmount = 43.5f; pulseReloadTime = 15; energyTransmission = 8.5f; connectionsPotential = 3; pulseCapacity = 275; resistance = 0.25f; laserOffset = 10; laserRange = 7; minRequiredPulsePercent = 0.35f; }}; infectedsGeneratorCore = new InfectedsGeneratorCore("infecteds-generator-core"){{ requirements(Category.power, with(Items.lead, 450, Items.titanium, 650, Items.metaglass, 350, RustingItems.melonaleum, 350, RustingItems.gelChip, 540)); centerResearchRequirements(true, with(Items.titanium, 1500, Items.metaglass, 2340, RustingItems.gelChip, 950, RustingItems.melonaleum, 1250)); consumes.item(RustingItems.melonaleum, 3); size = 6; canOverload = true; overloadCapacity = 1250; productionTime = 10; pulseAmount = 115.5f; pulseReloadTime = 5; energyTransmission = 45.5f; connectionsPotential = 7; pulseCapacity = 2350; resistance = 0.25f; laserOffset = 10; laserRange = 55; minRequiredPulsePercent = 0.35f; }}; //endregion collection //Loses power fast, but is great at transmitting pulses to far blocks. pulseCanal = new PulseCanal("pulse-canal"){{ requirements(Category.power, with(Items.lead, 2, Items.titanium, 1)); centerResearchRequirements(false, with()); pulseCapacity = 25; }}; pulseFlowSplitter = new PulseFlowSplitter("pulse-flow-splitter"){{ requirements(Category.power, with(Items.lead, 4, Items.titanium, 3)); centerResearchRequirements(false, with()); pulseCapacity = 65; }}; pulseCanalTunnel = new PulseCanalTunnel("pulse-tunnel-dock"){{ hideFromUI(); }}; pulseNode = new PulseNode("pulse-node"){{ requirements(Category.power, with(Items.copper, 5, Items.lead, 4, Items.titanium, 3)); centerResearchRequirements(true, with(Items.copper, 120, Items.lead, 95, Items.titanium, 65)); size = 1; drain = 0.0025f; pulseReloadTime = 15; energyTransmission = 25f; pulseCapacity = 65; resistance = 0.075f; laserRange = 13; canOverload = false; }}; //Shoots lightning around itself when overloaded. Easly overloads. Acts as a large power node, with two connections, but slower reload pulseTesla = new PulseNode("pulse-tesla"){{ requirements(Category.power, with(Items.copper, 65, Items.lead, 45, Items.graphite, 25, Items.titanium, 20)); centerResearchRequirements(true, with(Items.copper, 365, Items.lead, 175, Items.coal, 155, Items.titanium, 80)); size = 2; projectile = RustingBullets.craeBolt; projectileChanceModifier = 0.15f; drain = 0.00835f; pulseReloadTime = 35; minRequiredPulsePercent = 0.15f; connectionsPotential = 2; energyTransmission = 35f; pulseCapacity = 95; overloadCapacity = 15; resistance = 0.075f; laserOffset = 3; laserRange = 18; canOverload = true; }}; //stores power for later usage less effectively than nodes, but stores more power. Transmits power to blocks nearby with less pulse power percentage. pulseResonator = new ConductivePulseBlock("pulse-resonator"){{ requirements(Category.power, with(Items.copper, 35, Items.silicon, 20, Items.titanium, 10)); centerResearchRequirements(false, with()); health = 350; size = 1; drain = 0.00425f; resistance = 0; pulseCapacity = 350; energyTransmission = 2.5f; canOverload = false; }}; pulseSiphon = new PulseSiphon("pulse-siphon"){{ requirements(Category.power, with(Items.copper, 10, Items.graphite, 20, Items.titanium, 15)); centerResearchRequirements(false, with()); size = 1; drain = 0.000035f; siphonAmount = 5; energyTransmission = 11f; pulseReloadTime = 55; pulseCapacity = 35; laserRange = 6; canOverload = false; }}; pulseGraphiteForge = new PulseGenericCrafter("pulse-graphite-forge"){{ requirements(Category.crafting, with(Items.lead, 65, Items.graphite, 25, Items.titanium, 35)); centerResearchRequirements(false, with(Items.coal, 125, Items.silicon, 45, Items.metaglass, 65, Items.titanium, 85)); drawer = new DrawPulseSpinningCrafter(); size = 2; itemCapacity = 20; drain = 0.05f; pulseCapacity = 240; canOverload = false; minRequiredPulsePercent = 0.45f; customConsumes.pulse = 14; craftTime = 75; consumes.items(ItemStack.with(Items.coal, 4, Items.sand, 2)); outputItems = ItemStack.with(Items.graphite, 2, Items.silicon, 1); }}; pulseGlassFoundry = new PulseForgery("pulse-glass-foundry"){{ requirements(Category.crafting, with(Items.graphite, 65, Items.silicon, 25, Items.titanium, 35)); centerResearchRequirements(false, with(Items.coal, 125, Items.silicon, 45, Items.metaglass, 65, Items.titanium, 85)); size = 2; itemCapacity = 30; drain = 0.05f; pulseCapacity = 240; canOverload = false; minRequiredPulsePercent = 0.45f; customConsumes.pulse = 14; craftTime = 75; updateEffectChance = 0.05f; consumes.items(ItemStack.with(Items.lead, 6, Items.sand, 15)); outputItems = ItemStack.with(Items.metaglass, 10, Items.silicon, 4); }}; pulseCondensary = new PulseCondensary("pulse-melonaleum-condensery"){{ requirements(Category.crafting, with(Items.copper, 345, Items.coal, 235, Items.silicon, 200, Items.titanium, 185, Items.metaglass, 130)); centerResearchRequirements(true, with(Items.coal, 65, Items.silicon, 45, Items.pyratite, 25, Items.metaglass, 85)); size = 2; drain = 0.35f; pulseCapacity = 1750; canOverload = false; minRequiredPulsePercent = 0.65f; customConsumes.pulse = 350; craftTime = 85; drawer = new CondensaryDrawer(); itemCapacity = 70; consumes.liquid(RustingLiquids.melomae, 1.725f); outputItems = ItemStack.with(RustingItems.melonaleum, 35); }}; pulseMelomaeMixer = new PulseGenericCrafter("pulse-melomae-mixer"){{ requirements(Category.crafting, with(Items.lead, 80, Items.titanium, 15, Items.metaglass, 45)); centerResearchRequirements(true, with(Items.coal, 125, Items.silicon, 45, Items.metaglass, 65, Items.titanium, 85)); drawer = new DrawPulseLiquidMixer(); hasLiquids = true; size = 2; drain = 0.05f; pulseCapacity = 150; canOverload = false; minRequiredPulsePercent = 0.45f; customConsumes.pulse = 6.5f; consumes.liquid(Liquids.water, 0.16f); craftTime = 15; liquidCapacity = 75; outputLiquid = new LiquidStack(RustingLiquids.melomae, 3); }}; pulseGelPress = new PulseGenericCrafter("pulse-gel-press"){{ requirements(Category.crafting, with(Items.copper, 95, Items.metaglass, 65, Items.plastanium, 55, RustingItems.halsinte, 35)); centerResearchRequirements(true, with(Items.coal, 125, Items.silicon, 45, Items.metaglass, 65, Items.titanium, 85)); drawer = new DrawPulseLiquidCrafter(); hasLiquids = true; size = 3; drain = 0.05f; pulseCapacity = 350; canOverload = false; minRequiredPulsePercent = 0.45f; customConsumes.pulse = 45; consumes.liquid(RustingLiquids.melomae, 0.16f); consumes.items(ItemStack.with(RustingItems.bulastelt, 2, RustingItems.halsinte, 3, Items.lead, 1)); craftTime = 85; liquidCapacity = 75; outputItems = ItemStack.with(RustingItems.gelChip, 3); }}; pulseBarrier = new PulseBarrier("pulse-barrier"){{ requirements(Category.defense, with(Items.copper, 8, Items.graphite, 6, Items.titanium, 5)); centerResearchRequirements(true, with(Items.copper, 115, Items.coal, 65, Items.titanium, 30)); size = 1; health = 410 * size * size; drain = 0.35f; pulseCapacity = 240; overloadCapacity = 1350; canOverload = true; shieldRadius = 10; shieldSides = 4; }}; pulseBarrierLarge = new PulseBarrier("pulse-barrier-large"){{ requirements(Category.defense, with(Items.copper, 32, Items.graphite, 24, Items.titanium, 20)); centerResearchRequirements(true, with(Items.copper, 450, Items.graphite, 75, Items.titanium, 120)); size = 2; health = 410 * size * size; drain = 0.000035f; pulseCapacity = 135; laserOffset = 5.5f; canOverload = false; }}; pulseResearchCenter = new PulseResearchBlock("pulse-research-center"){{ requirements(Category.effect, with(Items.copper, 65, Items.lead, 50, Items.coal, 25)); centerResearchRequirements(false, with(Items.copper, 40, Items.coal, 15)); size = 2; fieldNames.add("pulseCapacity"); fieldNames.add("canOverload"); }}; pulseUpkeeper = new PulseChainNode("pulse-upkeeper"){{ requirements(Category.effect, with(Items.copper, 95, Items.lead, 75, Items.silicon, 45, Items.titanium, 25)); centerResearchRequirements(true, with(Items.copper, 550, Items.coal, 355, Items.metaglass, 100, Items.graphite, 125, Items.titanium, 175, RustingItems.melonaleum, 75)); size = 2; drain = 0.0000155f; minRequiredPulsePercent = 0.5f; pulseReloadTime = 165; connectionsPotential = 4; energyTransmission = 0.5f; pulseCapacity = 70; overloadCapacity = 30; laserRange = 10; laserOffset = 9; healingPercentCap = 13; healPercent = 26; healPercentFalloff = healPercent/3; overdrivePercent = 0.65f; }}; smallParticleSpawner = new PulseParticleSpawner("small-particle-spawner"){{ requirements(Category.effect, with(Items.silicon, 5, Items.graphite, 2, Items.titanium, 10)); centerResearchRequirements(false, with()); flags = EnumSet.of(BlockFlag.generator); effects = new Effect[] {Fxr.blueSpark}; size = 1; health = 35 * size * size; projectileChanceModifier = 0; customConsumes.pulse = 0.25f; pulseCapacity = 70; overloadCapacity = 30; drain = 0; minRequiredPulsePercent = 0; canOverload = true; effectFrequency = 0.45f; lightRadius = 145; lightAlpha = 0.3f; lightColor = Palr.pulseBullet; }}; fraeCore = new CoreBlock("frae-core"){{ requirements(Category.effect, BuildVisibility.editorOnly, with(Items.copper, 1000, Items.lead, 800)); alwaysUnlocked = false; unitType = RustingUnits.duoly; health = 2100; itemCapacity = 6500; size = 3; unitCapModifier = 13; }}; //Todo: fully flesh this out craeCore = new PlayerCore("crae-core"){{ requirements(Category.effect, BuildVisibility.editorOnly, with(Items.copper, 1000, Items.lead, 800)); alwaysUnlocked = false; unitType = RustingUnits.glimpse; unitTypes = Seq.with(RustingUnits.glimpse, RustingUnits.unwavering); solid = false; health = 2100; itemCapacity = 6500; size = 3; unitCapModifier = 13; }}; archangel = new DysfunctionalMonolith("archangel"){{ requirements(Category.effect, with(Items.copper, 300, Items.lead, 115, Items.metaglass, 50, Items.titanium, 45)); centerResearchRequirements(with(Items.copper, 350, Items.coal, 95, Items.graphite, 55, Items.titanium, 225)); flags = EnumSet.of(BlockFlag.turret); size = 3; health = 135 * size * size; projectile = RustingBullets.craeWeaver; projectileChanceModifier = 0; reloadTime = 125; shots = 2; bursts = 3; burstSpacing = 3; inaccuracy = 5; customConsumes.pulse = 65; cruxInfiniteConsume = false; pulseCapacity = 140; overloadCapacity = 30; drain = 0; minRequiredPulsePercent = 0; canOverload = true; }}; pulseMotar = new PulsePulsar("pulse-motar"){{ //requirements(Category.effect, with(Items.copper, 300, Items.lead, 115, Items.metaglass, 50, Items.titanium, 45)); centerResearchRequirements(with(Items.copper, 350, Items.coal, 95, Items.graphite, 55, Items.titanium, 225)); buildVisibility = BuildVisibility.hidden; flags = EnumSet.of(BlockFlag.turret); size = 3; health = 135 * size * size; projectile = RustingBullets.craeQuadStorm; shots = 2; bursts = 3; burstSpacing = 7; inaccuracy = 13; projectileChanceModifier = 0; range = 31; reloadTime = 85; customConsumes.pulse = 25; cruxInfiniteConsume = true; pulseCapacity = 70; overloadCapacity = 30; drain = 0; minRequiredPulsePercent = 0; canOverload = true; }}; pulseFieldGen = new PulseBlock("pulse-rip-field-generator"){{ }}; //region landmines pulseLandmine = new PulseLandmine("pulse-landmine") {{ requirements(Category.effect, with(Items.lead, 15, Items.silicon, 10, RustingItems.melonaleum, 5)); centerResearchRequirements(with(Items.copper, 45, Items.coal, 245, Items.graphite, 95, Items.silicon, 55, RustingItems.melonaleum, 15)); health = 135; reloadTime = 85; shots = 3; customConsumes.pulse = 10; pulseCapacity = 75; cruxInfiniteConsume = true; canOverload = false; drain = 0; }}; //region units pulseCommandCenter = new PulseCommandCenter("pulse-command-center"){{ buildVisibility = buildVisibility.shown; category = Category.units; size = 2; }}; pulseFactory = new PulseUnitFactory("pulse-factory"){{ requirements(Category.units, with(Items.copper, 75, Items.lead, 60, Items.coal, 35, Items.titanium, 25)); centerResearchRequirements(with(Items.copper, 145, Items.lead, 145, Items.graphite, 55, Items.titanium, 85, Items.pyratite, 35)); customConsumes.pulse = 10f; drain = 0.00155f; minRequiredPulsePercent = 0.35f; laserOffset = 8f; pulseCapacity = 55; overloadCapacity = 25; size = 3; plans.addAll( new UnitPlan(RustingUnits.duono, 1920, ItemStack.with(Items.lead, 25, Items.silicon, 35, Items.titanium, 10)), new UnitPlan(RustingUnits.fahrenheit, 1250, ItemStack.with(Items.lead, 35, Items.silicon, 15, RustingItems.melonaleum, 10)) ); }}; //not for player use, however accessible through custom games antiquaeGuardianBuilder = new GuardianPulseUnitFactory("antiquae-guardian-builder"){{ requirements(Category.units, with(Items.copper, 75, Items.lead, 60, Items.coal, 35, Items.titanium, 25)); centerResearchRequirements(false, with(Items.copper, 145, Items.lead, 145, Items.graphite, 55, Items.titanium, 85, Items.pyratite, 35)); consumes.liquid(RustingLiquids.melomae, 0.85f); hideFromUI(); buildVisibility = BuildVisibility.hidden; liquidCapacity = 85; customConsumes.pulse = 65f; drain = 0.0f; minRequiredPulsePercent = 0.65f; laserOffset = 8f; pulseCapacity = 1365; canOverload = false; size = 7; cruxInfiniteConsume = true; plans.addAll( new UnitPlan(RustingUnits.stingray, 143080, ItemStack.with(Items.lead, 4550, Items.silicon, 1450, Items.titanium, 3500, RustingItems.halsinte, 2500, RustingItems.melonaleum, 750)) ); }}; enlightenmentReconstructor = new PulseReconstructor("enlightenment-reconstructor") {{ requirements(Category.units, with(Items.copper, 135, Items.lead, 85, Items.silicon, 45, Items.titanium, 35)); centerResearchRequirements(with(Items.copper, 450, Items.lead, 375, Items.silicon, 145, Items.titanium, 135, Items.pyratite, 75, RustingItems.melonaleum, 45)); consumes.items(ItemStack.with(Items.silicon, 35, Items.titanium, 25, RustingItems.melonaleum, 25)); customConsumes.pulse = 25f; drain = 0.00155f; minRequiredPulsePercent = 0.65f; laserOffset = 8f; pulseCapacity = 85; canOverload = false; size = 3; upgrades.add( new UnitType[]{RustingUnits.duono, RustingUnits.duoly}, new UnitType[]{RustingUnits.fahrenheit, RustingUnits.celsius} ); constructTime = 720; }}; ascendanceReconstructor = new PulseReconstructor("ascendance-reconstructor") {{ requirements(Category.units, with(Items.lead, 465, Items.metaglass, 245, Items.pyratite, 85, Items.titanium, 85)); centerResearchRequirements(with(Items.lead, 1255, Items.silicon, 455, Items.titanium, 235, Items.pyratite, 145, RustingItems.melonaleum, 125)); consumes.items(ItemStack.with(Items.silicon, 145, Items.titanium, 55, RustingItems.melonaleum, 55, RustingItems.bulastelt, 85)); customConsumes.pulse = 65f; drain = 0.00155f; minRequiredPulsePercent = 0.55f; laserOffset = 8f; pulseCapacity = 145; canOverload = false; size = 5; upgrades.add( new UnitType[]{RustingUnits.duoly, RustingUnits.duanga}, new UnitType[]{RustingUnits.metaphys, RustingUnits.ribigen} ); constructTime = 720; }}; //region logic pulseDirectionalController = new PulseController("pulse-controller"){{ requirements(Category.effect, with(Items.lead, 465, Items.metaglass, 245, Items.pyratite, 85, Items.titanium, 85)); }}; pulseContactSender = new PulseContactSender("pulse-sender"){{ requirements(Category.effect, with(Items.lead, 465, Items.metaglass, 245, Items.pyratite, 85, Items.titanium, 85)); }}; pulseSource = new PulseSource("pulse-source"){{ category = Category.power; buildVisibility = BuildVisibility.sandboxOnly; }}; //endregion pulse //region frae //temperary block fraeResarchCenter = new CapsuleBlockResearchCenter("frae-research-center"){{ requirements(Category.effect, with(Items.copper, 60, Items.lead, 25, Items.silicon, 25)); size = 2; }}; //endregion frae //region turrets thrum = new HealerBeamTurret("thrum"){{ requirements(Category.turret, with(Items.copper, 60, Items.lead, 25, Items.silicon, 25)); health = 220; size = 1; reloadTime = 60; range = 115; shootCone = 1; powerUse = 0.5f; rotateSpeed = 10; squares = 3; alphaFalloff = 0.65f; maxEffectSize = 4; healing = 40; targetAir = true; targetGround = true; shootType = RustingBullets.paveBolt; }}; spikent = new AreaHealerBeamTurret("spikent"){{ requirements(Category.turret, with(Items.copper, 125, Items.lead, 85, Items.silicon, 55, RustingItems.melonaleum, 35)); health = 650; size = 2; reloadTime = 35; range = 150; shootCone = 3; powerUse = 0.8f; rotateSpeed = 8; alphaFalloff = 0.35f; healing = 35; healRadius = 25; targetAir = true; targetGround = true; shootType = RustingBullets.paveBolt; }}; conserve = new ChainHealerBeamTurret("conserve"){{ requirements(Category.turret, with(Items.copper, 125, Items.lead, 85, Items.silicon, 55, RustingItems.melonaleum, 35)); size = 2; range = 150; reloadTime = 120; healing = 35; shootLength = 4.5f; requiresWarmup = false; }}; kindle = new PowerTurret("kindle"){{ requirements(Category.turret, with()); cooldown = 0.05f; health = 350; reloadTime = 95; range = 185; shootType = new BulletSpawnBulletType(0, 45, "none") {{ consUpdate = RustingBullets.homing; trueSpeed = 0.325f; range = 185; collides = true; pierce = true; pierceBuilding = true; homingPower = 0.05f; homingRange = 0; lifetime = 192; frontColor = Pal.lightPyraFlame; backColor = Palr.darkPyraBloom; despawnEffect = Fx.sparkShoot; drawSize = 3.5f; bullets = Seq.with( new BulletSpawner(){{ bullet = RustingBullets.mhemShard; reloadTime = 35; manualAiming = true; inaccuracy = 0; intervalIn = 35; intervalOut = 65; }} ); }}; }}; plasmae = new DirectAimPowerTurret("plasmae") {{ requirements(Category.turret, with()); cooldown = 0.11f; size = 2; health = 350; reloadTime = 330; shots = 5; burstSpacing = 5; inaccuracy = 5; spread = 5; range = 215; shootLength = 5; shootType = RustingBullets.mhemaeShard; }}; photosphere = new DirectAimPowerTurret("photosphere"){{ requirements(Category.turret, with()); cooldown = 0.11f; size = 3; health = 350; reloadTime = 550; shots = 2; spread = 90; range = 450; shootLength = 5; shootType = new BulletSpawnBulletType(2, 45, "none") {{ consUpdate = RustingBullets.velbasedHomingFlame; trueSpeed = 0.325f; range = 185; collides = true; pierce = true; pierceBuilding = true; homingPower = 0.015f; homingRange = 0; lifetime = 750; frontColor = Pal.lightPyraFlame; backColor = Palr.darkPyraBloom; despawnEffect = Fx.sparkShoot; drawSize = 3.5f; bullets = Seq.with( new BulletSpawner(){{ bullet = new BounceBulletType( 5.5f, 4, "bullet"){{ consUpdate = RustingBullets.velbasedHomingFlame; despawnEffect = Fx.fireSmoke; hitEffect = Fx.fire; bounceEffect = Fxr.shootMhemFlame; incendAmount = 10; status = StatusEffects.burning; statusDuration = 3600; maxRange = 156; width = 6; height = 8; hitSize = 12; lifetime = 85; homingPower = 0.25f; homingRange = 0; homingDelay = 35; hitEffect = Fx.hitFuse; trailLength = 0; bounciness = 0.85f; bounceCap = 0; weaveScale = 4; weaveMag = 3; knockback = 1; drag = 0.0015f; pierceBuilding = false; buildingDamageMultiplier = 0.15f; }}; reloadTime = 15; manualAiming = true; inaccuracy = 0; intervalIn = 35; intervalOut = 65; }} ); }}; }}; pilink = new HarpoonTurret("pilink") {{ requirements(Category.turret, with(Items.lead, 35, RustingItems.bulastelt, 25)); size = 1; health = 250; reloadTime = 115; range = 245; pullStrength = 35; basePullStrength = 0; shootLength = 3.5f; ammoTypes = ObjectMap.of(RustingItems.bulastelt, RustingBullets.buulasteltSmallHarpoon); shootSound = ModSounds.harpoonLaunch; shootEffect = Fx.shootBig; shootShake = 3; }}; tether = new HarpoonTurret("tether"){{ requirements(Category.turret, with(Items.lead, 75, Items.titanium, 55, Items.thorium, 15, RustingItems.camaintAmalgam, 75)); size = 2; health = 350 * size * size; shootLength = 6.25f; reloadTime = 115; range = 245; pullStrength = 85; ammoTypes = ObjectMap.of(RustingItems.cameoShardling, RustingBullets.cameoSmallHarpoon); shootSound = ModSounds.harpoonLaunch; shootEffect = Fx.shootBig; shootShake = 3; unitSort = (unit, x, y) -> unit.vel.len(); }}; prikend = new PowerTurret("prikend"){{ requirements(Category.turret, with(Items.copper, 60, Items.lead, 45, Items.silicon, 35)); range = 185f; shootLength = 2; chargeEffects = 7; recoilAmount = 2f; reloadTime = 75f; cooldown = 0.03f; powerUse = 1.25f; shootShake = 2f; shootEffect = Fx.hitFlameSmall; smokeEffect = Fx.none; heatColor = Color.orange; size = 1; health = 280 * size * size; shootSound = Sounds.bigshot; shootType = RustingBullets.fossilShard; shots = 2; burstSpacing = 15f; inaccuracy = 2; }}; prsimdeome = new PanelTurret("prsimdeome"){{ requirements(Category.turret, with(Items.copper, 85, Items.lead, 70, Items.silicon, 50, RustingItems.bulastelt, 35)); range = 165f; chargeEffects = 7; recoilAmount = 2f; reloadTime = 96f; cooldown = 0.03f; powerUse = 4f; shootShake = 2f; shootEffect = Fxr.shootMhemFlame; smokeEffect = Fx.none; heatColor = Color.red; size = 2; health = 295 * size * size; shootSound = Sounds.flame2; shootType = RustingBullets.mhemShard; shots = 6; spread = 10f; burstSpacing = 5f; inaccuracy = 10; panels.add( new PanelHolder(name){{ panelX = 6; panelY = -4; }} ); }}; prefraecon = new PanelTurret("prefraecon"){{ requirements(Category.turret, with(Items.titanium, 115, Items.silicon, 65, RustingItems.bulastelt, 55, RustingItems.melonaleum, 45)); range = 200f; recoilAmount = 2f; reloadTime = 65f; powerUse = 6f; shootShake = 5f; shootEffect = Fxr.shootMhemFlame; smokeEffect = Fx.none; heatColor = Pal.darkPyraFlame; size = 3; health = 310 * size * size; shootSound = Sounds.release; shootType = RustingBullets.fraeShard; panels.add( new PanelHolder(name){{ panelX = 10; panelY = -4; }} ); }}; rangi = new PanelTurret("rangi"){{ requirements(Category.turret, with(Items.metaglass, 75, Items.silicon, 55, RustingItems.taconite, 45, RustingItems.bulastelt, 25)); range = 166f; recoilAmount = 2f; reloadTime = 145f; shootCone = 360; powerUse = 8f; shootShake = 1f; shootEffect = Fxr.shootMhemFlame; smokeEffect = Fx.none; heatColor = Palr.dustriken; size = 3; health = 255 * size * size; shootSound = Sounds.release; shootType = RustingBullets.cloudyVortex; }}; pafleaver = new PanelTurret("pafleaver"){{ requirements(Category.turret, with(Items.copper, 60, Items.lead, 70, Items.silicon, 50)); buildVisibility = BuildVisibility.hidden; range = 260f; recoilAmount = 2f; reloadTime = 60f; powerUse = 6f; shootShake = 2f; shootEffect = Fxr.shootMhemFlame; smokeEffect = Fx.none; heatColor = Pal.darkPyraFlame; size = 4; health = 345 * size * size; shootSound = Sounds.flame; shootType = RustingBullets.paveShard; shots = 3; burstSpacing = 5; panels.add( new PanelHolder(name + "1"){{ panelX = 10.75; panelY = -4.5; }}, new PanelHolder(name + "2"){{ panelX = -10.75; panelY = -4.5; }}, new ShootingPanelHolder(name + "1"){{ panelX = 13.75; panelY = -3.75; shootType = RustingBullets.mhemShard; lifetimeMulti = 2.5f; }}, new ShootingPanelHolder(name + "2"){{ panelX = -13.75; panelY = -3.75; shootType = RustingBullets.mhemShard; lifetimeMulti = 2.5f; }} ); }}; octain = new AutoreloadItemTurret("octain"){{ requirements(Category.turret, with(Items.graphite, 35, Items.metaglass, 25, RustingItems.taconite, 65)); size = 2; health = 255 * size * size; ammo( Items.metaglass, RustingBullets.spawnerGlass, RustingItems.bulastelt, RustingBullets.spawnerBulat ); shots = 2; burstSpacing = 5; inaccuracy = 2; reloadTime = 125f; recoilAmount = 2.5f; range = 175f; shootCone = 25f; shootSound = Sounds.release; coolantMultiplier = 1.1f; autoreloadThreshold = 1 - 1/reloadTime; }}; triagon = new AutoreloadItemTurret("triagon"){{ requirements(Category.turret, with(Items.graphite, 75, Items.titanium, 45, RustingItems.taconite, 95, RustingItems.bulastelt, 35)); size = 3; health = 295 * size * size; ammo( Items.pyratite, RustingBullets.flamstrikenVortex, RustingItems.melonaleum, RustingBullets.boltingVortex ); shots = 1; reloadTime = 325f; recoilAmount = 2.5f; range = 175f; shootCone = 25f; shootSound = Sounds.release; coolantMultiplier = 1.15f; autoreloadThreshold = 1 - 1/reloadTime; shootLength = 5.25f; }}; cuin = new QuakeTurret("cuin"){{ requirements(Category.turret, with(Items.graphite, 35, Items.metaglass, 25, RustingItems.taconite, 65)); buildVisibility = BuildVisibility.hidden; size = 3; health = 255 * size * size; targetAir = false; shots = 3; spread = 15; reloadTime = 162f; recoilAmount = 2.5f; range = 175f; quakeInterval = 2; spacing = 7; shootCone = 25f; shootSound = Sounds.explosionbig; coolantMultiplier = 0.85f; shootType = Bullets.artilleryIncendiary; shootEffect = Fx.flakExplosion; }}; icosahen = new LiquidBeamTurret("icosahen"){{ requirements(Category.turret, ItemStack.with()); buildVisibility = BuildVisibility.hidden; size = 2; health = 145 * size * size; reloadTime = 250; range = 135; shots = 4; burstSpacing = 3; pressureCap = 11.5f; ammo( Liquids.water, RustingBullets.waterBeamShot, Liquids.slag, RustingBullets.slagBeamShot, Liquids.cryofluid, RustingBullets.cryoBeamShot, Liquids.oil, RustingBullets.oilBeamShot, RustingLiquids.melomae, RustingBullets.melomaeBeamShot, RustingLiquids.cameaint, RustingBullets.cameoBeamShot ); }}; pulver = new LightningTurret("pulver"){{ centerResearchRequirements(true, ItemStack.with(Items.silicon, 260, RustingItems.gelChip, 50)); requirements(Category.turret, ItemStack.with(RustingItems.gelChip, 25, Items.metaglass, 45, RustingItems.bulastelt, 55)); size = 2; health = 185 * size * size; canOverload = true; pulseCapacity = 125; overloadCapacity = 1075; customConsumes.pulse = 10.875f; range = 145; lightning = 4; healAmount = 15; shootCone = 65; reloadTime = 35; damage = 65; shootSound = Sounds.spark; lightColor = Palr.pulseBullet; lightAlpha = 0.65f; beamLength = 35; healEffect = Fxr.healingWaterSmoke; color = Color.valueOf("#a9e2ea"); }}; contingent = new PulsePreciseLaserTurret("contingent"){{ category = Category.effect; buildVisibility = BuildVisibility.sandboxOnly; size = 3; damage = 4.5f; health = 155 * size * size; }}; horaNoctis = new AutoreloadItemTurret("hora-noctis"){{ requirements(Category.turret, with()); buildVisibility = BuildVisibility.hidden; size = 2; health = 165 * size * size; shootLength = -35; range = 265; spread = 2; inaccuracy = 4; xRand = 8; shots = 3; burstSpacing = 6; reloadTime = 42; consumes.power(0.8f); ammo( Items.titanium, RustingBullets.lightfractureTitanim, RustingItems.bulastelt, RustingBullets.lightfractureBulat ); }}; holocaust = new AutoreloadItemTurret("holocaust"){{ requirements(Category.turret, with()); buildVisibility = BuildVisibility.hidden; size = 2; health = 315 * size * size; range = 152; shootLength = 7; spread = 2; inaccuracy = 6; xRand = 5; shots = 2; reloadTime = 4.75f; ammo( Items.pyratite, RustingBullets.longPyraFlame, Items.thorium, RustingBullets.longThorFlame ); }}; spraien = new PumpLiquidTurret("spraien"){{ requirements(Category.turret, with(Items.lead, 16, RustingItems.taconite, 23, RustingItems.halsinte, 12)); ammo( Liquids.water, Bullets.waterShot, Liquids.slag, Bullets.slagShot, Liquids.cryofluid, Bullets.cryoShot, Liquids.oil, Bullets.oilShot, RustingLiquids.melomae, RustingBullets.melomaeShot, RustingLiquids.cameaint, RustingBullets.cameoShot ); floating = true; size = 1; recoilAmount = 0f; reloadTime = 54f; shots = 5; spread = 2.5f; burstSpacing = 15; inaccuracy = 2f; shootCone = 50f; liquidCapacity = 16f; shootEffect = Fx.shootLiquid; range = 110f; health = 250; flags = EnumSet.of(BlockFlag.turret, BlockFlag.extinguisher); }}; glare = new BerthaTurret("glare"){{ category = Category.turret; shootType = RustingBullets.saltyBolt; buildVisibility = BuildVisibility.sandboxOnly; size = 3; health = 8000; shots = 5; inaccuracy = 0.5f; burstSpacing = 2; range = 1350; restitution = 0.0075f; cooldown = 0.0025f; reloadTime = 420; maxCharge = 3600; xOffset = 4.5f; shellReloadOffset = 2.75f; yOffset = 0.75f; recoilAmount = 5; shellRecoil = 1.5f; shootSound = Sounds.shootBig; heatColor = Color.orange; canOverdrive = false; }}; refract = new ItemTurret("refract"){{ requirements(Category.turret, with(Items.copper, 40, Items.graphite, 17)); ammo( Items.graphite, RustingBullets.denseRoundaboutLight, RustingItems.halsinte, RustingBullets.saltyRoundaboutLight, RustingItems.melonaleum, RustingBullets.craeRoundaboutLight ); health = 340; shots = 3; burstSpacing = 7; reloadTime = 105f; recoilAmount = 1.5f; range = 135f; inaccuracy = 15f; shootCone = 15f; shootSound = Sounds.bang; }}; diffract = new ItemTurret("diffract"){{ requirements(Category.turret, with(Items.copper, 85, Items.lead, 70, Items.graphite, 55)); ammo( Items.graphite, RustingBullets.denseGlaiveHeavy, RustingItems.melonaleum, RustingBullets.craeGlaiveHeavy, RustingItems.halsinte, RustingBullets.saltyGlaiveHeavy ); ammoPerShot = 4; health = 960; size = 2; shots = 1; reloadTime = 120f; recoilAmount = 1.5f; range = 175f; inaccuracy = 0; shootCone = 15f; shootSound = Sounds.bang; }}; reflect = new BoomerangTurret("reflect"){{ requirements(Category.turret, with(Items.copper, 40, Items.graphite, 17)); ammo( Items.graphite, RustingBullets.craeGlaiveLight, RustingItems.halsinte, RustingBullets.saltyRoundaboutLight ); buildVisibility = BuildVisibility.hidden; health = 1460; size = 3; shots = 8; spread = 45; burstSpacing = 7.5f; shootLength = 11; reloadTime = 60f; recoilAmount = 0f; range = 165f; inaccuracy = 0; shootCone = 360f; rotateSpeed = 1; shootSound = Sounds.bang; }}; //endregion //region unit hotSpringSprayer = new HotSpring("hot-spring-sprayer"){{ requirements(Category.units, with(RustingItems.bulastelt, 6, RustingItems.halsinte, 12)); consumes.liquid(Liquids.water, 0.05f); liquidCapacity = 250; healthPerSecond = 35; }}; coldSpringSprayer = new HotSpring("cold-spring-sprayer"){{ requirements(Category.units, with(RustingItems.bulastelt, 6, RustingItems.halsinte, 12)); consumes.liquid(RustingLiquids.melomae, 0.05f); apply = StatusEffects.freezing; liquidCapacity = 250; healthPerSecond = 15; smokeEffect = Fxr.healingColdWaterSmoke; washOff.removeAll(Seq.with(StatusEffects.freezing, RustingStatusEffects.hailsalilty)); washOff.addAll(RustingStatusEffects.macrosis, RustingStatusEffects.macotagus, RustingStatusEffects.balancedPulsation, RustingStatusEffects.causticBurning); }}; fraeFactory = new UnitFactory("frae-factory"){{ requirements(Category.units, with(Items.copper, 75, RustingItems.taconite, 55, RustingItems.bulastelt, 30)); plans = Seq.with( new UnitPlan(RustingUnits.marrow, 2345, with(Items.silicon, 35, Items.copper, 15, RustingItems.taconite, 25)), new UnitPlan(RustingUnits.stingray, 60, with()), new UnitPlan(RustingUnits.kelvin, 60, with()) ); size = 3; consumes.power(0.85f); }}; absentReconstructor = new Reconstructor("absent-reconstructor"){{ requirements(Category.units, with(Items.lead, 465, Items.metaglass, 245, Items.pyratite, 85, Items.titanium, 85)); consumes.items(ItemStack.with(Items.silicon, 65, Items.titanium, 25, Items.pyratite, 5, RustingItems.melonaleum, 15)); size = 3; upgrades.add( new UnitType[]{RustingUnits.marrow, RustingUnits.metaphys} ); constructTime = 854; }}; dwindlingReconstructor = new Reconstructor("dwindling-reconstructor"){{ requirements(Category.units, with(Items.lead, 465, Items.metaglass, 245, Items.pyratite, 85, Items.titanium, 85)); consumes.items(ItemStack.with(Items.silicon, 65, Items.titanium, 25, Items.pyratite, 5, RustingItems.melonaleum, 15)); size = 5; upgrades.add( new UnitType[]{RustingUnits.metaphys, RustingUnits.ribigen} ); constructTime = 1460; }}; pulseDistributor = new PulsePoint("pulse-distributor"){{ requirements(Category.units, with(Items.lead, 465, Items.metaglass, 245, Items.pyratite, 85, Items.titanium, 85)); hideFromUI(); }}; //endregion //region, *sigh* logic mhemLog = new UnbreakableMessageBlock("mhem-log"){{ buildVisibility = BuildVisibility.sandboxOnly; }}; raehLog = new UnbreakableMessageBlock("raeh-log"){{ buildVisibility = BuildVisibility.sandboxOnly; }}; fraeLog = new UnbreakableMessageBlock("frae-log"){{ buildVisibility = BuildVisibility.sandboxOnly; }}; waveAlarm = new WaveAlarm("wave-alarm"){{ }}; halsinteLamp = new LightBlock("halsinte-lamp"){{ requirements(Category.effect, BuildVisibility.lightingOnly, with(Items.metaglass, 5, RustingItems.halsinte, 16, RustingItems.bulastelt, 9)); hasPower = false; brightness = 0.15f; radius = 85; }}; gelBasin = new Block("gel-crucible"){{ }}; //endregion addLiquidAmmoes(Blocks.wave, ObjectMap.of(RustingLiquids.melomae, RustingBullets.melomaeShot, RustingLiquids.cameaint, RustingBullets.cameoShot)); addLiquidAmmo(Blocks.tsunami, RustingLiquids.melomae, RustingBullets.heavyMelomaeShot); addLiquidAmmo(Blocks.tsunami, RustingLiquids.cameaint, RustingBullets.heavyCameoShot); } }
37.923383
206
0.56158
d9a5d92e20628bb9b2d99ff89e3fe4dda83aa9cb
243
package io.meeting.dao; import io.meeting.entity.ConferenceUserEntity; /** * * * @author neckhyg * @email [email protected] * @date 2017-03-02 09:56:17 */ public interface ConferenceUserDao extends BaseDao<ConferenceUserEntity> { }
16.2
74
0.72428
0e53ab88260c111618809bab84a66d27fb01e41b
4,429
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.stats; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpRequestInfo; import java.util.concurrent.ConcurrentHashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; /** * Unit tests for {@link StatsManager}. */ @RunWith(MockitoJUnitRunner.class) public class StatsManagerTest { @Test public void testCollectRouteStats() { String route = "test"; int status = 500; StatsManager sm = StatsManager.getManager(); assertNotNull(sm); // 1st request sm.collectRouteStats(route, status); ConcurrentHashMap<Integer, RouteStatusCodeMonitor> routeStatusMap = sm.routeStatusMap.get("test"); assertNotNull(routeStatusMap); RouteStatusCodeMonitor routeStatusMonitor = routeStatusMap.get(status); // 2nd request sm.collectRouteStats(route, status); } @Test public void testGetRouteStatusCodeMonitor() { StatsManager sm = StatsManager.getManager(); assertNotNull(sm); sm.collectRouteStats("test", 500); assertNotNull(sm.getRouteStatusCodeMonitor("test", 500)); } @Test public void testCollectRequestStats() { final String host = "api.netflix.com"; final String proto = "https"; final HttpRequestInfo req = Mockito.mock(HttpRequestInfo.class); Headers headers = new Headers(); when(req.getHeaders()).thenReturn(headers); headers.set(StatsManager.HOST_HEADER, host); headers.set(StatsManager.X_FORWARDED_PROTO_HEADER, proto); when(req.getClientIp()).thenReturn("127.0.0.1"); final StatsManager sm = StatsManager.getManager(); sm.collectRequestStats(req); final NamedCountingMonitor hostMonitor = sm.getHostMonitor(host); assertNotNull("hostMonitor should not be null", hostMonitor); final NamedCountingMonitor protoMonitor = sm.getProtocolMonitor(proto); assertNotNull("protoMonitor should not be null", protoMonitor); assertEquals(1, hostMonitor.getCount()); assertEquals(1, protoMonitor.getCount()); } @Test public void createsNormalizedHostKey() { assertEquals("host_EC2.amazonaws.com", StatsManager.hostKey("ec2-174-129-179-89.compute-1.amazonaws.com")); assertEquals("host_IP", StatsManager.hostKey("12.345.6.789")); assertEquals("host_IP", StatsManager.hostKey("ip-10-86-83-168")); assertEquals("host_CDN.nflxvideo.net", StatsManager.hostKey("002.ie.llnw.nflxvideo.net")); assertEquals("host_CDN.llnwd.net", StatsManager.hostKey("netflix-635.vo.llnwd.net")); assertEquals("host_CDN.nflximg.com", StatsManager.hostKey("cdn-0.nflximg.com")); } @Test public void extractsClientIpFromXForwardedFor() { final String ip1 = "hi"; final String ip2 = "hey"; assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(ip1)); assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(String.format("%s,%s", ip1, ip2))); assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(String.format("%s, %s", ip1, ip2))); } @Test public void isIPv6() { assertTrue(StatsManager.isIPv6("0:0:0:0:0:0:0:1")); assertTrue(StatsManager.isIPv6("2607:fb10:2:232:72f3:95ff:fe03:a6e7")); assertFalse(StatsManager.isIPv6("127.0.0.1")); assertFalse(StatsManager.isIPv6("10.2.233.134")); } }
36.303279
115
0.69361
654e89853b8620b643f4465636d1b049098ff253
1,007
package top.ljming.javaindepth.designpatterns.geeklesson.observer; import java.util.ArrayList; import java.util.List; /** * 描述类的功能. * * @author ljming */ public class UserRegController { private List<RegObserver> regObserverList = new ArrayList<>(); public void setRegObserverList(List<RegObserver> regObserverList) { this.regObserverList.addAll(regObserverList); } // 同步阻塞的方式 public Long reg(String phone, String pwd) { long userId = 11111; for (RegObserver observer : regObserverList) { observer.handleRegSuccess(userId); } return userId; } public static void main(String[] args) { List<RegObserver> observers = new ArrayList<>(); observers.add(new RegPromotionObserver()); observers.add(new RegNotificationObserver()); UserRegController regController = new UserRegController(); regController.setRegObserverList(observers); regController.reg("111", "11"); } }
25.175
71
0.672294
f019e6023d0447e1e0fe92454fb736659c631f5e
1,806
package com.plus.mevanspn.BBCSoundEditor; import com.plus.mevanspn.BBCSoundEditor.WaveFile.*; import com.plus.mevanspn.BBCSoundEditor.WaveFile.Exceptions.InvalidPCMSampleException; import com.plus.mevanspn.BBCSoundEditor.WaveFile.Exceptions.InvalidPCMSampleSizeException; import com.plus.mevanspn.BBCSoundEditor.WaveFile.Exceptions.InvalidSoundChannelException; import java.io.IOException; public class Main { public static void main(String[] args) { try { WaveFile waveFile = new WaveFile(1, 8000, 16); SoundChannel soundChannel = waveFile.GetChannel(0); final double sineLength = 0.008, volume = 50; final int sineWaveSamplesLength = (int) (sineLength * waveFile.GetSampleRate()); final int sampleLengthInSeconds = 5, totalSamples = sampleLengthInSeconds * waveFile.GetSampleRate(); double waveInc = Math.PI * 2 / sineWaveSamplesLength; int i = 0; while (i < totalSamples) { double waveValue = 0; for (int j = 0; i < totalSamples && j < sineWaveSamplesLength; j++) { int sampleValue = (int) (32767 * (volume / 100.0) * Math.sin(waveValue)); soundChannel.AddSample(sampleValue); waveValue += waveInc; i++; } } waveFile.ToFile("test.wav"); } catch (InvalidPCMSampleSizeException issex) { issex.printStackTrace(); } catch (InvalidSoundChannelException iccex) { iccex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } catch (InvalidPCMSampleException isex) { isex.printStackTrace(); } } }
44.04878
114
0.608527
25168d75e74b198363bf20feab030a8d16925c2f
3,355
package example; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class ReadWriteLockExample { public static void main(final String[] args) throws Exception { final ReadWriteLock rwl = new ReentrantReadWriteLock(); final int size = 3; final ExecutorService executor = Executors.newFixedThreadPool(size); try { final ReadWriteLockExample obj = new ReadWriteLockExample(rwl, size, executor); obj.example1(); obj.example2(); } finally { executor.shutdown(); } } private final ReadWriteLock rwl; private final int size; private final ExecutorService executor; private ReadWriteLockExample(final ReadWriteLock rwl, final int size, final ExecutorService executor) { this.rwl = rwl; this.size = size; this.executor = executor; } private void example1() throws Exception { System.out.println("**** example 1 ****"); final CountDownLatch ready = new CountDownLatch(size); final CountDownLatch go = new CountDownLatch(1); final Callable<Void> task = () -> { ready.countDown(); go.await(); final Lock lock = rwl.readLock(); lock.lock(); try { System.out.printf("begin: %s%n", Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(1); System.out.printf("end: %s%n", Thread.currentThread().getName()); } finally { lock.unlock(); } return null; }; final List<Future<Void>> fetures = IntStream.range(0, size) .mapToObj(i -> executor.submit(task)) .collect(Collectors.toList()); ready.await(); go.countDown(); for (final Future<Void> future : fetures) { future.get(); } } private void example2() throws Exception { System.out.println("**** example 2 ****"); final CountDownLatch ready = new CountDownLatch(size); final CountDownLatch go = new CountDownLatch(1); final Callable<Void> readTask = () -> { ready.countDown(); go.await(); TimeUnit.SECONDS.sleep(1); final Lock lock = rwl.readLock(); lock.lock(); try { System.out.printf("[r]begin: %s%n", Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(1); System.out.printf("[r]end: %s%n", Thread.currentThread().getName()); } finally { lock.unlock(); } return null; }; final Callable<Void> writeTask = () -> { ready.countDown(); go.await(); final Lock lock = rwl.writeLock(); lock.lock(); try { System.out.printf("[w]begin: %s%n", Thread.currentThread().getName()); TimeUnit.SECONDS.sleep(3); System.out.printf("[w]end: %s%n", Thread.currentThread().getName()); } finally { lock.unlock(); } return null; }; final List<Future<Void>> fetures = Stream.concat( IntStream.range(0, size - 1).mapToObj(i -> executor.submit(readTask)), Stream.of(executor.submit(writeTask))) .collect(Collectors.toList()); ready.await(); go.countDown(); for (final Future<Void> future : fetures) { future.get(); } } }
28.432203
82
0.687928
1a15e4afe51e0e66ffa31fc0438810b9a96a875c
1,235
package kotlin.sequences; import java.util.Iterator; import kotlin.jvm.internal.markers.KMappedMarker; import org.jetbrains.annotations.NotNull; public final class MergingSequence$iterator$1 implements Iterator<V>, KMappedMarker { @NotNull private final Iterator<T1> iterator1; @NotNull private final Iterator<T2> iterator2; final /* synthetic */ MergingSequence this$0; public void remove() { throw new UnsupportedOperationException("Operation is not supported for read-only collection"); } MergingSequence$iterator$1(MergingSequence mergingSequence) { this.this$0 = mergingSequence; this.iterator1 = mergingSequence.sequence1.iterator(); this.iterator2 = mergingSequence.sequence2.iterator(); } @NotNull public final Iterator<T1> getIterator1() { return this.iterator1; } @NotNull public final Iterator<T2> getIterator2() { return this.iterator2; } public V next() { return this.this$0.transform.invoke(this.iterator1.next(), this.iterator2.next()); } public boolean hasNext() { return this.iterator1.hasNext() && this.iterator2.hasNext(); } }
29.404762
104
0.671255
dd1fe8ffcba49ffcf9f9b9415c124cb35c43e0d7
3,675
/**************************************************************** * 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.james.transport.mailets.redirect; import org.apache.james.core.Domain; import org.apache.james.core.MailAddress; public class SpecialAddress { public static final MailAddress SENDER = AddressMarker.SENDER; public static final MailAddress REVERSE_PATH = AddressMarker.REVERSE_PATH; public static final MailAddress FROM = AddressMarker.FROM; public static final MailAddress REPLY_TO = AddressMarker.REPLY_TO; public static final MailAddress TO = AddressMarker.TO; public static final MailAddress RECIPIENTS = AddressMarker.RECIPIENTS; public static final MailAddress DELETE = AddressMarker.DELETE; public static final MailAddress UNALTERED = AddressMarker.UNALTERED; public static final MailAddress NULL = AddressMarker.NULL; public static class AddressMarker { public static final Domain ADDRESS_MARKER = Domain.of("address.marker"); public static final MailAddress SENDER = mailAddressUncheckedException(SpecialAddressKind.SENDER, ADDRESS_MARKER); public static final MailAddress REVERSE_PATH = mailAddressUncheckedException(SpecialAddressKind.REVERSE_PATH, ADDRESS_MARKER); public static final MailAddress FROM = mailAddressUncheckedException(SpecialAddressKind.FROM, ADDRESS_MARKER); public static final MailAddress REPLY_TO = mailAddressUncheckedException(SpecialAddressKind.REPLY_TO, ADDRESS_MARKER); public static final MailAddress TO = mailAddressUncheckedException(SpecialAddressKind.TO, ADDRESS_MARKER); public static final MailAddress RECIPIENTS = mailAddressUncheckedException(SpecialAddressKind.RECIPIENTS, ADDRESS_MARKER); public static final MailAddress DELETE = mailAddressUncheckedException(SpecialAddressKind.DELETE, ADDRESS_MARKER); public static final MailAddress UNALTERED = mailAddressUncheckedException(SpecialAddressKind.UNALTERED, ADDRESS_MARKER); public static final MailAddress NULL = mailAddressUncheckedException(SpecialAddressKind.NULL, ADDRESS_MARKER); private static MailAddress mailAddressUncheckedException(SpecialAddressKind kind, Domain domain) { try { return new MailAddress(kind.getValue(), domain); } catch (Exception e) { throw new RuntimeException(e); } } } public static boolean isSpecialAddress(MailAddress mailAddress) { return mailAddress.getDomain().equals(AddressMarker.ADDRESS_MARKER); } }
59.274194
134
0.687891
ee9ba6e62101c82dc2bde985fa26bb3729c20ecf
1,753
/* * Copyright © 2014 - 2018 Leipzig University (Database Research Group) * * 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.gradoop.flink.model.impl.operators.grouping.functions; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.functions.FunctionAnnotation; import org.gradoop.flink.model.impl.operators.grouping.tuples.VertexWithSuperVertex; import org.gradoop.flink.model.impl.operators.grouping.tuples.VertexGroupItem; /** * Maps a {@link VertexGroupItem} to a {@link VertexWithSuperVertex}. */ @FunctionAnnotation.ForwardedFields( "f0;" + // vertex id "f1" // super vertex id ) public class BuildVertexWithSuperVertex implements MapFunction<VertexGroupItem, VertexWithSuperVertex> { /** * Avoid object instantiation. */ private final VertexWithSuperVertex reuseTuple; /** * Creates mapper. */ public BuildVertexWithSuperVertex() { this.reuseTuple = new VertexWithSuperVertex(); } @Override public VertexWithSuperVertex map(VertexGroupItem vertexGroupItem) throws Exception { reuseTuple.setVertexId(vertexGroupItem.getVertexId()); reuseTuple.setSuperVertexId(vertexGroupItem.getSuperVertexId()); return reuseTuple; } }
33.075472
84
0.758699
fb715bd3c89245fa3e7a61df64a6d1db434d2c20
2,094
package crc6406d57bc67a4dd4fc; public class CameraPreview_DetectorProcessor extends java.lang.Object implements mono.android.IGCUserPeer, com.google.android.gms.vision.Detector.Processor { /** @hide */ public static final String __md_methods; static { __md_methods = "n_receiveDetections:(Lcom/google/android/gms/vision/Detector$Detections;)V:GetReceiveDetections_Lcom_google_android_gms_vision_Detector_Detections_Handler:Android.Gms.Vision.Detector/IProcessorInvoker, Xamarin.GooglePlayServices.Vision.Common\n" + "n_release:()V:GetReleaseHandler:Android.Gms.Vision.Detector/IProcessorInvoker, Xamarin.GooglePlayServices.Vision.Common\n" + ""; mono.android.Runtime.register ("GoogleVisionBarCodeScanner.CameraPreview+DetectorProcessor, BarcodeScanner.XF", CameraPreview_DetectorProcessor.class, __md_methods); } public CameraPreview_DetectorProcessor () { super (); if (getClass () == CameraPreview_DetectorProcessor.class) mono.android.TypeManager.Activate ("GoogleVisionBarCodeScanner.CameraPreview+DetectorProcessor, BarcodeScanner.XF", "", this, new java.lang.Object[] { }); } public CameraPreview_DetectorProcessor (android.content.Context p0, boolean p1) { super (); if (getClass () == CameraPreview_DetectorProcessor.class) mono.android.TypeManager.Activate ("GoogleVisionBarCodeScanner.CameraPreview+DetectorProcessor, BarcodeScanner.XF", "Android.Content.Context, Mono.Android:System.Boolean, mscorlib", this, new java.lang.Object[] { p0, p1 }); } public void receiveDetections (com.google.android.gms.vision.Detector.Detections p0) { n_receiveDetections (p0); } private native void n_receiveDetections (com.google.android.gms.vision.Detector.Detections p0); public void release () { n_release (); } private native void n_release (); private java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
32.215385
251
0.775549
af0351f9d192e34dcbe6f5b2813eac910f94c27e
2,347
package com.lcj.mutichannel.Netty; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import lombok.extern.slf4j.Slf4j; /** * @author zhanghaoyan.zhy * @date 2021/6/23 */ @Slf4j public class TcpDataClient { private static final String HOST = "127.0.0.1"; private static final int PORT= 23333; public static void main(String[] args){ new TcpDataClient().start(HOST, PORT); } public void start(String host, int port) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap client = new Bootstrap().group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new HelloWorldClientHandler()); } }); ChannelFuture future = client.connect(host, port).sync(); log.debug("client start"); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } public static class HelloWorldClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { int cnt = 0; // byte[] bytes = {1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8}; byte[] bytes = {1, 2}; while (true) { bytes[0]++; bytes[0] %= 127; ctx.writeAndFlush(Unpooled.wrappedBuffer(bytes)); Thread.sleep(1); cnt++; if(cnt > 0) break; } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("HelloWorldClientHandler read Message:ff"+ msg.toString()); } } }
31.716216
110
0.567959
f4a4a9bf96d70a8a42c6fa4723ee4b1fc28ce7f0
872
package senntyou.webmonitor.mbg.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import senntyou.webmonitor.mbg.model.JsError; import senntyou.webmonitor.mbg.model.JsErrorExample; public interface JsErrorMapper { long countByExample(JsErrorExample example); int deleteByExample(JsErrorExample example); int deleteByPrimaryKey(Integer id); int insert(JsError record); int insertSelective(JsError record); List<JsError> selectByExample(JsErrorExample example); JsError selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") JsError record, @Param("example") JsErrorExample example); int updateByExample(@Param("record") JsError record, @Param("example") JsErrorExample example); int updateByPrimaryKeySelective(JsError record); int updateByPrimaryKey(JsError record); }
29.066667
108
0.779817
87ff21b2cac5c813ea367898e1dc520b3df040c9
2,892
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.forms.editor.client.editor.properties.util; import java.util.List; import java.util.stream.Collectors; import org.jboss.errai.databinding.client.BindableProxy; import org.jboss.errai.databinding.client.BindableProxyFactory; import org.jboss.errai.databinding.client.PropertyType; public class DeepCloneHelper { public static <T> T deepClone(T instance) { if(instance == null) { return null; } return doDeepClone(instance).deepUnwrap(); } private static <T> BindableProxy<T> doDeepClone(T instance) { final BindableProxy<T> proxy; if(instance instanceof BindableProxy) { proxy = (BindableProxy<T>) instance; } else { proxy = (BindableProxy<T>) BindableProxyFactory.getBindableProxy(instance); } if(proxy != null) { proxy.getBeanProperties() .entrySet() .stream() .filter(entry -> isProxy(entry.getValue().getType())) .forEach(entry -> deepCloneProxyProperty(proxy, entry.getKey(), entry.getValue())); } return proxy; } private static <T> void deepCloneProxyProperty(BindableProxy<T> proxy, String propertyName, PropertyType type) { Object value = proxy.get(propertyName); if(type.isList() && value != null) { value = doDeepCloneList((List)value); } else { value = doDeepClone(value); } proxy.set(propertyName, value); } protected static <T> List<Object> doDeepCloneList(List<T> values) { return values.stream() .map(DeepCloneHelper::doDeepCloneListValue) .collect(Collectors.toList()); } private static <T> Object doDeepCloneListValue(T instance) { if (isProxy(instance.getClass())) { return doDeepClone(instance); } return instance; } private static boolean isProxy(Class clazz) { try { if(BindableProxyFactory.getBindableProxy(clazz) != null) { return true; } } catch (Exception ex) { // Non proxyable class. } return false; } }
31.096774
116
0.624481
2f797e361a2713b8142154658294203c12e1591b
20,096
/* * Copyright (C) 2010, Christian Halstrick <[email protected]>, * Copyright (C) 2010, Philipp Thun <[email protected]> * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - 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. * * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 org.eclipse.jgit.treewalk.filter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.dircache.DirCacheIterator; import org.eclipse.jgit.junit.RepositoryTestCase; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.treewalk.FileTreeIterator; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.util.FileUtils; import org.junit.Before; import org.junit.Test; public class IndexDiffFilterTest extends RepositoryTestCase { private static final String FILE = "file"; private static final String UNTRACKED_FILE = "untracked_file"; private static final String IGNORED_FILE = "ignored_file"; private static final String FILE_IN_FOLDER = "folder/file"; private static final String UNTRACKED_FILE_IN_FOLDER = "folder/untracked_file"; private static final String IGNORED_FILE_IN_FOLDER = "folder/ignored_file"; private static final String FILE_IN_IGNORED_FOLDER = "ignored_folder/file"; private static final String FOLDER = "folder"; private static final String UNTRACKED_FOLDER = "untracked_folder"; private static final String IGNORED_FOLDER = "ignored_folder"; private static final String GITIGNORE = ".gitignore"; private static final String FILE_CONTENT = "content"; private static final String MODIFIED_FILE_CONTENT = "modified_content"; private Git git; @Override @Before public void setUp() throws Exception { super.setUp(); git = new Git(db); } @Test public void testRecursiveTreeWalk() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteAll(); writeFileWithFolderName(); TreeWalk treeWalk = createTreeWalk(commit); assertTrue(treeWalk.next()); assertEquals("folder", treeWalk.getPathString()); assertTrue(treeWalk.next()); assertEquals("folder/file", treeWalk.getPathString()); assertFalse(treeWalk.next()); } @Test public void testNonRecursiveTreeWalk() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteAll(); writeFileWithFolderName(); TreeWalk treeWalk = createNonRecursiveTreeWalk(commit); assertTrue(treeWalk.next()); assertEquals("folder", treeWalk.getPathString()); assertTrue(treeWalk.next()); assertEquals("folder", treeWalk.getPathString()); assertTrue(treeWalk.isSubtree()); treeWalk.enterSubtree(); assertTrue(treeWalk.next()); assertEquals("folder/file", treeWalk.getPathString()); assertFalse(treeWalk.next()); } @Test public void testFileCommitted() throws Exception { RevCommit commit = writeFileAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testConflicts() throws Exception { RevCommit initial = git.commit().setMessage("initial").call(); writeTrashFile(FILE, "master"); git.add().addFilepattern(FILE).call(); RevCommit master = git.commit().setMessage("master").call(); git.checkout().setName("refs/heads/side") .setCreateBranch(true).setStartPoint(initial).call(); writeTrashFile(FILE, "side"); git.add().addFilepattern(FILE).call(); RevCommit side = git.commit().setMessage("side").call(); assertFalse(git.merge().include("master", master).call() .getMergeStatus() .isSuccessful()); assertEquals(read(FILE), "<<<<<<< HEAD\nside\n=======\nmaster\n>>>>>>> master\n"); writeTrashFile(FILE, "master"); TreeWalk treeWalk = createTreeWalk(side); int count = 0; while (treeWalk.next()) count++; assertEquals(2, count); } @Test public void testFileInFolderCommitted() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testEmptyFolderCommitted() throws Exception { RevCommit commit = createEmptyFolderAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileCommittedChangedNotModified() throws Exception { RevCommit commit = writeFileAndCommit(); writeFile(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileInFolderCommittedChangedNotModified() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolder(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileCommittedModified() throws Exception { RevCommit commit = writeFileAndCommit(); writeFileModified(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE); } @Test public void testFileInFolderCommittedModified() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolderModified(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testFileCommittedDeleted() throws Exception { RevCommit commit = writeFileAndCommit(); deleteFile(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE); } @Test public void testFileInFolderCommittedDeleted() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteFileInFolder(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testFileInFolderCommittedAllDeleted() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteAll(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testEmptyFolderCommittedDeleted() throws Exception { RevCommit commit = createEmptyFolderAndCommit(); deleteFolder(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileCommittedModifiedCommittedComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileAndCommit(); writeFileModifiedAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE); } @Test public void testFileInFolderCommittedModifiedCommittedComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolderModifiedAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testFileCommittedDeletedCommittedComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileAndCommit(); deleteFileAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE); } @Test public void testFileInFolderCommittedDeletedCommittedComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteFileInFolderAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testFileInFolderCommittedAllDeletedCommittedComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteAllAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testEmptyFolderCommittedDeletedCommittedComparedWithInitialCommit() throws Exception { RevCommit commit = createEmptyFolderAndCommit(); deleteFolderAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileUntracked() throws Exception { RevCommit commit = writeFileAndCommit(); writeFileUntracked(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, UNTRACKED_FILE); } @Test public void testFileInFolderUntracked() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolderUntracked(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, UNTRACKED_FILE_IN_FOLDER); } @Test public void testEmptyFolderUntracked() throws Exception { RevCommit commit = createEmptyFolderAndCommit(); createEmptyFolderUntracked(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileIgnored() throws Exception { RevCommit commit = writeFileAndCommit(); writeFileIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileInFolderIgnored() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolderIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileInFolderAllIgnored() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolderAllIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testEmptyFolderIgnored() throws Exception { RevCommit commit = createEmptyFolderAndCommit(); createEmptyFolderIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileIgnoredNotHonored() throws Exception { RevCommit commit = writeFileAndCommit(); writeFileIgnored(); TreeWalk treeWalk = createTreeWalkDishonorIgnores(commit); assertPaths(treeWalk, IGNORED_FILE, GITIGNORE); } @Test public void testFileCommittedModifiedIgnored() throws Exception { RevCommit commit = writeFileAndCommit(); writeFileModifiedIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE); } @Test public void testFileInFolderCommittedModifiedIgnored() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolderModifiedIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testFileInFolderCommittedModifiedAllIgnored() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); writeFileInFolderModifiedAllIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testFileCommittedDeletedCommittedIgnoredComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileAndCommit(); deleteFileAndCommit(); rewriteFileIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE); } @Test public void testFileInFolderCommittedDeletedCommittedIgnoredComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteFileInFolderAndCommit(); rewriteFileInFolderIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testFileInFolderCommittedAllDeletedCommittedAllIgnoredComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteAllAndCommit(); rewriteFileInFolderAllIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FILE_IN_FOLDER); } @Test public void testEmptyFolderCommittedDeletedCommittedIgnoredComparedWithInitialCommit() throws Exception { RevCommit commit = createEmptyFolderAndCommit(); deleteFolderAndCommit(); recreateEmptyFolderIgnored(); TreeWalk treeWalk = createTreeWalk(commit); assertFalse(treeWalk.next()); } @Test public void testFileInFolderCommittedNonRecursive() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); TreeWalk treeWalk = createNonRecursiveTreeWalk(commit); assertPaths(treeWalk, FOLDER); } @Test public void testFolderChangedToFile() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteAll(); writeFileWithFolderName(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FOLDER, FILE_IN_FOLDER); } @Test public void testFolderChangedToFileCommittedComparedWithInitialCommit() throws Exception { RevCommit commit = writeFileInFolderAndCommit(); deleteAll(); writeFileWithFolderNameAndCommit(); TreeWalk treeWalk = createTreeWalk(commit); assertPaths(treeWalk, FOLDER, FILE_IN_FOLDER); } private void writeFile() throws Exception { writeTrashFile(FILE, FILE_CONTENT); } private RevCommit writeFileAndCommit() throws Exception { writeFile(); return commitAdd(); } private void writeFileModified() throws Exception { writeTrashFile(FILE, MODIFIED_FILE_CONTENT); } private void writeFileModifiedAndCommit() throws Exception { writeFileModified(); commitAdd(); } private void writeFileUntracked() throws Exception { writeTrashFile(UNTRACKED_FILE, FILE_CONTENT); } private void writeFileIgnored() throws Exception { writeTrashFile(IGNORED_FILE, FILE_CONTENT); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + IGNORED_FILE); } private void writeFileModifiedIgnored() throws Exception { writeFileModified(); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + FILE); } private void rewriteFileIgnored() throws Exception { writeFile(); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + FILE); } private void writeFileWithFolderName() throws Exception { writeTrashFile(FOLDER, FILE_CONTENT); } private void writeFileWithFolderNameAndCommit() throws Exception { writeFileWithFolderName(); commitAdd(); } private void deleteFile() throws Exception { deleteTrashFile(FILE); } private void deleteFileAndCommit() throws Exception { deleteFile(); commitRm(FILE); } private void writeFileInFolder() throws Exception { writeTrashFile(FILE_IN_FOLDER, FILE_CONTENT); } private RevCommit writeFileInFolderAndCommit() throws Exception { writeFileInFolder(); return commitAdd(); } private void writeFileInFolderModified() throws Exception { writeTrashFile(FILE_IN_FOLDER, MODIFIED_FILE_CONTENT); } private void writeFileInFolderModifiedAndCommit() throws Exception { writeFileInFolderModified(); commitAdd(); } private void writeFileInFolderUntracked() throws Exception { writeTrashFile(UNTRACKED_FILE_IN_FOLDER, FILE_CONTENT); } private void writeFileInFolderIgnored() throws Exception { writeTrashFile(IGNORED_FILE_IN_FOLDER, FILE_CONTENT); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + IGNORED_FILE_IN_FOLDER); } private void writeFileInFolderAllIgnored() throws Exception { writeTrashFile(FILE_IN_IGNORED_FOLDER, FILE_CONTENT); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + IGNORED_FOLDER + "/"); } private void writeFileInFolderModifiedIgnored() throws Exception { writeFileInFolderModified(); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + FILE_IN_FOLDER); } private void rewriteFileInFolderIgnored() throws Exception { writeFileInFolder(); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + FILE_IN_FOLDER); } private void writeFileInFolderModifiedAllIgnored() throws Exception { writeFileInFolderModified(); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + FOLDER + "/"); } private void rewriteFileInFolderAllIgnored() throws Exception { writeFileInFolder(); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + FOLDER + "/"); } private void deleteFileInFolder() throws Exception { deleteTrashFile(FILE_IN_FOLDER); } private void deleteFileInFolderAndCommit() throws Exception { deleteFileInFolder(); commitRm(FILE_IN_FOLDER); } private void createEmptyFolder() throws Exception { File path = new File(db.getWorkTree(), FOLDER); FileUtils.mkdir(path); } private RevCommit createEmptyFolderAndCommit() throws Exception { createEmptyFolder(); return commitAdd(); } private void createEmptyFolderUntracked() throws Exception { File path = new File(db.getWorkTree(), UNTRACKED_FOLDER); FileUtils.mkdir(path); } private void createEmptyFolderIgnored() throws Exception { File path = new File(db.getWorkTree(), IGNORED_FOLDER); FileUtils.mkdir(path); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + IGNORED_FOLDER + "/"); } private void recreateEmptyFolderIgnored() throws Exception { createEmptyFolder(); writeTrashFile(GITIGNORE, GITIGNORE + "\n" + FOLDER + "/"); } private void deleteFolder() throws Exception { deleteTrashFile(FOLDER); } private void deleteFolderAndCommit() throws Exception { deleteFolder(); commitRm(FOLDER); } private void deleteAll() throws Exception { deleteFileInFolder(); deleteFolder(); } private void deleteAllAndCommit() throws Exception { deleteFileInFolderAndCommit(); deleteFolderAndCommit(); } private RevCommit commitAdd() throws Exception { git.add().addFilepattern(".").call(); return git.commit().setMessage("commit").call(); } private RevCommit commitRm(String path) throws Exception { git.rm().addFilepattern(path).call(); return git.commit().setMessage("commit").call(); } private TreeWalk createTreeWalk(RevCommit commit) throws Exception { return createTreeWalk(commit, true, true); } private TreeWalk createTreeWalkDishonorIgnores(RevCommit commit) throws Exception { return createTreeWalk(commit, true, false); } private TreeWalk createNonRecursiveTreeWalk(RevCommit commit) throws Exception { return createTreeWalk(commit, false, true); } private TreeWalk createTreeWalk(RevCommit commit, boolean isRecursive, boolean honorIgnores) throws Exception { TreeWalk treeWalk = new TreeWalk(db); treeWalk.setRecursive(isRecursive); treeWalk.addTree(commit.getTree()); treeWalk.addTree(new DirCacheIterator(db.readDirCache())); treeWalk.addTree(new FileTreeIterator(db)); if (!honorIgnores) treeWalk.setFilter(new IndexDiffFilter(1, 2, honorIgnores)); else treeWalk.setFilter(new IndexDiffFilter(1, 2)); return treeWalk; } private static void assertPaths(TreeWalk treeWalk, String... paths) throws Exception { for (int i = 0; i < paths.length; i++) { assertTrue(treeWalk.next()); assertPath(treeWalk.getPathString(), paths); } assertFalse(treeWalk.next()); } private static void assertPath(String path, String... paths) { for (String p : paths) if (p.equals(path)) return; fail("Expected path '" + path + "' is not returned"); } }
30.26506
94
0.767466
ff2ae71b8c6bbf84c5b082366dc89184a9344e24
446
package org.ethereum.net.submit; import org.ethereum.core.Transaction; /** * @author Roman Mandeleil * Created on: 23/05/2014 18:41 */ public class WalletTransaction { private Transaction tx; int approved = 0; // each time the tx got from the wire this value increased public WalletTransaction(Transaction tx) { this.tx = tx; } public void incApproved() { ++this.approved; } public int getApproved() { return approved; } }
17.153846
77
0.70852
ee52e64d76c6ca39af974c8ac654e492d53ed138
966
package mekanism.client.render.entity; import mekanism.client.model.ModelRobit; import mekanism.common.entity.Robit; import mekanism.common.util.MekanismUtils; import mekanism.common.util.MekanismUtils.ResourceType; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderRobit extends RenderLiving { public RenderRobit() { super(new ModelRobit(), 0.5F); } @Override protected ResourceLocation getEntityTexture(Entity entity) { Robit robit = (Robit)entity; if((Math.abs(entity.posX-entity.prevPosX) + Math.abs(entity.posX-entity.prevPosX)) > 0.001) { if(robit.ticksExisted % 3 == 0) { robit.texTick = !robit.texTick; } } return MekanismUtils.getResource(ResourceType.RENDER, "Robit" + (robit.texTick ? "2" : "") + ".png"); } }
26.108108
103
0.753623
b6d4ddf0f2b0a4ea1ee513b7f304d168a74033c7
1,210
import tfc.lang.Executor; import tfc.lang.LangClass; public class Benchmarking { public static void main(String[] args) { { long avgTime = 0; for (int i = 0; i < 25600; i++) { long timens = System.nanoTime(); method(); avgTime += System.nanoTime() - timens; avgTime /= 2; } System.out.println(avgTime); } { long avgTime = 0; Executor executor = new Executor(255); executor.classPath = "test/out/"; // tfc.lang.LangClass clazz; // { // byte[] bytes; // { // FileInputStream stream = new FileInputStream("test/out/Test2.langclass"); // bytes = new byte[stream.available()]; // stream.read(bytes); // stream.close(); // } // clazz = new tfc.lang.LangClass(bytes); // } LangClass clazz = executor.load("Test2"); for (int i = 0; i < 25600; i++) { long timens = System.nanoTime(); clazz.runMethod("method", "()I"); avgTime += System.nanoTime() - timens; avgTime /= 2; } System.out.println(avgTime); } } @SuppressWarnings("UnusedReturnValue") private static int method() { int i = 0; i += 5; i += 64; i += 32; i += 12; i += 16; i += 64; i += 923; i += 203; i += 22; return i; } }
21.22807
80
0.572727
a857dc6675abb6f19176b564afeadd11ba3527fd
1,149
package com.ociweb.iot.examples; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.gl.api.PubSubService; import com.ociweb.iot.maker.AnalogListener; import com.ociweb.iot.maker.FogRuntime; import com.ociweb.iot.maker.Port; public class ModeSelector implements AnalogListener { private final PubSubService commandChannel; private final Logger logger = LoggerFactory.getLogger(ModeSelector.class); private int angleDivisor; private long lastChange; //used to keep user from toggling between states quickly public ModeSelector(FogRuntime runtime, int angleRange) { this.commandChannel = runtime.newCommandChannel().newPubSubService(); this.angleDivisor = 1+((angleRange-1)/PumpState.values().length); //rounds up so 1023 does not produce a new state } @Override public void analogEvent(Port port, long time, long durationMillis, int average, int value) { if ((time-lastChange)>200) { int pumpStateIndex = value/angleDivisor; PumpState state = PumpState.values()[pumpStateIndex]; logger.info("changed mode to {}",state); commandChannel.changeStateTo(state); lastChange = time; } } }
31.054054
116
0.770235
4f747327781f9a1fb9e09fe9e26575375cbe6ba3
883
package com.solvd.shop24.gui.common.pages.purchase; import com.solvd.shop24.gui.common.components.MenuItem; import com.solvd.shop24.gui.common.components.purchase.BasketItemBase; import com.solvd.shop24.gui.common.pages.HomePageBase; import com.solvd.shop24.gui.common.components.purchase.BasketItem; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.FindBy; import java.util.List; public abstract class BasketPageBase extends HomePageBase { @FindBy(className = "page-nav") private MenuItem menu; @FindBy(xpath = "//div[@class='basket-items']//div[@class='basket-block-main']") private List<? extends BasketItemBase> products; public BasketPageBase(WebDriver driver) { super(driver); setPageURL("/personal/basket.php"); } public List<? extends BasketItemBase> getProducts() { return products; } }
30.448276
84
0.741789
6ff87911a10ecd1c70dc7ad09696621533586d9e
5,487
// // RemoteLoggerRecord.java // Open XAL // // Created by Pelaia II, Tom on 9/28/12 // Copyright 2012 Oak Ridge National Lab. All rights reserved. // package xal.app.pvlogger; import java.util.concurrent.Callable; import java.util.*; import xal.tools.UpdateListener; import xal.extension.service.*; import xal.tools.dispatch.DispatchQueue; import xal.service.pvlogger.RemoteLogging; /** RemoteLoggerRecord */ public class RemoteLoggerRecord implements UpdateListener { /** remote proxy */ private final RemoteLogging REMOTE_PROXY; /** cache for the host name */ private final RemoteDataCache<String> HOST_NAME_CACHE; /** cache for the launch time */ private final RemoteDataCache<Date> LAUNCH_TIME_CACHE; /** cache for the remote service heartbeat */ private final RemoteDataCache<Date> HEARTBEAT_CACHE; /** host address of the remote service */ private final String REMOTE_ADDRESS; /** list of group types */ private final List<String> GROUP_TYPES; /** logger sessions keyed by group type */ private final Map<String,LoggerSessionHandler> LOGGER_SESSIONS; /** optional handler of the update event */ private UpdateListener _updateListener; /** Constructor */ public RemoteLoggerRecord( final RemoteLogging proxy ) { REMOTE_PROXY = proxy; REMOTE_ADDRESS = ((ServiceState)proxy).getServiceHost(); // don't need to keep making remote requests for host name as it won't change HOST_NAME_CACHE = createRemoteOperationCache( new Callable<String>() { public String call() { return REMOTE_PROXY.getHostName(); } }); // don't need to keep making remote requests for launch time as it won't change LAUNCH_TIME_CACHE = createRemoteOperationCache( new Callable<Date>() { public Date call() { return REMOTE_PROXY.getLaunchTime(); } }); // insulate this call from hangs of the remote application HEARTBEAT_CACHE = createRemoteOperationCache( new Callable<Date>() { public Date call() { return REMOTE_PROXY.getHeartbeat(); } }); GROUP_TYPES = REMOTE_PROXY.getGroupTypes(); LOGGER_SESSIONS = new HashMap<String,LoggerSessionHandler>(); for ( final String groupType : GROUP_TYPES ) { LOGGER_SESSIONS.put( groupType, new LoggerSessionHandler( groupType, REMOTE_PROXY ) ); } // observe updates from the caches HOST_NAME_CACHE.setUpdateListener( this ); LAUNCH_TIME_CACHE.setUpdateListener( this ); HEARTBEAT_CACHE.setUpdateListener( this ); } /** Create a remote operation cache for the given operation */ static private <DataType> RemoteDataCache<DataType> createRemoteOperationCache( final Callable<DataType> operation ) { return new RemoteDataCache<DataType>( operation ); } /** set the update handler which is called when the cache has been updated */ public void setUpdateListener( final UpdateListener handler ) { _updateListener = handler; } /** get the update handler */ public UpdateListener getUpdateListener() { return _updateListener; } /** called when the source posts an update to this observer */ public void observedUpdate( final Object source ) { // propagate update notification to the update listener if any final UpdateListener updateHandler = _updateListener; if ( updateHandler != null ) { updateHandler.observedUpdate( this ); } } /** refresh the record */ public void refresh() { HEARTBEAT_CACHE.refresh(); } /** * Get the group types that are being logged. Each type has an associated PVLogger session. * @return the list of pvlogger groups */ public List<String> getGroupTypes() { return GROUP_TYPES; } /** * Get a logger session by group type * @param groupType the type of group for which to get the logger session * @return the named logger session */ public LoggerSessionHandler getLoggerSession( final String groupType ) { return LOGGER_SESSIONS.get( groupType ); } /** * Get the name of the host where the application is running. * @return The name of the host where the application is running. */ public String getHostName() { final String hostName = HOST_NAME_CACHE.getValue(); return hostName != null ? hostName : REMOTE_ADDRESS; // if we can't get the host name from the remote service something went wrong and just return the remote address so we have some information } /** * Get the launch time of the application * @return the time at with the application was launched */ public Date getLaunchTime() { return LAUNCH_TIME_CACHE.getValue(); } /** * Get the heartbeat from the service * @return the time at with the application was launched in seconds since the epoch */ public Date getHeartbeat() { return HEARTBEAT_CACHE.getValue(); } /** Determine whether this record is believed to be connected but don't test */ public boolean isConnected() { return HEARTBEAT_CACHE.isConnected(); } /** Publish snapshots. */ public void publishSnapshots() { REMOTE_PROXY.publishSnapshots(); } /** Stop logging, reload groups from the database and resume logging. */ public void restartLogger() { REMOTE_PROXY.restartLogger(); } /** Resume the logger logging. */ public void resumeLogging() { REMOTE_PROXY.resumeLogging(); } /** Stop the logger. */ public void stopLogging() { REMOTE_PROXY.stopLogging(); } /** * Shutdown the process without waiting for a response. * @param code The shutdown code which is normally just 0. */ public void shutdown( int code ) { REMOTE_PROXY.shutdown( code ); } }
26.635922
195
0.728996
e7bd3a3ea4abc4e214a4be8b5146b49cfd208a10
665
// VeriBlock Blockchain Project // Copyright 2017-2018 VeriBlock, Inc // Copyright 2018-2020 Xenios SEZC // All rights reserved. // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. package veriblock.model; import org.veriblock.core.bitcoinj.Base58; public class StandardAddress extends AddressLight { @Override public byte getType() { return (byte)0x01; } public StandardAddress(String address) { super(address); } @Override public byte[] toByteArray() { return Base58.decode(get()); } }
23.75
70
0.699248
30e73ab221420e03ae388913c1828b3a3ab25418
156
package com.example; /** * Created by Pooholah on 2017/6/28. */ public class Son extends Parent { public Son(String a) { super(a); } }
12
36
0.589744
525293eba4780147b931a4e479fdedafafc2effb
233
import java.util.ArrayList; public class ErasedTypeEquivalence { public static void main(String args[]){ Class a=new ArrayList<String>().getClass(); Class b=new ArrayList<Integer>().getClass(); System.out.println(a==b); } }
23.3
46
0.72103
314140dfdd8d9b4269c29b16454a73aa41a8f279
159
package hr.from.ivantoplak.petclinic.services; import hr.from.ivantoplak.petclinic.model.Vet; public interface VetService extends CrudService<Vet, Long> { }
22.714286
60
0.811321
d36f9fc3cd9544f53135461ea84e82cbe3637078
3,377
package com.i2r.utils; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.i2r.object.Dialogue; import com.i2r.object.Turn; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; /** * transcriptprocessing * com.i2r.utils * Created by Zhang Chen * 6/23/2018 */ @Slf4j public class XmlParser { public static List<Dialogue> XmlToDialogue(String path) { XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); File file = new File(path); List<Dialogue> dialogueObjList = new ArrayList<>(); try { if (file.exists()) { String xml = inputStreamToString(new FileInputStream(file)); List<String> DialogueStringList = new ArrayList<>(); int startIndex = 0; int endIndex = xml.indexOf("</dialogue>"); while(endIndex != -1) { String dialogueString = xml.substring(startIndex, endIndex + 11); DialogueStringList.add(dialogueString); startIndex = endIndex + 11; endIndex = xml.indexOf("</dialogue>", startIndex); } for(int i = 0; i < DialogueStringList.size(); i++) { String temp = DialogueStringList.get(i); startIndex = temp.indexOf("<turn"); endIndex = temp.indexOf("</turn>"); List<Turn> turnObjList = new ArrayList<>(); while(startIndex != -1) { String turnString = temp.substring(startIndex, endIndex + 7); turnString = turnString.substring(0, turnString.indexOf("</utterance>") + 12) + "</turn>"; turnString = turnString.replace("<name-self>", " "); Turn turn = xmlMapper.readValue(turnString, Turn.class); turnObjList.add(turn); startIndex = temp.indexOf("<turn", endIndex + 7); endIndex = temp.indexOf("</turn>", startIndex); } temp = temp.substring(0, temp.indexOf("</timestamp>") + 12) + "</dialogue>"; Dialogue dialogue = xmlMapper.readValue(temp, Dialogue.class); dialogue.setTurns(turnObjList); dialogueObjList.add(dialogue); } } else { throw new NoSuchElementException(); } } catch (NoSuchElementException e) { log.error("Specified file does not exist with specified file path: {}", path); } catch (Exception e) { log.error("Parsing error: ", e); } return dialogueObjList; } private static String inputStreamToString(InputStream is) throws IOException { StringBuilder sb = new StringBuilder(); String line; InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); return sb.toString(); } }
38.816092
114
0.558188
b3149871ad60cd0cc70322fade2bf44be3682468
572
package com.nettooe; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication //@Configuration public class CampanhaApiApplication { public static void main(String[] args) { SpringApplication.run(CampanhaApiApplication.class, args); } // @Bean // ServletRegistrationBean h2servletRegistration() { // ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet()); // registrationBean.addUrlMappings("/console/*"); // return registrationBean; // } }
27.238095
93
0.798951
64b891afabc716c84c17426d92a4647ea405814d
32,708
package org.folio.rest.impl.integrationsuite; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static java.lang.String.format; import static org.apache.http.HttpStatus.SC_BAD_REQUEST; import static org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR; import static org.apache.http.HttpStatus.SC_NOT_FOUND; import static org.apache.http.HttpStatus.SC_NO_CONTENT; import static org.apache.http.HttpStatus.SC_UNPROCESSABLE_ENTITY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.folio.repository.RecordType.RESOURCE; import static org.folio.repository.accesstypes.AccessTypeMappingsTableConstants.ACCESS_TYPES_MAPPING_TABLE_NAME; import static org.folio.repository.accesstypes.AccessTypesTableConstants.ACCESS_TYPES_TABLE_NAME; import static org.folio.repository.kbcredentials.KbCredentialsTableConstants.KB_CREDENTIALS_TABLE_NAME; import static org.folio.repository.resources.ResourceTableConstants.RESOURCES_TABLE_NAME; import static org.folio.repository.tag.TagTableConstants.TAGS_TABLE_NAME; import static org.folio.rest.impl.PackagesTestData.STUB_PACKAGE_ID; import static org.folio.rest.impl.ProvidersTestData.STUB_VENDOR_ID; import static org.folio.rest.impl.ProvidersTestData.STUB_VENDOR_NAME; import static org.folio.rest.impl.ResourcesTestData.STUB_CUSTOM_RESOURCE_ID; import static org.folio.rest.impl.ResourcesTestData.STUB_MANAGED_RESOURCE_ID; import static org.folio.rest.impl.TagsTestData.STUB_TAG_VALUE; import static org.folio.rest.impl.TagsTestData.STUB_TAG_VALUE_2; import static org.folio.rest.impl.TitlesTestData.STUB_CUSTOM_PACKAGE_ID; import static org.folio.rest.impl.TitlesTestData.STUB_CUSTOM_TITLE_ID; import static org.folio.rest.impl.TitlesTestData.STUB_CUSTOM_VENDOR_ID; import static org.folio.rest.impl.TitlesTestData.STUB_MANAGED_TITLE_ID; import static org.folio.test.util.TestUtil.getFile; import static org.folio.test.util.TestUtil.mockGet; import static org.folio.test.util.TestUtil.mockPut; import static org.folio.test.util.TestUtil.readFile; import static org.folio.test.util.TestUtil.readJsonFile; import static org.folio.util.AccessTypesTestUtil.getAccessTypeMappings; import static org.folio.util.AccessTypesTestUtil.insertAccessTypeMapping; import static org.folio.util.AccessTypesTestUtil.insertAccessTypes; import static org.folio.util.AccessTypesTestUtil.testData; import static org.folio.util.AssertTestUtil.assertEqualsResourceId; import static org.folio.util.AssertTestUtil.assertErrorContainsTitle; import static org.folio.util.KBTestUtil.clearDataFromTable; import static org.folio.util.KBTestUtil.getDefaultKbConfiguration; import static org.folio.util.KBTestUtil.setupDefaultKBConfiguration; import static org.folio.util.KbCredentialsTestUtil.STUB_TOKEN_HEADER; import static org.folio.util.TagsTestUtil.saveTag; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern; import com.github.tomakehurst.wiremock.matching.EqualToPattern; import com.github.tomakehurst.wiremock.matching.RegexPattern; import com.github.tomakehurst.wiremock.matching.UrlPathPattern; import io.vertx.core.json.Json; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.skyscreamer.jsonassert.JSONAssert; import org.folio.repository.RecordType; import org.folio.repository.accesstypes.AccessTypeMapping; import org.folio.repository.resources.DbResource; import org.folio.rest.impl.WireMockTestBase; import org.folio.rest.jaxrs.model.AccessType; import org.folio.rest.jaxrs.model.Errors; import org.folio.rest.jaxrs.model.JsonapiError; import org.folio.rest.jaxrs.model.KbCredentials; import org.folio.rest.jaxrs.model.Resource; import org.folio.rest.jaxrs.model.ResourceBulkFetchCollection; import org.folio.rest.jaxrs.model.ResourcePutRequest; import org.folio.rest.jaxrs.model.ResourceTags; import org.folio.rest.jaxrs.model.ResourceTagsPutRequest; import org.folio.rest.jaxrs.model.Tags; import org.folio.util.ResourcesTestUtil; import org.folio.util.TagsTestUtil; @RunWith(VertxUnitRunner.class) public class EholdingsResourcesImplTest extends WireMockTestBase { private static final String MANAGED_PACKAGE_ENDPOINT = "/rm/rmaccounts/" + STUB_CUSTOMER_ID + "/vendors/" + STUB_VENDOR_ID + "/packages/" + STUB_PACKAGE_ID; private static final String MANAGED_RESOURCE_ENDPOINT = MANAGED_PACKAGE_ENDPOINT + "/titles/" + STUB_MANAGED_TITLE_ID; private static final String CUSTOM_RESOURCE_ENDPOINT = "/rm/rmaccounts/" + STUB_CUSTOMER_ID + "/vendors/" + STUB_CUSTOM_VENDOR_ID + "/packages/" + STUB_CUSTOM_PACKAGE_ID + "/titles/" + STUB_CUSTOM_TITLE_ID; private static final String STUB_MANAGED_RESOURCE_PATH = "eholdings/resources/" + STUB_MANAGED_RESOURCE_ID; private static final String RESOURCE_TAGS_PATH = "eholdings/resources/" + STUB_CUSTOM_RESOURCE_ID + "/tags"; private static final String RESOURCES_BULK_FETCH = "/eholdings/resources/bulk/fetch"; private KbCredentials configuration; @Override @Before public void setUp() throws Exception { super.setUp(); setupDefaultKBConfiguration(getWiremockUrl(), vertx); configuration = getDefaultKbConfiguration(vertx); setUpTestUsers(); } @After public void tearDown() { clearDataFromTable(vertx, ACCESS_TYPES_MAPPING_TABLE_NAME); clearDataFromTable(vertx, ACCESS_TYPES_TABLE_NAME); clearDataFromTable(vertx, TAGS_TABLE_NAME); clearDataFromTable(vertx, RESOURCES_TABLE_NAME); clearDataFromTable(vertx, KB_CREDENTIALS_TABLE_NAME); tearDownTestUsers(); } @Test public void shouldReturnResourceWhenValidId() throws IOException, URISyntaxException, JSONException { String stubResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-resource-by-id.json"; mockResource(stubResponseFile); String actualResponse = getWithOk(STUB_MANAGED_RESOURCE_PATH, STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, true); } @Test public void shouldReturnResourceWithTags() throws IOException, URISyntaxException { saveTag(vertx, STUB_MANAGED_RESOURCE_ID, RecordType.RESOURCE, STUB_TAG_VALUE); String stubResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; mockResource(stubResponseFile); Resource resource = getWithOk(STUB_MANAGED_RESOURCE_PATH, STUB_TOKEN_HEADER).as(Resource.class); assertTrue(resource.getData().getAttributes().getTags().getTagList().contains(STUB_TAG_VALUE)); } @Test public void shouldReturnResourceWithTitleWhenTitleFlagSetToTrue() throws IOException, URISyntaxException, JSONException { String stubResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-resource-by-id-with-title.json"; mockResource(stubResponseFile); String actualResponse = getWithOk("eholdings/resources/" + STUB_MANAGED_RESOURCE_ID + "?include=title", STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, true); } @Test public void shouldReturnResourceWithProviderWhenProviderFlagSetToTrue() throws IOException, URISyntaxException, JSONException { String stubResourceResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; String stubVendorResponseFile = "responses/rmapi/vendors/get-vendor-by-id-for-resource.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-resource-by-id-with-provider.json"; mockResource(stubResourceResponseFile); mockVendor(stubVendorResponseFile); String actualResponse = getWithOk("eholdings/resources/" + STUB_MANAGED_RESOURCE_ID + "?include=provider", STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, true); } @Test public void shouldReturnResourceWithPackageWhenPackageFlagSetToTrue() throws IOException, URISyntaxException, JSONException { String stubResourceResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; String stubPackageResponseFile = "responses/rmapi/packages/get-package-by-id-for-resource.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-resource-by-id-with-package.json"; mockResource(stubResourceResponseFile); mockPackage(stubPackageResponseFile); String actualResponse = getWithOk("eholdings/resources/" + STUB_MANAGED_RESOURCE_ID + "?include=package", STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, true); } @Test public void shouldReturnResourceWithAllIncludedObjectsWhenIncludeContainsAllObjects() throws IOException, URISyntaxException, JSONException { String stubResourceResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; String stubVendorResponseFile = "responses/rmapi/vendors/get-vendor-by-id-for-resource.json"; String stubPackageResponseFile = "responses/rmapi/packages/get-package-by-id-for-resource.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-resource-by-id-with-all-objects.json"; mockResource(stubResourceResponseFile); mockVendor(stubVendorResponseFile); mockPackage(stubPackageResponseFile); String actualResponse = getWithOk( "eholdings/resources/" + STUB_MANAGED_RESOURCE_ID + "?include=package,title,provider", STUB_TOKEN_HEADER) .asString(); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, true); } @Test public void shouldReturn404WhenRMAPINotFoundOnResourceGet() throws IOException, URISyntaxException { String stubResponseFile = "responses/rmapi/resources/get-resource-by-id-not-found-response.json"; stubFor( get(new UrlPathPattern(new RegexPattern(MANAGED_PACKAGE_ENDPOINT + "/titles.*"), true)) .willReturn(new ResponseDefinitionBuilder() .withBody(readFile(stubResponseFile)) .withStatus(404))); JsonapiError error = getWithStatus(STUB_MANAGED_RESOURCE_PATH, SC_NOT_FOUND, STUB_TOKEN_HEADER) .as(JsonapiError.class); assertErrorContainsTitle(error, "Title is no longer in this package."); } @Test public void shouldReturn400WhenValidationErrorOnResourceGet() { JsonapiError error = getWithStatus("eholdings/resources/583-abc-762169", SC_BAD_REQUEST, STUB_TOKEN_HEADER) .as(JsonapiError.class); assertErrorContainsTitle(error, "Resource id is invalid - 583-abc-762169"); } @Test public void shouldReturn500WhenRMApiReturns500ErrorOnResourceGet() { mockGet(new RegexPattern(MANAGED_PACKAGE_ENDPOINT + "/titles.*"), SC_INTERNAL_SERVER_ERROR); JsonapiError error = getWithStatus(STUB_MANAGED_RESOURCE_PATH, SC_INTERNAL_SERVER_ERROR, STUB_TOKEN_HEADER).as(JsonapiError.class); assertThat(error.getErrors().get(0).getTitle(), notNullValue()); } @Test public void shouldReturnUpdatedValuesManagedResourceOnSuccessfulPut() throws IOException, URISyntaxException, JSONException { String stubResponseFile = "responses/rmapi/resources/get-managed-resource-updated-response.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-managed-resource.json"; String actualResponse = mockUpdateResourceScenario(stubResponseFile, MANAGED_RESOURCE_ENDPOINT, STUB_MANAGED_RESOURCE_ID, readFile("requests/kb-ebsco/resource/put-managed-resource.json")); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, false); verify(1, putRequestedFor(new UrlPathPattern(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), true)) .withRequestBody( equalToJson(readFile("requests/rmapi/resources/put-managed-resource-is-selected-multiple-attributes.json")))); } @Test public void shouldCreateNewAccessTypeMappingOnSuccessfulPut() throws IOException, URISyntaxException, JSONException { List<AccessType> accessTypes = insertAccessTypes(testData(configuration.getId()), vertx); String accessTypeId = accessTypes.get(0).getId(); String stubResponseFile = "responses/rmapi/resources/get-managed-resource-updated-response.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-resource-by-id-with-access-type.json"; String requestBody = format(readFile("requests/kb-ebsco/resource/put-resource-with-access-type.json"), accessTypeId); String actualResponse = mockUpdateResourceScenario(stubResponseFile, MANAGED_RESOURCE_ENDPOINT, STUB_MANAGED_RESOURCE_ID, requestBody); String expectedJson = format(readFile(expectedResourceFile), accessTypeId, accessTypeId); JSONAssert.assertEquals(expectedJson, actualResponse, false); verify(1, putRequestedFor(new UrlPathPattern(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), true)).withRequestBody( equalToJson(readFile("requests/rmapi/resources/put-managed-resource-is-selected-multiple-attributes.json")))); List<AccessTypeMapping> accessTypeMappingsInDB = getAccessTypeMappings(vertx); assertEquals(1, accessTypeMappingsInDB.size()); assertEquals(accessTypeId, accessTypeMappingsInDB.get(0).getAccessTypeId().toString()); assertEquals(RESOURCE, accessTypeMappingsInDB.get(0).getRecordType()); } @Test public void shouldDeleteAccessTypeMappingOnSuccessfulPut() throws IOException, URISyntaxException, JSONException { List<AccessType> accessTypes = insertAccessTypes(testData(configuration.getId()), vertx); String accessTypeId = accessTypes.get(0).getId(); insertAccessTypeMapping(STUB_MANAGED_RESOURCE_ID, RESOURCE, accessTypeId, vertx); String stubResponseFile = "responses/rmapi/resources/get-managed-resource-updated-response.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-managed-resource.json"; String actualResponse = mockUpdateResourceScenario(stubResponseFile, MANAGED_RESOURCE_ENDPOINT, STUB_MANAGED_RESOURCE_ID, readFile("requests/kb-ebsco/resource/put-managed-resource.json")); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, false); verify(1, putRequestedFor(new UrlPathPattern(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), true)).withRequestBody( equalToJson(readFile("requests/rmapi/resources/put-managed-resource-is-selected-multiple-attributes.json")))); List<AccessTypeMapping> accessTypeMappingsInDB = getAccessTypeMappings(vertx); assertEquals(0, accessTypeMappingsInDB.size()); } @Test public void shouldReturn400OnPutPackageWithNotExistedAccessType() throws URISyntaxException, IOException { String requestBody = readFile("requests/kb-ebsco/resource/put-managed-resource-with-missing-access-type.json"); JsonapiError error = putWithStatus(STUB_MANAGED_RESOURCE_PATH, requestBody, SC_BAD_REQUEST, CONTENT_TYPE_HEADER, STUB_TOKEN_HEADER).as(JsonapiError.class); verify(0, putRequestedFor(new UrlPathPattern(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), true))); assertErrorContainsTitle(error, "Access type not found: id = 99999999-9999-1999-a999-999999999999"); } @Test public void shouldReturn422OnPutPackageWithInvalidAccessTypeId() throws URISyntaxException, IOException { String requestBody = readFile("requests/kb-ebsco/resource/put-managed-resource-with-invalid-access-type.json"); Errors error = putWithStatus(STUB_MANAGED_RESOURCE_PATH, requestBody, SC_UNPROCESSABLE_ENTITY, CONTENT_TYPE_HEADER, STUB_TOKEN_HEADER).as(Errors.class); verify(0, putRequestedFor(new UrlPathPattern(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), true))); assertEquals(1, error.getErrors().size()); assertEquals("must match \"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[1-5][a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$\"", error.getErrors().get(0).getMessage()); } @Test public void shouldDeselectManagedResourceOnPutWithSelectedFalse() throws IOException, URISyntaxException, JSONException { String stubResponseFile = "responses/rmapi/resources/get-managed-resource-updated-response-is-selected-false.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-managed-resource.json"; ResourcePutRequest request = readJsonFile("requests/kb-ebsco/resource/put-managed-resource-is-not-selected.json", ResourcePutRequest.class); request.getData().getAttributes().setIsSelected(false); String actualResponse = mockUpdateResourceScenario(stubResponseFile, MANAGED_RESOURCE_ENDPOINT, STUB_MANAGED_RESOURCE_ID, Json.encode(request)); Resource expectedResource = readJsonFile(expectedResourceFile, Resource.class); expectedResource.getData().getAttributes().setIsSelected(false); JSONAssert.assertEquals(Json.encode(expectedResource), actualResponse, false); verify(1, putRequestedFor(new UrlPathPattern(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), true)) .withRequestBody(new EqualToJsonPattern(readFile("requests/rmapi/resources/put-managed-resource-is-not-selected.json"), true, true))); } @Test public void shouldReturnUpdatedValuesCustomResourceOnSuccessfulPut() throws IOException, URISyntaxException, JSONException { String stubResponseFile = "responses/rmapi/resources/get-custom-resource-updated-response.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-custom-resource.json"; String actualResponse = mockUpdateResourceScenario(stubResponseFile, CUSTOM_RESOURCE_ENDPOINT, STUB_CUSTOM_RESOURCE_ID, readFile("requests/kb-ebsco/resource/put-custom-resource.json")); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, false); verify(1, putRequestedFor(new UrlPathPattern(new RegexPattern(CUSTOM_RESOURCE_ENDPOINT), true)) .withRequestBody( equalToJson(readFile("requests/rmapi/resources/put-custom-resource-is-selected-multiple-attributes.json")))); } @Test public void shouldUpdateTagsOnSuccessfulTagsPut() throws IOException, URISyntaxException { List<String> tags = Collections.singletonList(STUB_TAG_VALUE); sendPutTags(tags); List<DbResource> resources = ResourcesTestUtil.getResources(vertx); assertEquals(1, resources.size()); assertEqualsResourceId(resources.get(0).getId()); assertEquals(STUB_VENDOR_NAME, resources.get(0).getName()); } @Test public void shouldUpdateTagsOnSuccessfulTagsPutWithAlreadyExistingTags() throws IOException, URISyntaxException { saveTag(vertx, STUB_CUSTOM_RESOURCE_ID, RecordType.RESOURCE, STUB_TAG_VALUE); List<String> newTags = Arrays.asList(STUB_TAG_VALUE, STUB_TAG_VALUE_2); sendPutTags(newTags); List<String> tagsAfterRequest = TagsTestUtil.getTagsForRecordType(vertx, RecordType.RESOURCE); assertThat(tagsAfterRequest, containsInAnyOrder(newTags.toArray())); } @Test public void shouldReturn422OnPutTagsWhenRequestBodyIsInvalid() throws IOException, URISyntaxException { ObjectMapper mapper = new ObjectMapper(); ResourceTagsPutRequest tags = mapper.readValue(getFile("requests/kb-ebsco/resource/put-resource-tags.json"), ResourceTagsPutRequest.class); tags.getData().getAttributes().setName(""); JsonapiError error = putWithStatus(RESOURCE_TAGS_PATH, mapper.writeValueAsString(tags), SC_UNPROCESSABLE_ENTITY, STUB_TOKEN_HEADER) .as(JsonapiError.class); assertErrorContainsTitle(error, "Invalid name"); } @Test public void shouldReturn422WhenInvalidUrlIsProvidedForCustomResource() throws URISyntaxException, IOException { final String stubResponseFile = "responses/rmapi/resources/get-custom-resource-updated-response.json"; final String invalidPutBody = readFile("requests/kb-ebsco/resource/put-custom-resource-invalid-url.json"); mockGet(new RegexPattern(CUSTOM_RESOURCE_ENDPOINT), stubResponseFile); JsonapiError error = putWithStatus("eholdings/resources/" + STUB_CUSTOM_RESOURCE_ID, invalidPutBody, SC_UNPROCESSABLE_ENTITY, STUB_TOKEN_HEADER).as(JsonapiError.class); assertErrorContainsTitle(error, "Invalid url"); } @Test public void shouldPostResourceToRMAPI() throws IOException, URISyntaxException, JSONException { String stubTitleResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; String stubPackageResponseFile = "responses/rmapi/packages/get-custom-package-by-id-response.json"; String stubPackageResourcesFile = "responses/rmapi/resources/get-resources-by-package-id-response.json"; String postStubRequest = "requests/kb-ebsco/resource/post-resources-request.json"; String expectedResourceFile = "responses/kb-ebsco/resources/expected-resource-after-post.json"; EqualToJsonPattern putRequestBodyPattern = new EqualToJsonPattern(readFile("requests/rmapi/resources/select-resource-request.json"), true, true); mockPackageResources(stubPackageResourcesFile); mockPackage(stubPackageResponseFile); mockTitle(stubTitleResponseFile); mockResource(stubTitleResponseFile); mockPut(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), putRequestBodyPattern, SC_NO_CONTENT); String actualResponse = postWithOk("eholdings/resources", readFile(postStubRequest), STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals(readFile(expectedResourceFile), actualResponse, true); verify(1, putRequestedFor(new UrlPathPattern(new EqualToPattern(MANAGED_RESOURCE_ENDPOINT), false)) .withRequestBody(putRequestBodyPattern)); } @Test public void shouldReturn404IfTitleOrPackageIsNotFound() throws IOException, URISyntaxException { String postStubRequest = "requests/kb-ebsco/resource/post-resources-request.json"; mockGet(new RegexPattern("/rm/rmaccounts/" + STUB_CUSTOMER_ID + "/titles.*"), SC_NOT_FOUND); mockGet(new RegexPattern(MANAGED_PACKAGE_ENDPOINT), SC_NOT_FOUND); JsonapiError error = postWithStatus("eholdings/resources", readFile(postStubRequest), SC_NOT_FOUND, STUB_TOKEN_HEADER) .as(JsonapiError.class); assertErrorContainsTitle(error, "not found"); } @Test public void shouldReturn422IfPackageIsNotCustom() throws IOException, URISyntaxException { String stubTitleResponseFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; String stubPackageResponseFile = "responses/rmapi/packages/get-package-by-id-for-resource.json"; String stubPackageResourcesFile = "responses/rmapi/resources/get-resources-by-package-id-response.json"; String postStubRequest = "requests/kb-ebsco/resource/post-resources-request.json"; mockPackageResources(stubPackageResourcesFile); mockPackage(stubPackageResponseFile); mockTitle(stubTitleResponseFile); JsonapiError error = postWithStatus("eholdings/resources", readFile(postStubRequest), SC_UNPROCESSABLE_ENTITY, STUB_TOKEN_HEADER) .as(JsonapiError.class); assertThat(error.getErrors().get(0).getTitle(), containsString("Invalid PackageId")); } @Test public void shouldSendDeleteRequestForResourceAssociatedWithCustomPackage() throws IOException, URISyntaxException { EqualToJsonPattern putBodyPattern = new EqualToJsonPattern("{\"isSelected\":false}", true, true); deleteResource(putBodyPattern); verify(1, putRequestedFor(new UrlPathPattern(new EqualToPattern(CUSTOM_RESOURCE_ENDPOINT), false)) .withRequestBody(putBodyPattern)); } @Test public void shouldDeleteTagsOnDeleteRequest() throws IOException, URISyntaxException { saveTag(vertx, STUB_CUSTOM_RESOURCE_ID, RecordType.RESOURCE, STUB_TAG_VALUE); EqualToJsonPattern putBodyPattern = new EqualToJsonPattern("{\"isSelected\":false}", true, true); deleteResource(putBodyPattern); List<String> actualTags = TagsTestUtil.getTags(vertx); assertThat(actualTags, empty()); } @Test public void shouldDeleteAccessTypeOnDeleteRequest() throws IOException, URISyntaxException { String accessTypeId = insertAccessTypes(testData(configuration.getId()), vertx).get(0).getId(); insertAccessTypeMapping(STUB_CUSTOM_RESOURCE_ID, RecordType.RESOURCE, accessTypeId, vertx); EqualToJsonPattern putBodyPattern = new EqualToJsonPattern("{\"isSelected\":false}", true, true); deleteResource(putBodyPattern); List<AccessTypeMapping> actualMappings = getAccessTypeMappings(vertx); assertThat(actualMappings, empty()); } @Test public void shouldReturn400WhenResourceIdIsInvalid() { JsonapiError error = deleteWithStatus("eholdings/resources/abc-def", SC_BAD_REQUEST, STUB_TOKEN_HEADER).as(JsonapiError.class); assertErrorContainsTitle(error, "Resource id is invalid"); } @Test public void shouldReturn400WhenTryingToDeleteResourceAssociatedWithManagedPackage() throws URISyntaxException, IOException { String stubResponseFile = "responses/rmapi/resources/get-managed-resource-updated-response.json"; mockGet(new EqualToPattern(MANAGED_RESOURCE_ENDPOINT), stubResponseFile); JsonapiError error = deleteWithStatus(STUB_MANAGED_RESOURCE_PATH, SC_BAD_REQUEST, STUB_TOKEN_HEADER).as(JsonapiError.class); assertErrorContainsTitle(error, "Resource cannot be deleted"); } @Test public void shouldReturnListWithBulkFetchResources() throws IOException, URISyntaxException, JSONException { String postBody = readFile("requests/kb-ebsco/resource/post-resources-bulk.json"); String expectedResourceFile = "responses/kb-ebsco/resources/expected-resources-bulk-response.json"; String responseRmApiFile = "responses/rmapi/resources/get-resource-by-id-success-response.json"; mockGet(new EqualToPattern(MANAGED_RESOURCE_ENDPOINT), responseRmApiFile); final String actualResponse = postWithOk("/eholdings/resources/bulk/fetch", postBody, STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals( readFile(expectedResourceFile), actualResponse, true); } @Test public void shouldReturn422OnInvalidIdFormat() throws IOException, URISyntaxException { String postBody = readFile("requests/kb-ebsco/resource/post-resources-bulk-with-invalid-id-format.json"); final Errors error = postWithStatus(RESOURCES_BULK_FETCH, postBody, SC_UNPROCESSABLE_ENTITY, STUB_TOKEN_HEADER) .as(Errors.class); assertThat(error.getErrors().get(0).getMessage(), equalTo("elements in list must match pattern")); } @Test public void shouldReturnResponseWhenIdIsTooLong() throws IOException, URISyntaxException, JSONException { String postBody = readFile("requests/kb-ebsco/resource/post-resource-with-too-long-id.json"); String expectedResourceFile = "responses/kb-ebsco/resources/expected-response-on-too-long-id.json"; final String actualResponse = postWithOk(RESOURCES_BULK_FETCH, postBody, STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals( readFile(expectedResourceFile), actualResponse, false); } @Test public void shouldReturnResourcesAndFailedIds() throws IOException, URISyntaxException, JSONException { String postBody = readFile("requests/kb-ebsco/resource/post-resources-bulk-with-invalid-ids.json"); String expectedResourceFile = "responses/kb-ebsco/resources/expected-resources-bulk-response-with-failed-ids.json"; String resourceResponse1 = "responses/rmapi/resources/get-resource-by-id-success-response.json"; mockGet(new EqualToPattern(MANAGED_RESOURCE_ENDPOINT), resourceResponse1); String resourceResponse2 = "responses/rmapi/resources/get-custom-resource-updated-response.json"; mockGet(new EqualToPattern(CUSTOM_RESOURCE_ENDPOINT), resourceResponse2); String notFoundResponse = "responses/rmapi/resources/get-resource-by-id-not-found-response.json"; stubFor( get(new UrlPathPattern( new EqualToPattern("/rm/rmaccounts/" + STUB_CUSTOMER_ID + "/vendors/186/packages/3150130/titles/19087948"), false)) .willReturn(new ResponseDefinitionBuilder() .withBody(readFile(notFoundResponse)) .withStatus(404))); final String actualResponse = postWithOk(RESOURCES_BULK_FETCH, postBody, STUB_TOKEN_HEADER).asString(); JSONAssert.assertEquals( readFile(expectedResourceFile), actualResponse, false); } @Test public void shouldReturnErrorWhenRMApiFails() throws IOException, URISyntaxException { mockGet(new RegexPattern(MANAGED_PACKAGE_ENDPOINT + "/titles.*"), SC_INTERNAL_SERVER_ERROR); String postBody = readFile("requests/kb-ebsco/resource/post-resources-bulk.json"); final ResourceBulkFetchCollection bulkFetchCollection = postWithOk(RESOURCES_BULK_FETCH, postBody, STUB_TOKEN_HEADER).as(ResourceBulkFetchCollection.class); assertThat(bulkFetchCollection.getIncluded().size(), equalTo(0)); assertThat(bulkFetchCollection.getMeta().getFailed().getResources().size(), equalTo(1)); assertThat(bulkFetchCollection.getMeta().getFailed().getResources().get(0), equalTo("19-3964-762169")); } private void mockPackageResources(String stubPackageResourcesFile) throws IOException, URISyntaxException { mockGet(new RegexPattern(MANAGED_PACKAGE_ENDPOINT + "/titles.*"), stubPackageResourcesFile); } private void mockPackage(String responseFile) throws IOException, URISyntaxException { mockGet(new RegexPattern(MANAGED_PACKAGE_ENDPOINT), responseFile); } private void mockResource(String responseFile) throws IOException, URISyntaxException { mockGet(new RegexPattern(MANAGED_RESOURCE_ENDPOINT), responseFile); } private void mockTitle(String responseFile) throws IOException, URISyntaxException { mockGet(new RegexPattern("/rm/rmaccounts/" + STUB_CUSTOMER_ID + "/titles.*"), responseFile); } private void mockVendor(String responseFile) throws IOException, URISyntaxException { mockGet(new RegexPattern("/rm/rmaccounts/" + STUB_CUSTOMER_ID + "/vendors/" + STUB_VENDOR_ID), responseFile); } private String mockUpdateResourceScenario(String updatedResourceResponseFile, String resourceEndpoint, String resourceId, String requestBody) throws IOException, URISyntaxException { stubFor( get(new UrlPathPattern(new RegexPattern(resourceEndpoint), false)) .willReturn(new ResponseDefinitionBuilder().withBody(readFile(updatedResourceResponseFile)))); stubFor( put(new UrlPathPattern(new RegexPattern(resourceEndpoint), true)) .willReturn(new ResponseDefinitionBuilder().withStatus(SC_NO_CONTENT))); return putWithOk("eholdings/resources/" + resourceId, requestBody, STUB_TOKEN_HEADER).asString(); } private void sendPutTags(List<String> newTags) throws IOException, URISyntaxException { ObjectMapper mapper = new ObjectMapper(); ResourceTagsPutRequest tags = mapper.readValue(getFile("requests/kb-ebsco/resource/put-resource-tags.json"), ResourceTagsPutRequest.class); if (newTags != null) { tags.getData().getAttributes().setTags(new Tags() .withTagList(newTags)); } putWithOk(RESOURCE_TAGS_PATH, mapper.writeValueAsString(tags), STUB_TOKEN_HEADER).as(ResourceTags.class); } private void deleteResource(EqualToJsonPattern putBodyPattern) throws IOException, URISyntaxException { String stubResponseFile = "responses/rmapi/resources/get-custom-resource-updated-response.json"; mockGet(new EqualToPattern(CUSTOM_RESOURCE_ENDPOINT), stubResponseFile); mockPut(new EqualToPattern(CUSTOM_RESOURCE_ENDPOINT), putBodyPattern, SC_NO_CONTENT); deleteWithNoContent("eholdings/resources/" + STUB_CUSTOM_RESOURCE_ID, STUB_TOKEN_HEADER); } }
50.32
129
0.79424
1b56963ea28a3ac5ce394822ca11134803d7b158
1,323
package net.mednikov.MessageServiceExample.auth; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.User; import io.vertx.ext.auth.jwt.JWTAuth; import io.vertx.ext.jwt.JWTOptions; import java.util.UUID; public class AuthProvider implements JWTAuth { /* This is just a dummy AuthProvider and is a boilerplate:) If you need to implement AuthProvider, please consider my article: http://www.mednikov.net/case-studies/how-i-reinvented-a-wheel-building-sms-auth-in-vertx-with-java/ and code: https://github.com/yuri-mednikov/vertx-sms-auth-example */ private IAuthDao authDao; public AuthProvider() throws Exception{ } @Override public String generateToken(JsonObject jsonObject, JWTOptions jwtOptions) { return UUID.randomUUID().toString(); } @Override public void authenticate(JsonObject payload, Handler<AsyncResult<User>> handler) { String token = payload.getString("jwt"); if (token!=null){ AuthenticatedUser user = new AuthenticatedUser(); handler.handle(Future.succeededFuture(user)); } else { handler.handle(Future.failedFuture("Access denied! No token!")); } } }
28.148936
103
0.70068
04f3af57bb15e5348e64c7602f725100a76e4a70
23,537
/* * Copyright 2010 Vrije Universiteit * * 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. */ /* $Id$ */ package ibis.ipl; import java.io.IOException; import java.nio.ByteBuffer; /** * A message used to write data from a {@link SendPort} to one or more * {@link ReceivePort}s. * <p> * A <code>WriteMessage</code> is obtained from a {@link SendPort} through * the {@link SendPort#newMessage SendPort.newMessage} method. * At most one <code>WriteMessage</code> is alive at one time for a given * <code>SendPort</code>. * When a message is alive and a new message is requested, the requester * is blocked until the live message is finished. * <p> * For all read methods in this class, the invariant is that the reads must * match the writes one by one. An exception to this rule is that an * array written with any of the <code>writeArray</code> methods can be * read by {@link ReadMessage#readObject}. Likewise, an * array written with the {@link WriteMessage#writeByteBuffer} method can be read * by {@link ReadMessage#readObject} (resulting in a byte array), and also by the * {@link ReadMessage#readArray(byte[])} method. * <strong> * In contrast, an array written with * {@link #writeObject writeObject} * cannot be read with <code>readArray</code>, because * {@link #writeObject writeObject} does duplicate detection, * and may have written only a handle. * </strong> * However, an array written with {@link #writeArray(byte[])} can be * read with {@link ReadMessage#readByteBuffer(ByteBuffer)}. * <p> * The {@link #writeObject(Object)} and {@link #writeString(String)} methods * do duplicate checks if the underlying serialization stream is an object * serialization stream: if the object was already written to this * message, a handle for this object is written instead of the object itself. *<p> * When the port type has the {@link PortType#CONNECTION_ONE_TO_MANY} * or {@link PortType#CONNECTION_MANY_TO_MANY} capability set, * no exceptions are thrown by write methods in the write message. * Instead, the exception may be passed on to the <code>lostConnection</code> * upcall, in case a {@link SendPortDisconnectUpcall} is registered. * This allows a multicast to continue to the other destinations. * Ultimately, the {@link WriteMessage#finish() finish} method will * throw an exception. * <p> * Data may be streamed, so the user is not allowed to change the data * pushed into this message. * It is only safe to touch the data after it has actually been * sent, which can be ensured by either calling {@link #flush}, * {@link WriteMessage#finish()} or {@link #reset}, * or a {@link #send} followed by a corresponding {@link #sync}. */ public interface WriteMessage { /** * Starts sending the message to all {@link ibis.ipl.ReceivePort * ReceivePorts} its {@link ibis.ipl.SendPort} is connected to. * Data may be streamed, so the user is not allowed to change the data * pushed into this message, as the send is NON-blocking. * It is only safe to touch the data after it has actually been * sent, which can be ensured by either calling {@link #finish()} or * {@link #reset}, or a {@link #sync} corresponding to this send. * The <code>send</code> method returns a ticket, which can be used * as a parameter to the {@link #sync} method, which will block until * the data corresponding to this ticket can be used again. * @return * a ticket. * @exception IOException * an error occurred **/ public int send() throws IOException; /** * Blocks until the data of the <code>send</code> which returned * the <code>ticket</code> parameter may be used again. * It also synchronizes with respect to all sends before that. * If <code>ticket</code> does not correspond to any <code>send</code>, * it blocks until all outstanding sends have been processed. * @param ticket * the ticket number. * @exception IOException * an error occurred */ public void sync(int ticket) throws IOException; /** * Blocks until all objects written to this message can be * used again. * @exception IOException * an error occurred */ public void flush() throws IOException; /** * Resets the state of any objects already written to the stream. * This means that the WriteMessage "forgets" which objects already * have been written with it. * @exception IOException * an error occurred */ public void reset() throws IOException; /** * If needed, send, and then block until the entire message has been sent * and clear the message. The number of bytes written in this message * is returned. * After the finish, no more bytes can be written to the message, * and other information obtained from the message, such as * {@link #bytesWritten()} is no longer available. Implementations * are explicitly allowed to reuse the message object. * <strong> * Even for multicast messages, the size only counts once. * </strong> * @return * the number of bytes written in this message. * @exception IOException * an error occurred **/ public long finish() throws IOException; /** * This method can be used to inform Ibis that one of the * <code>WriteMessage</code> methods has thrown an IOException. * It implies a {@link #finish()}. * @param exception * the exception that was thrown. */ public void finish(IOException exception); /** * Returns the number of bytes read from this message. * Note that for streaming implementations (i.e., messages with an unlimited * capacity) this number may not be exact because of intermediate buffering. * * <strong> * Even for multicast messages, the size only counts once. * </strong> * @return * the number of bytes written to this message. * @exception IOException * an error occurred. */ public long bytesWritten() throws IOException; /** * Returns the maximum number of bytes that will fit into this message. * * @return * the maximum number of bytes that will fit into this message or * -1 when the message size is unlimited * @exception IOException * an error occurred. */ public int capacity() throws IOException; /** * Returns the remaining number of bytes that can be written into this * message. * * @return * the remaining number of bytes that can be written into this * message or -1 when the message size is unlimited * @exception IOException * an error occurred. */ public int remaining() throws IOException; /** * Returns the {@link SendPort} of this <code>WriteMessage</code>. * @return * the {@link SendPort} of this <code>WriteMessage</code>. */ public SendPort localPort(); /** * Writes a boolean value to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * @param value * the boolean value to write. * @exception IOException * an error occurred */ public void writeBoolean(boolean value) throws IOException; /** * Writes a byte value to the message. * @param value * the byte value to write. * @exception IOException * an error occurred */ public void writeByte(byte value) throws IOException; /** * Writes a char value to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * @param value * the char value to write. * @exception IOException * an error occurred */ public void writeChar(char value) throws IOException; /** * Writes a short value to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * @param value * the short value to write. * @exception IOException * an error occurred */ public void writeShort(short value) throws IOException; /** * Writes a int value to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * @param value * the int value to write. * @exception IOException * an error occurred */ public void writeInt(int value) throws IOException; /** * Writes a long value to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * @param value * the long value to write. * @exception IOException * an error occurred */ public void writeLong(long value) throws IOException; /** * Writes a float value to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * @param value * the float value to write. * @exception IOException * an error occurred */ public void writeFloat(float value) throws IOException; /** * Writes a double value to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * @param value * the double value to write. * @exception IOException * an error occurred */ public void writeDouble(double value) throws IOException; /** * Writes a <code>String</code> to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * If the underlying serialization stream is an object serialization * stream, a duplicate check for this <code>String</code> object * is performed: if the object was already written to this * message, a handle for this object is written instead of * the object itself. * @param value * the string to write. * @exception IOException * an error occurred */ public void writeString(String value) throws IOException; /** * Writes a <code>Serializable</code> object to the message. * This method throws an IOException if the underlying serialization * stream cannot do object serialization. * (See {@link PortType#SERIALIZATION_OBJECT}). * A duplicate check for this <code>String</code> object * is performed: if the object was already written to this * message, a handle for this object is written instead of * the object itself. * @param value * the object value to write. * @exception IOException * an error occurred */ public void writeObject(Object value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred **/ public void writeArray(boolean[] value) throws IOException; /** * Writes an array to the message. * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(byte[] value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(char[] value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(short[] value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(int[] value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(long[] value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(float[] value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(double[] value) throws IOException; /** * Writes an array to the message. * This method throws an IOException if the underlying serialization * stream cannot do object serialization. * (See {@link PortType#SERIALIZATION_OBJECT}). * No duplicate check is performed for this array! * This method is just a shortcut for doing: * <code>writeArray(val, 0, val.length);</code> * @param value * the array to be written. * @exception IOException * an error occurred */ public void writeArray(Object[] value) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(boolean[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(byte[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(char[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(short[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(int[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(long[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(float[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream can only do byte serialization. * (See {@link PortType#SERIALIZATION_BYTE}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(double[] value, int offset, int length) throws IOException; /** * Writes a slice of an array. The slice starts at offset <code>off</code>. * This method throws an IOException if the underlying serialization * stream cannot do object serialization. * (See {@link PortType#SERIALIZATION_OBJECT}). * No duplicate check is performed for this array! * @param value * the array to be written * @param offset * offset in the array * @param length * the number of elements to be written * @exception IOException * an error occurred */ public void writeArray(Object[] value, int offset, int length) throws IOException; /** * Writes the contents of the byte buffer (between its current position and its * limit). This method is allowed for all serialization types, even * {@link PortType#SERIALIZATION_BYTE}. * @param value * the byte buffer from which data is to be written * @exception IOException * an error occurred */ public void writeByteBuffer(ByteBuffer value) throws IOException; }
37.719551
83
0.638229
2c50390f06e97d8ee33e3e6d30708a243ec4bfe8
2,053
package net.jxta.impl.endpoint.netty.http; import java.util.concurrent.Executors; import net.jxta.impl.endpoint.netty.NettyTransport; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.ServerSocketChannelFactory; import org.jboss.netty.channel.socket.httptunnel.HttpTunnelClientChannelFactory; import org.jboss.netty.channel.socket.httptunnel.HttpTunnelServerChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * Netty based transport which uses a full duplex HTTP tunnel rather than a raw TCP * connection to send messages between client and server. This is intended to allow * negotiation of restrictive transparent firewalls and proxies, typically in corporate * environments. * * @author [email protected] */ public class NettyHttpTunnelTransport extends NettyTransport { @Override protected ClientSocketChannelFactory createClientSocketChannelFactory() { NioClientSocketChannelFactory nioFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); return new HttpTunnelClientChannelFactory(nioFactory); } @Override protected ServerSocketChannelFactory createServerSocketChannelFactory() { NioServerSocketChannelFactory nioFactory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); return new HttpTunnelServerChannelFactory(nioFactory); } @Override protected String getDefaultProtocolName() { return "http2"; } @Override protected int getDefaultPort() { return 8080; } @Override protected int getDefaultPortRangeLowerBound() { return 8081; } @Override protected int getDefaultPortRangeUpperBound() { return 8099; } @Override protected String getTransportDescriptiveName() { return "HTTP Tunnel"; } }
33.112903
151
0.774476
0942955f50bd66dfeef2efd00bd4191de47db9c1
196
package com.simibubi.create.foundation.tileEntity.behaviour; import com.simibubi.create.foundation.tileEntity.TileEntityBehaviour; public class BehaviourType<T extends TileEntityBehaviour> { }
24.5
69
0.846939
6fdcfe15c5d9b9d97260fdcc51d876e525c8b905
3,339
package amazon; import java.util.*; /* Given a map Map<String, List<String>> userMap, where the key is a username and the value is a list of user's songs. Also given a map Map<String, List<String>> genreMap, where the key is a genre and the value is a list of songs belonging to this genre. The task is to return a map Map<String, List<String>>, where the key is a username and the value is a list of the user's favorite genres. Favorite genre is a genre with the most song. Example 1: Input: userMap = { "David": ["song1", "song2", "song3", "song4", "song8"], "Emma": ["song5", "song6", "song7"] }, genreMap = { "Rock": ["song1", "song3"], "Dubstep": ["song7"], "Techno": ["song2", "song4"], "Pop": ["song5", "song6"], "Jazz": ["song8", "song9"] } Output: { "David": ["Rock", "Techno"], "Emma": ["Pop"] } Explanation: David has 2 Rock, 2 Techno and 1 Jazz song. So he has 2 favorite genres. Emma has 2 Pop and 1 Dubstep song. Pop is Emma's favorite genre. Example 2: Input: userMap = { "David": ["song1", "song2"], "Emma": ["song3", "song4"] }, genreMap = {} Output: { "David": [], "Emma": [] } */ public class FavoriteGenres { public static void main(String[] args) { Map<String, List<String>> userSongs = new HashMap<>(); userSongs.put("David", Arrays.asList("song1", "song2", "song3", "song4", "song8")); userSongs.put("Emma", Arrays.asList("song5", "song6", "song7")); Map<String, List<String>> genreMap = new HashMap<>(); genreMap.put("Rock", Arrays.asList("song1", "song3")); genreMap.put("Dubstep", Arrays.asList("song7")); genreMap.put("Techno", Arrays.asList("song2", "song4")); genreMap.put("Pop", Arrays.asList("song5", "song6")); genreMap.put("Jazz", Arrays.asList("song8", "song9")); System.out.println(favoriteGenres(userSongs, genreMap)); userSongs.put("David", Arrays.asList("song1", "song2")); userSongs.put("Emma", Arrays.asList("song3", "song4")); genreMap = new HashMap<>(); System.out.println(favoriteGenres(userSongs, genreMap)); } public static Map<String, List<String>> favoriteGenres(Map<String, List<String>> userSongs, Map<String, List<String>> genres) { Map<String, List<String>> userGenres = new HashMap<>(userSongs.size()); Map<String, String> songGenre = new HashMap<>(); for (Map.Entry<String, List<String>> genre : genres.entrySet()) { genre.getValue().forEach(s -> songGenre.put(s, genre.getKey())); } for (Map.Entry<String, List<String>> user : userSongs.entrySet()) { Map<String, Integer> countGenre = new HashMap<>(); user.getValue().forEach(s -> { if (songGenre.containsKey(s)) { // System.out.println("s = " + s); int val = countGenre.getOrDefault(songGenre.get(s), 0); countGenre.put(songGenre.get(s), val + 1); } }); if (countGenre.isEmpty()) { userGenres.put(user.getKey(), Collections.emptyList()); } else { List<String> faGenres = new ArrayList<>(); int max = -1; for (Map.Entry<String, Integer> count : countGenre.entrySet()) { if (count.getValue() > max) { faGenres.clear(); faGenres.add(count.getKey()); max = count.getValue(); } else if (count.getValue() == max) { faGenres.add(count.getKey()); } } userGenres.put(user.getKey(), faGenres); } } return userGenres; } }
31.205607
137
0.634921
2b20a2afa301e4603196074c96aeb2856541b4b4
16,500
/* * Copyright (C) 2013-2015 RoboVM AB * * 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. * * Portions of this code is based on Parse's AnyPic sample * which is copyright (C) 2013 Parse. */ package org.robovm.samples.robopods.parse.anypic.ios.util; import org.robovm.apple.coregraphics.CGAffineTransform; import org.robovm.apple.coregraphics.CGBitmapContext; import org.robovm.apple.coregraphics.CGBitmapInfo; import org.robovm.apple.coregraphics.CGColorSpace; import org.robovm.apple.coregraphics.CGContext; import org.robovm.apple.coregraphics.CGImage; import org.robovm.apple.coregraphics.CGImageAlphaInfo; import org.robovm.apple.coregraphics.CGInterpolationQuality; import org.robovm.apple.coregraphics.CGRect; import org.robovm.apple.coregraphics.CGSize; import org.robovm.apple.uikit.UIColor; import org.robovm.apple.uikit.UIImage; import org.robovm.apple.uikit.UIViewContentMode; public class UIImageUtility { /** * * @param image * @return true if the image has an alpha layer */ public static boolean hasAlpha(UIImage image) { CGImageAlphaInfo alpha = image.getCGImage().getAlphaInfo(); return alpha == CGImageAlphaInfo.First || alpha == CGImageAlphaInfo.Last || alpha == CGImageAlphaInfo.PremultipliedFirst || alpha == CGImageAlphaInfo.PremultipliedLast; } /** * * @param image * @return a copy of the given image, adding an alpha channel if it doesn't * already have one */ public static UIImage addAlpha(UIImage image) { if (hasAlpha(image)) { return image; } CGImage i = image.getCGImage(); long width = i.getWidth(); long height = i.getHeight(); // The bitsPerComponent and bitmapInfo values are hard-coded to prevent // an "unsupported parameter combination" error CGBitmapContext offscreenContext = CGBitmapContext.create(width, height, 8, 0, i.getColorSpace(), new CGBitmapInfo(CGBitmapInfo.ByteOrderDefault.value() | CGImageAlphaInfo.PremultipliedFirst.value())); // TODO // could // be // improved // Draw the image into the context and retrieve the new image, which // will now have an alpha layer offscreenContext.drawImage(new CGRect(0, 0, width, height), i); CGImage ia = offscreenContext.toImage(); UIImage alphaImage = new UIImage(ia); return alphaImage; } /** * * @param image * @param borderSize * @return a copy of the image with a transparent border of the given size * added around its edges. If the image has no alpha layer, one will * be added to it. */ public static UIImage addTransparentBorder(UIImage image, int borderSize) { // If the image does not have an alpha layer, add one image = addAlpha(image); CGRect newRect = new CGRect(0, 0, image.getSize().getWidth() + borderSize * 2, image.getSize().getHeight() + borderSize * 2); CGImage i = image.getCGImage(); // Build a context that's the same dimensions as the new size CGBitmapContext bitmap = CGBitmapContext.create((long) newRect.getSize().getWidth(), (long) newRect.getSize() .getHeight(), i.getBitsPerComponent(), 0, i.getColorSpace(), i.getBitmapInfo()); // Draw the image in the center of the context, leaving a gap around the // edges CGRect imageLocation = new CGRect(borderSize, borderSize, image.getSize().getWidth(), image.getSize() .getHeight()); bitmap.drawImage(imageLocation, i); CGImage borderImage = bitmap.toImage(); // Create a mask to make the border transparent, and combine it with the // image CGImage maskImage = newBorderMask(borderSize, newRect.getSize()); CGImage tbi = CGImage.createWithMask(borderImage, maskImage); UIImage transparentBorderImage = new UIImage(tbi); return transparentBorderImage; } /** * * @param borderSize * @param size * @return a mask that makes the outer edges transparent and everything else * opaque The size must include the entire mask (opaque part + * transparent border) */ private static CGImage newBorderMask(int borderSize, CGSize size) { CGColorSpace colorSpace = CGColorSpace.createDeviceGray(); // Build a context that's the same dimensions as the new size CGBitmapContext maskContext = CGBitmapContext.create((long) size.getWidth(), (long) size.getHeight(), 8, 0, colorSpace, new CGBitmapInfo(CGBitmapInfo.ByteOrderDefault.value() | CGImageAlphaInfo.None.value())); // TODO // easier // Start with a mask that's entirely transparent maskContext.setFillColor(UIColor.black().getCGColor()); maskContext.fillRect(new CGRect(0, 0, size.getWidth(), size.getHeight())); // Make the inner part (within the border) opaque maskContext.setFillColor(UIColor.white().getCGColor()); maskContext.fillRect(new CGRect(borderSize, borderSize, size.getWidth() - borderSize * 2, size.getHeight() - borderSize * 2)); // Get an image of the context CGImage maskImage = maskContext.toImage(); return maskImage; } /** * * @param image * @param bounds * @return a copy of this image that is cropped to the given bounds. The * bounds will be adjusted using CGRectIntegral. This method ignores * the image's imageOrientation setting. */ public static UIImage crop(UIImage image, CGRect bounds) { CGImage i = CGImage.createWithImageInRect(image.getCGImage(), bounds); UIImage croppedImage = new UIImage(i); return croppedImage; } /** * * @param image * @param thumbnailSize * @param borderSize * @param cornerRadius * @param quality * @return a copy of this image that is squared to the thumbnail size. If * transparentBorder is non-zero, a transparent border of the given * size will be added around the edges of the thumbnail. (Adding a * transparent border of at least one pixel in size has the * side-effect of antialiasing the edges of the image when rotating * it using Core Animation.) */ public static UIImage createThumbnail(UIImage image, int thumbnailSize, int borderSize, int cornerRadius, CGInterpolationQuality quality) { UIImage resizedImage = resize(image, UIViewContentMode.ScaleAspectFill, new CGSize(thumbnailSize, thumbnailSize), quality); // Crop out any part of the image that's larger than the thumbnail size // The cropped rect must be centered on the resized image // Round the origin points so that the size isn't altered when // CGRectIntegral is later invoked CGRect cropRect = new CGRect(Math.round((resizedImage.getSize().getWidth() - thumbnailSize) / 2), Math.round((resizedImage.getSize().getHeight() - thumbnailSize) / 2), thumbnailSize, thumbnailSize); UIImage croppedImage = crop(resizedImage, cropRect); UIImage transparentBorderImage = borderSize != 0 ? addTransparentBorder(croppedImage, borderSize) : croppedImage; return createRoundedCornerImage(transparentBorderImage, cornerRadius, borderSize); } /** * * @param image * @param newSize * @param quality * @return a rescaled copy of the image, taking into account its orientation * The image will be scaled disproportionately if necessary to fit * the bounds specified by the parameter */ public static UIImage resize(UIImage image, CGSize newSize, CGInterpolationQuality quality) { boolean drawTransposed; switch (image.getOrientation()) { case Left: case LeftMirrored: case Right: case RightMirrored: drawTransposed = true; break; default: drawTransposed = false; break; } return resize(image, newSize, getTransformForOrientation(image, newSize), drawTransposed, quality); } /** * Resizes the image according to the given content mode, taking into * account the image's orientation * * @param image * @param contentMode * @param bounds * @param quality * @return */ public static UIImage resize(UIImage image, UIViewContentMode contentMode, CGSize bounds, CGInterpolationQuality quality) { double horizontalRatio = bounds.getWidth() / image.getSize().getWidth(); double verticalRatio = bounds.getHeight() / image.getSize().getHeight(); double ratio; switch (contentMode) { case ScaleAspectFill: ratio = Math.max(horizontalRatio, verticalRatio); break; case ScaleAspectFit: ratio = Math.min(horizontalRatio, verticalRatio); break; default: throw new IllegalArgumentException("Unsupported content mode: " + contentMode); } CGSize newSize = new CGSize(image.getSize().getWidth() * ratio, image.getSize().getHeight() * ratio); return resize(image, newSize, quality); } /** * * @param image * @param newSize * @param transform * @param transpose * @param quality * @return a copy of the image that has been transformed using the given * affine transform and scaled to the new size The new image's * orientation will be UIImageOrientationUp, regardless of the * current image's orientation If the new size is not integral, it * will be rounded up */ private static UIImage resize(UIImage image, CGSize newSize, CGAffineTransform transform, boolean transpose, CGInterpolationQuality quality) { CGRect newRect = new CGRect(0, 0, newSize.getWidth(), newSize.getHeight()).integral(); CGRect transposedRect = new CGRect(0, 0, newRect.getSize().getHeight(), newRect.getSize().getWidth()); CGImage i = image.getCGImage(); // Build a context that's the same dimensions as the new size CGBitmapContext bitmap = CGBitmapContext.create((long) newRect.getSize().getWidth(), (long) newRect.getSize() .getHeight(), i.getBitsPerComponent(), 0, i.getColorSpace(), i.getBitmapInfo()); // Rotate and/or flip the image if required by its orientation bitmap.concatCTM(transform); // Set the quality level to use when rescaling bitmap.setInterpolationQuality(quality); // Draw into the context; this scales the image bitmap.drawImage(transpose ? transposedRect : newRect, i); // Get the resized image from the context and a UIImage CGImage ni = bitmap.toImage(); UIImage newImage = new UIImage(ni); return newImage; } /** * * @param image * @param newSize * @return an affine transform that takes into account the image orientation * when drawing a scaled image */ private static CGAffineTransform getTransformForOrientation(UIImage image, CGSize newSize) { CGAffineTransform transform = CGAffineTransform.Identity(); switch (image.getOrientation()) { case Down: // EXIF = 3 case DownMirrored: // EXIF = 4 transform = transform.translate(newSize.getWidth(), newSize.getHeight()); transform = transform.rotate(Math.PI); break; case Left: // EXIF = 6 case LeftMirrored: // EXIF = 5 transform = transform.translate(newSize.getWidth(), 0); transform = transform.rotate(Math.PI / 2); break; case Right: // EXIF = 8 case RightMirrored: // EXIF = 7 transform = transform.translate(0, newSize.getHeight()); transform.rotate(-Math.PI / 2); break; default: break; } switch (image.getOrientation()) { case UpMirrored: // EXIF = 2 case DownMirrored: // EXIF = 4 transform = transform.translate(newSize.getWidth(), 0); transform = transform.scale(-1, 1); break; case LeftMirrored: // EXIF = 5 case RightMirrored: // EXIF = 7 transform = transform.translate(newSize.getHeight(), 0); transform = transform.scale(-1, 1); default: break; } return transform; } /** * Creates a copy of this image with rounded corners If borderSize is * non-zero, a transparent border of the given size will also be added * Original author: Björn Sållarp. Used with permission. See: * http://blog.sallarp.com/iphone-uiimage-round-corners/ * * @param image * @param cornerSize * @param borderSize * @return */ private static UIImage createRoundedCornerImage(UIImage image, int cornerSize, int borderSize) { // If the image does not have an alpha layer, add one image = addAlpha(image); // Build a context that's the same dimensions as the new size CGImage i = image.getCGImage(); CGBitmapContext context = CGBitmapContext.create((long) image.getSize().getWidth(), (long) image.getSize() .getHeight(), i.getBitsPerComponent(), 0, i.getColorSpace(), i.getBitmapInfo()); // Create a clipping path with rounded corners context.beginPath(); addRoundedRectToPath(new CGRect(borderSize, borderSize, image.getSize().getWidth() - borderSize * 2, image .getSize().getHeight() - borderSize * 2) , context, cornerSize, cornerSize); context.closePath(); context.clip(); // Draw the image to the context; the clipping path will make anything // outside the rounded rect transparent context.drawImage(new CGRect(0, 0, image.getSize().getWidth(), image.getSize().getHeight()), i); // Create a CGImage from the context CGImage clippedImage = context.toImage(); // Create a UIImage from the CGImage UIImage roundedImage = new UIImage(clippedImage); return roundedImage; } /** * Adds a rectangular path to the given context and rounds its corners by * the given extents Original author: Björn Sållarp. Used with permission. * See: http://blog.sallarp.com/iphone-uiimage-round-corners/ * * @param rect * @param context * @param ovalWidth * @param ovalHeight */ private static void addRoundedRectToPath(CGRect rect, CGContext context, double ovalWidth, double ovalHeight) { if (ovalWidth == 0 || ovalHeight == 0) { context.addRect(rect); return; } context.saveGState(); context.translateCTM(rect.getMinX(), rect.getMinY()); context.scaleCTM(ovalWidth, ovalHeight); double fw = rect.getWidth() / ovalWidth; double fh = rect.getHeight() / ovalHeight; context.moveToPoint(fw, fh / 2); context.addArcToPoint(fw, fh, fw / 2, fh, 1); context.addArcToPoint(0, fh, 0, fh / 2, 1); context.addArcToPoint(0, 0, fw / 2, 0, 1); context.addArcToPoint(fw, 0, fw, fh / 2, 1); context.closePath(); context.restoreGState(); } }
40.441176
131
0.627515
7a903cd26e0277583b4bda5e06812ee5d7c89c07
3,354
/* * 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 michid.crdt; import static michid.crdt.plugins.LWWEditor.LWW_UPDATE; import static michid.crdt.plugins.LWWEditor.LWW_VALUE; import static michid.crdt.plugins.LWWEditor.MIX_LWW_REGISTER; import static michid.crdt.plugins.LWWEditor.MIX_LWW_REGISTER_CND; import static org.junit.Assert.assertEquals; import java.io.IOException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import michid.crdt.plugins.LWWEditorProvider; import org.apache.jackrabbit.commons.cnd.ParseException; import org.apache.jackrabbit.oak.jcr.Jcr; import org.junit.Before; import org.junit.Test; public class LWWTest extends TestBase { @Before public void setup() throws RepositoryException, IOException, ParseException { Session session = createAdminSession(); try { registerNodeType(session, MIX_LWW_REGISTER_CND); Node root = session.getRootNode(); Node lww = root.addNode("lww"); lww.addMixin(MIX_LWW_REGISTER); session.save(); } finally { session.logout(); } } @Override protected Jcr initJcr(Jcr jcr) { return jcr.with(new LWWEditorProvider()); } @Test public void noConflict() throws RepositoryException { Session s1 = createAdminSession(); try { s1.getNode("/lww").setProperty(LWW_UPDATE + '1', 1); s1.save(); } finally { s1.logout(); } Session s2 = createAdminSession(); try { s2.getNode("/lww").setProperty(LWW_UPDATE + '2', 2); s2.save(); } finally { s2.logout(); } Session session = createAdminSession(); try { assertEquals(2L, session.getProperty("/lww/" + LWW_VALUE).getLong()); } finally { session.logout(); } } @Test public void conflict() throws RepositoryException { Session s1 = createAdminSession(); Session s2 = createAdminSession(); try { s1.getNode("/lww").setProperty(LWW_UPDATE + '1', "one"); s1.save(); s2.getNode("/lww").setProperty(LWW_UPDATE + '2', "two"); s2.save(); } finally { s1.logout(); s2.logout(); } Session session = createAdminSession(); try { assertEquals("two", session.getProperty("/lww/" + LWW_VALUE).getString()); } finally { session.logout(); } } }
30.216216
86
0.634168
19705ae772426606940ca012a5c3b592f52e1f02
405
package com.dute7liang.pay.tool.ali.core.common; import com.dute7liang.pay.tool.ali.bean.AliTransferTrade; import java.util.Map; /** * 支付宝转账业务参数封装 * @Auther: yangyuan * @Date: 2019/1/15 13:52 */ public interface AliTransferBizOptions extends AliBizOptions{ /** * 构造转账业务参数 * @param aliTransferTrade */ Map<String ,String> buildBizParams(AliTransferTrade aliTransferTrade); }
20.25
74
0.720988
0dc9ab6cc290548f41e45a554d0465d45221cca6
2,968
package gov.wa.wsdot.android.wsdot.ui.myroute.newroute; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import gov.wa.wsdot.android.wsdot.R; public class TrackingRouteDialogFragment extends DialogFragment implements View.OnClickListener { public interface TrackingRouteDialogListener { void onFinishTrackingDialog(); } public TrackingRouteDialogFragment() { // Empty constructor is required for DialogFragment // Make sure not to add arguments to the constructor // Use `newInstance` instead as shown below } public static TrackingRouteDialogFragment newInstance(String title) { TrackingRouteDialogFragment frag = new TrackingRouteDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); frag.setArguments(args); return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_tracking_route, container); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); addOnClickListeners(); // Fetch arguments from bundle and set title String title = getArguments().getString("title", "Enter Name"); getDialog().setTitle(title); } @Override public void onClick(View v) { if (v.getId() == R.id.finish_button) { // show confirm showConfirmView(); } else if (v.getId() == R.id.confirm_finish_button) { TrackingRouteDialogListener listener = (TrackingRouteDialogListener) getActivity(); listener.onFinishTrackingDialog(); dismiss(); } else if (v.getId() == R.id.cancel_button) { // hide confirm showTrackingView(); } } private void showConfirmView() { getView().findViewById(R.id.confirm_view).setVisibility(View.VISIBLE); getView().findViewById(R.id.tracking_view).setVisibility(View.GONE); } private void showTrackingView() { getView().findViewById(R.id.confirm_view).setVisibility(View.GONE); getView().findViewById(R.id.tracking_view).setVisibility(View.VISIBLE); } private void addOnClickListeners() { Button finishButton = getView().findViewById(R.id.finish_button); finishButton.setOnClickListener(this); Button confirmFinishButton = getView().findViewById(R.id.confirm_finish_button); confirmFinishButton.setOnClickListener(this); Button cancelButton = getView().findViewById(R.id.cancel_button); cancelButton.setOnClickListener(this); } }
34.511628
97
0.684636
0c3618e0b9841d09853d33491278133d1cf77df3
565
package qwe.qweqwe.texteditor.w0.c; import java.util.List; /* compiled from: lambda */ public final /* synthetic */ class a implements Runnable { /* renamed from: b reason: collision with root package name */ private final /* synthetic */ f f9794b; /* renamed from: c reason: collision with root package name */ private final /* synthetic */ List f9795c; public /* synthetic */ a(f fVar, List list) { this.f9794b = fVar; this.f9795c = list; } public final void run() { this.f9794b.a(this.f9795c); } }
24.565217
67
0.630088
1c5c57998dc764fe120875fbae836242ac9135a7
1,882
package org.firstinspires.ftc.teamcode.Vision; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvInternalCamera; @Autonomous(name="ImplementedCV", group="Autonomous") public class ImplementedCV extends LinearOpMode { OpenCvInternalCamera phoneCam; CVLinearOpMode pipeline; public void runOpMode(){ int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); phoneCam = OpenCvCameraFactory.getInstance().createInternalCamera(OpenCvInternalCamera.CameraDirection.BACK, cameraMonitorViewId); pipeline = new CVLinearOpMode(); phoneCam.setPipeline(pipeline); // We set the viewport policy to optimized view so the preview doesn't appear 90 deg // out when the RC activity is in portrait. We do our actual image processing assuming // landscape orientation, though. phoneCam.setViewportRenderingPolicy(OpenCvCamera.ViewportRenderingPolicy.OPTIMIZE_VIEW); phoneCam.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { phoneCam.startStreaming(320,240, OpenCvCameraRotation.SIDEWAYS_LEFT); } }); while (!opModeIsActive() && !isStopRequested()) { telemetry.addData("Analysis", pipeline.getAnalysis()); telemetry.addData("Position", pipeline.position); telemetry.update(); // Don't burn CPU cycles busy-looping in this sample sleep(50); } } }
34.851852
156
0.712009
04638127005b5d6ade42e809cc0932dbbd6f2a76
3,220
package net.mchs_u.mc.aiwolf.common.starter.component; import java.awt.GridLayout; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.JFrame; import org.aiwolf.common.data.Agent; import org.aiwolf.common.net.GameInfo; import org.aiwolf.common.net.GameSetting; import net.mchs_u.mc.aiwolf.common.AbstractEstimate; import net.mchs_u.mc.aiwolf.common.EstimatePlayer; public class DebugVisualizePlayer implements EstimatePlayer { private EstimatePlayer player; private JFrame frame = null; private List<EstimateGraph> estimateGraphs = null; public DebugVisualizePlayer(EstimatePlayer player) { this.player = player; } public String getName() { return player.getName(); } public void update(GameInfo gameInfo) { player.update(gameInfo); debugEstimateRefresh(); } public void initialize(GameInfo gameInfo, GameSetting gameSetting) { player.initialize(gameInfo, gameSetting); estimateGraphs = new ArrayList<>(); for(int i = 0; i < 3; i++) estimateGraphs.add(new EstimateGraph(gameSetting.getPlayerNum())); frame = new JFrame("debug"); frame.setSize(400, 800); frame.setLocation(1030, 0); GridLayout gl = new GridLayout(3,1); gl.setVgap(50); frame.setLayout(gl); for(EstimateGraph eg: estimateGraphs) frame.add(eg); frame.setVisible(true); debugEstimateRefresh(); } public void dayStart() { player.dayStart(); } public String talk() { return player.talk(); } public String whisper() { return player.whisper(); } public Agent vote() { return player.vote(); } public Agent attack() { return player.attack(); } public Agent divine() { return player.divine(); } public Agent guard() { return player.guard(); } public void finish() { player.finish(); debugEstimateRefresh(); frame.dispose(); } public AbstractEstimate getObjectiveEstimate() { return player.getObjectiveEstimate(); } public AbstractEstimate getSubjectiveEstimate() { return player.getSubjectiveEstimate(); } public AbstractEstimate getPretendVillagerEstimate() { return player.getPretendVillagerEstimate(); } private void debugEstimateRefresh(){ estimateGraphs.get(0).refreshVillagerTeamLikeness(player.getSubjectiveEstimate().getVillagerTeamLikeness()); estimateGraphs.get(0).refreshWerewolfLikeness(player.getSubjectiveEstimate().getWerewolfLikeness()); estimateGraphs.get(1).refreshVillagerTeamLikeness(player.getObjectiveEstimate().getVillagerTeamLikeness()); estimateGraphs.get(1).refreshWerewolfLikeness(player.getObjectiveEstimate().getWerewolfLikeness()); Map<Agent, Double> v = player.getObjectiveEstimate().getVillagerTeamLikeness(); Map<Agent, Double> w = player.getObjectiveEstimate().getWerewolfLikeness(); for(Agent a: v.keySet()) { System.out.println(a + ", " + (1 - v.get(a) - w.get(a)) + ", " + v.get(a) + ", " + w.get(a)); } estimateGraphs.get(2).refreshVillagerTeamLikeness(player.getPretendVillagerEstimate().getVillagerTeamLikeness()); estimateGraphs.get(2).refreshWerewolfLikeness(player.getPretendVillagerEstimate().getWerewolfLikeness()); } @Override public Agent getVoteTarget() { return player.getVoteTarget(); } }
25.15625
115
0.740062
b41cf79f6c8eb980c8ab0dff6d14b9e79cdc660e
814
package de.atennert.homectrl.registration; import java.util.Set; public interface IHostAddressBook { /** * Returns the host information belonging to an deviceId. * * @param deviceId * @return */ DataDescription getHostInformation( int deviceId ); /** * Get the devices of a host, identified by the hosts address and the IDs of * the data fields / devices on the host. * * @param senderAddress * address of the host node, that has send information * @param referenceIds * data field IDs of devices on the host node * @return the homectrl device descriptions of all identified (registered) * devices */ Set<DataDescription> getHostDevices( String senderAddress, Set<String> referenceIds ); }
29.071429
90
0.652334
fb71f02daaf7c9df025704ac9aa59fec1f1b0562
531
package com.christophecvb.elitedangerous.events.combat; import com.christophecvb.elitedangerous.events.Event; public class BountySkimmerEvent extends BountyEvent { public String faction; public Long reward; public interface Listener extends Event.Listener { @Override default <T extends Event> void onTriggered(T event) { this.onBountySkimmerEventTriggered((BountySkimmerEvent) event); } void onBountySkimmerEventTriggered(BountySkimmerEvent bountySkimmerEvent); } }
29.5
82
0.743879
c4c7852d3f5068ee3587f36d1f1f15bb2b657b74
11,569
package com.drive.admin.repository.impl; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.SecureUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.drive.admin.pojo.dto.ServiceInfoEditParam; import com.drive.admin.pojo.dto.ServiceInfoPageQueryParam; import com.drive.admin.pojo.entity.ServiceInfoEntity; import com.drive.admin.pojo.vo.ServiceInfoVo; import com.drive.admin.repository.ServiceInfoRepository; import com.drive.admin.service.AreaService; import com.drive.admin.service.ServiceInfoService; import com.drive.admin.service.mapstruct.ServiceInfoMapStruct; import com.drive.common.core.base.BaseController; import com.drive.common.core.biz.R; import com.drive.common.core.biz.ResObject; import com.drive.common.core.biz.SubResultCode; import com.drive.common.core.utils.BeanConvertUtils; import com.drive.common.data.utils.ExcelUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * * 客服人员信息表 服务类 * * @author xiaoguo */ @Slf4j @Service public class ServiceInfoRepositoryImpl extends BaseController<ServiceInfoPageQueryParam, ServiceInfoEntity> implements ServiceInfoRepository{ @Autowired private ServiceInfoService serviceInfoService; @Autowired private ServiceInfoMapStruct serviceInfoMapStruct; @Autowired private AreaService areaService; /* * *功能描述 * @author xiaoguo * @description 客服人员信息表 分页列表 * @date 2020/2/12 17:09 * @param * @param ServiceInfoPageQueryParam * @return */ @Override public ResObject pageList(ServiceInfoPageQueryParam param) { log.info(this.getClass() + "pageList-方法请求参数{}",param); Page<ServiceInfoEntity> page = new Page<>(param.getPageNum(), param.getPageSize()); QueryWrapper queryWrapper = this.getQueryWrapper(serviceInfoMapStruct, param); // 客服姓名模糊查询 queryWrapper.like(StrUtil.isNotEmpty(param.getVagueRealNameSearch()),"real_name",param.getVagueRealNameSearch()); // 手机号 模糊查询 queryWrapper.like(StrUtil.isNotEmpty(param.getVaguePhoneSearch()),"phone",param.getVaguePhoneSearch()); // 登录账户模糊查询 queryWrapper.like(StrUtil.isNotEmpty(param.getVagueLoginAccountSearch()),"login_account",param.getVagueLoginAccountSearch()); //queryWrapper.apply(StrUtil.isNotBlank(param.getBeSpeakMeetTimeSearch()), // "date_format (be_speak_meet_time,'%Y-%m-%d') = date_format('" + param.getBeSpeakMeetTimeSearch() + "','%Y-%m-%d')"); // 开始时间 结束时间都有才进入 if (StrUtil.isNotEmpty(param.getBeginTime()) && StrUtil.isNotEmpty(param.getEndTime())){ queryWrapper.between(StrUtil.isNotEmpty(param.getBeginTime()),"create_time",param.getBeginTime(),param.getEndTime()); } IPage<ServiceInfoEntity> pageList = serviceInfoService.page(page,queryWrapper); if (pageList.getRecords().size() <=0){ log.error("数据空"); return R.success(SubResultCode.DATA_NULL.subCode(),SubResultCode.DATA_NULL.subMsg(),pageList); } Page<ServiceInfoVo> serviceInfoVoPage = serviceInfoMapStruct.toVoList(pageList); /* serviceInfoVoPage.getRecords().stream().forEach((item) ->{ // 省市区 if (StrUtil.isNotEmpty(item.getProvinceId()))item.setProvinceName(areaService.getByBaCode(item.getProvinceId()).getBaName()); if (StrUtil.isNotEmpty(item.getCityId()))item.setCityName(areaService.getByBaCode(item.getCityId()).getBaName()); if (StrUtil.isNotEmpty(item.getAreaId()))item.setAreaName(areaService.getByBaCode(item.getAreaId()).getBaName()); });*/ log.info(this.getClass() + "pageList-方法请求结果{}",serviceInfoVoPage); return R.success(serviceInfoVoPage); } @Override public ResObject findList(ServiceInfoPageQueryParam param) { log.info(this.getClass() + "findList-方法请求参数{}",param); // 这里判断条件进行查询 QueryWrapper queryWrapper= this.getQueryWrapper(serviceInfoMapStruct, param); // 如 queryWrapper.eq(StrUtil.isNotEmpty(param.getPhone()),"phone",param.getPhone()); List<ServiceInfoEntity> pageList = serviceInfoService.list(queryWrapper); if (pageList == null){ log.error("数据空"); return R.success(SubResultCode.DATA_NULL.subCode(),SubResultCode.DATA_NULL.subMsg(),pageList); } List<ServiceInfoVo> serviceInfoVoList = serviceInfoMapStruct.toVoList(pageList); log.info(this.getClass() + "findList-方法请求结果{}",serviceInfoVoList); return R.success(serviceInfoVoList); } @Override public ResObject getInfo(ServiceInfoPageQueryParam param) { return null; } /** * *通过ID获取客服人员信息表 列表 **/ @Override public ResObject getById(String id) { log.info(this.getClass() + "getInfo-方法请求参数{}",id); if (StrUtil.isEmpty(id)){ return R.failure("数据空"); } ServiceInfoEntity serviceInfo = serviceInfoService.getById(id); ServiceInfoVo serviceInfoVo = BeanConvertUtils.copy(serviceInfo, ServiceInfoVo.class); log.info(this.getClass() + "getInfo-方法请求结果{}",serviceInfoVo); if (serviceInfoVo ==null){ log.error("活动数据对象空"); return R.success(SubResultCode.DATA_NULL.subCode(),SubResultCode.DATA_NULL.subMsg()); } return R.success(serviceInfoVo); } /** * *保存客服人员信息表 信息 **/ @Override public ResObject save(ServiceInfoEditParam installParam) { log.info(this.getClass() + "save方法请求参数{}",installParam); if (installParam == null){ log.error("数据空"); return R.failure(SubResultCode.PARAMISBLANK.subCode(),SubResultCode.PARAMISBLANK.subMsg()); } // 校验手机 QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("login_account",installParam.getLoginAccount()); queryWrapper.eq("operator_id",installParam.getOperatorId()); int count = serviceInfoService.count(queryWrapper); if (count >0){ return R.failure(SubResultCode.DATA_IDEMPOTENT.subCode(),SubResultCode.DATA_IDEMPOTENT.subMsg()); } // 密码加密 if (StrUtil.isNotEmpty(installParam.getPassword())){ String md5Password = SecureUtil.md5(installParam.getPassword()); installParam.setPassword(md5Password); } ServiceInfoEntity serviceInfo = BeanConvertUtils.copy(installParam, ServiceInfoEntity.class); Boolean result = serviceInfoService.save(serviceInfo); log.info(this.getClass() + "save-方法请求结果{}",result); // 判断结果 return result ?R.success(result):R.failure(result); } /** * *修改客服人员信息表 信息 **/ @Override public ResObject update(ServiceInfoEditParam updateParam) { log.info(this.getClass() + "update方法请求参数{}",updateParam); if (updateParam == null){ log.error("数据空"); return R.failure(SubResultCode.PARAMISBLANK.subCode(),SubResultCode.PARAMISBLANK.subMsg()); } // 密码加密 if (StrUtil.isNotEmpty(updateParam.getPassword())){ String md5Password = SecureUtil.md5(updateParam.getPassword()); updateParam.setPassword(md5Password); } ServiceInfoEntity serviceInfo = BeanConvertUtils.copy(updateParam, ServiceInfoEntity.class); Boolean result = serviceInfoService.updateById(serviceInfo); log.info(this.getClass() + "update-方法请求结果{}",result); // 判断结果 return result ?R.success(result):R.failure(result); } /** * *删除客服人员信息表 信息 **/ @Override public ResObject deleteByIds(String[] ids) { if (ids.length <= 0){ log.error("数据空"); return R.failure(SubResultCode.PARAMISBLANK.subCode(),SubResultCode.PARAMISBLANK.subMsg()); } return R.toRes(serviceInfoService.removeByIds(Arrays.asList(ids))); } /** * *通过id删除客服人员信息表 信息 **/ @Override public ResObject deleteById(String id) { log.info(this.getClass() + "deleteById-方法请求参数{}",id); if(StrUtil.isEmpty(id)){ log.error("ID数据空"); return R.failure(SubResultCode.PARAMISBLANK.subCode(),SubResultCode.PARAMISBLANK.subMsg()); } //QueryWrapper<String> queryWrapper = new QueryWrapper<String>(); //queryWrapper.eq(StrUtil.isNotEmpty(id),"id",id); Boolean result = serviceInfoService.removeById(id); log.info(this.getClass() + "deleteById-方法请求结果{}",result); // 判断结果 return result ?R.success(result):R.failure(result); } /** * *导出客服人员信息表 信息 **/ @Override public ResObject exportXls(ServiceInfoPageQueryParam param, HttpServletResponse response)throws IOException { log.info(this.getClass() + "exportXls方法请求参数{}",param); QueryWrapper queryWrapper = this.getQueryWrapper(serviceInfoMapStruct, param); List<ServiceInfoEntity> list = serviceInfoService.list(queryWrapper); List<ServiceInfoVo>serviceInfoList = serviceInfoMapStruct.toVoList(list); ExcelUtils.exportExcel(serviceInfoList, ServiceInfoVo.class, "", new ExportParams(), response); return R.success("导出成功"); } /** * *修改状态 **/ @Override public ResObject changeStatus(ServiceInfoEditParam param) { log.info(this.getClass() + "changeStatus方法请求参数{}",param); if (StrUtil.isEmpty(param.getId())){ log.error("ID数据空"); return R.failure(SubResultCode.PARAMISBLANK.subCode(),SubResultCode.PARAMISBLANK.subMsg()); } ServiceInfoEntity ServiceInfoEntity = new ServiceInfoEntity(); ServiceInfoEntity.setId(param.getId()); ServiceInfoEntity.setStatus(param.getStatus()); //ServiceInfoEntity.setUpdateTime() Boolean result = serviceInfoService.updateById(ServiceInfoEntity); log.info(this.getClass() +"changeStatus方法请求对象参数{},请求结果{}",ServiceInfoEntity,result); // 判断结果 return result ?R.success(result):R.failure(result); } @Override public ResObject resetPwd(ServiceInfoEditParam serviceInfoEditParam) { log.info(this.getClass() + "resetPwd-方法请求参数{}",serviceInfoEditParam); if (StrUtil.isEmpty(serviceInfoEditParam.getId())){ return R.failure(SubResultCode.PARAMISBLANK.subCode(),SubResultCode.PARAMISBLANK.subMsg()); } if (StrUtil.isEmpty(serviceInfoEditParam.getPassword())){ return R.failure(SubResultCode.PARAMISBLANK.subCode(),SubResultCode.PARAMISBLANK.subMsg()); } String md5Password = SecureUtil.md5(serviceInfoEditParam.getPassword()); ServiceInfoEntity serviceInfoEntity = serviceInfoMapStruct.toEntity(serviceInfoEditParam); serviceInfoEntity.setPassword(md5Password); Boolean updateResult = serviceInfoService.updateById(serviceInfoEntity); if (!updateResult){ return R.failure(SubResultCode.DATA_UPDATE_FAILL.subCode(),SubResultCode.DATA_UPDATE_FAILL.subMsg()); } return R.success(updateResult); } }
43.007435
143
0.67992
c858f055c6f43fb89890eb4fe99d69a55799d214
211
package com.example.asteroids; import javafx.application.Application; import javafx.stage.Stage; public class Main extends Application{ public void start(Stage stage){ new MainMenu(stage); } }
19.181818
38
0.739336
4bfdc90c7224840ab68b532356066a6da289d1ff
3,459
package com.gentics.mesh.core.data.root.impl; import static com.gentics.mesh.core.data.perm.InternalPermission.READ_PERM; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_ROLE; import static com.gentics.mesh.core.rest.error.Errors.error; import static com.gentics.mesh.madl.index.EdgeIndexDefinition.edgeIndex; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import com.gentics.madl.index.IndexHandler; import com.gentics.madl.type.TypeHandler; import com.gentics.mesh.context.BulkActionContext; import com.gentics.mesh.context.InternalActionContext; import com.gentics.mesh.core.data.Group; import com.gentics.mesh.core.data.Role; import com.gentics.mesh.core.data.generic.MeshVertexImpl; import com.gentics.mesh.core.data.impl.GroupImpl; import com.gentics.mesh.core.data.impl.RoleImpl; import com.gentics.mesh.core.data.page.Page; import com.gentics.mesh.core.data.page.impl.DynamicTransformablePageImpl; import com.gentics.mesh.core.data.root.RoleRoot; import com.gentics.mesh.core.data.user.HibUser; import com.gentics.mesh.core.rest.role.RoleResponse; import com.gentics.mesh.event.EventQueueBatch; import com.gentics.mesh.parameter.PagingParameters; import com.syncleus.ferma.traversals.VertexTraversal; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @see RoleRoot */ public class RoleRootImpl extends AbstractRootVertex<Role> implements RoleRoot { private static final Logger log = LoggerFactory.getLogger(RoleRootImpl.class); /** * Initialize the vertex type and index. * * @param type * @param index */ public static void init(TypeHandler type, IndexHandler index) { type.createVertexType(RoleRootImpl.class, MeshVertexImpl.class); index.createIndex(edgeIndex(HAS_ROLE).withInOut().withOut()); } @Override public Class<? extends Role> getPersistanceClass() { return RoleImpl.class; } @Override public String getRootLabel() { return HAS_ROLE; } @Override public void addRole(Role role) { if (log.isDebugEnabled()) { log.debug("Adding role {" + role.getUuid() + ":" + role.getName() + "#" + role.id() + "} to roleRoot {" + id() + "}"); } addItem(role); } @Override public void removeRole(Role role) { // TODO delete the role? unlink from all groups? how is ferma / blueprint handling this. Neo4j would explode when trying to remove a node that still has // connecting edges. removeItem(role); } @Override public long globalCount() { return db().count(RoleImpl.class); } @Override public void delete(BulkActionContext bac) { throw error(INTERNAL_SERVER_ERROR, "The global role root can't be deleted."); } @Override public Page<? extends Group> getGroups(Role role, HibUser user, PagingParameters pagingInfo) { VertexTraversal<?, ?, ?> traversal = role.out(HAS_ROLE); return new DynamicTransformablePageImpl<Group>(user, traversal, pagingInfo, READ_PERM, GroupImpl.class); } /** * Create a new role vertex. */ public Role create() { return getGraph().addFramedVertex(RoleImpl.class); } @Override public Role create(InternalActionContext ac, EventQueueBatch batch, String uuid) { throw new RuntimeException("Wrong invocation. Use Dao instead."); } @Override public RoleResponse transformToRestSync(Role element, InternalActionContext ac, int level, String... languageTags) { throw new RuntimeException("Wrong invocation. Use Dao instead."); } }
32.327103
154
0.766117
bc81e078525b9df2220a1990ba66e1d1ac15f14e
304
package pl.sdacademy.zdjavapol33.java.zaawansowana.programowanie.funkcyjne.interfejs; /** * @author : Jakub Olszewski [http://github.com/jakub-olszewski] * @project : ZDJAVApol33 * @since : 19.09.2020 **/ public class InterfejsFunkcyjnyMain { public static void main(String[] args) { } }
20.266667
85
0.713816
59bbeaa74d821b32b17497a74773edc3cad2ecdc
23,105
// // ======================================================================== // Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.start; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ConfigTest { private void assertEquals(String msg, Classpath expected, Classpath actual) { Assert.assertNotNull(msg + " : expected classpath should not be null",expected); Assert.assertNotNull(msg + " : actual classpath should not be null",actual); Assert.assertTrue(msg + " : expected should have an entry",expected.count() >= 1); Assert.assertTrue(msg + " : actual should have an entry",actual.count() >= 1); if (expected.count() != actual.count()) { expected.dump(System.err); actual.dump(System.err); Assert.assertEquals(msg + " : count",expected.count(),actual.count()); } List<File> actualEntries = Arrays.asList(actual.getElements()); List<File> expectedEntries = Arrays.asList(expected.getElements()); int len = expectedEntries.size(); for (int i = 0; i < len; i++) { File expectedFile = expectedEntries.get(i); File actualFile = actualEntries.get(i); if (!expectedFile.equals(actualFile)) { expected.dump(System.err); actual.dump(System.err); Assert.assertEquals(msg + ": entry [" + i + "]",expectedEntries.get(i),actualEntries.get(i)); } } } private void assertEquals(String msg, Collection<String> expected, Collection<String> actual) { Assert.assertTrue(msg + " : expected should have an entry",expected.size() >= 1); Assert.assertEquals(msg + " : size",expected.size(),actual.size()); for (String expectedVal : expected) { Assert.assertTrue(msg + " : should contain <" + expectedVal + ">",actual.contains(expectedVal)); } } private String getJettyEtcFile(String name) { File etc = new File(getTestableJettyHome(),"etc"); return new File(etc,name).getAbsolutePath(); } private File getJettyHomeDir() { return new File(getTestResourcesDir(),"jetty.home"); } private String getTestableJettyHome() { return getJettyHomeDir().getAbsolutePath(); } private File getTestResourcesDir() { File src = new File(System.getProperty("user.dir"),"src"); File test = new File(src,"test"); return new File(test,"resources"); } @Before public void reset() { Config.clearProperties(); } /* * Test for SUBJECT "/=" for assign canonical path */ @Test public void testSubjectAssignCanonicalPath() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("test.resources.dir/=src/test/resources\n"); Config cfg = new Config(); cfg.parse(buf); Assert.assertEquals(getTestResourcesDir().getCanonicalPath(),Config.getProperty("test.resources.dir")); } /* * Test for SUBJECT "~=" for assigning Start Properties */ @Test public void testSubjectAssignStartProperty() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("test.jetty.start.text~=foo\n"); buf.append("test.jetty.start.quote~=Eatagramovabits\n"); Config options = new Config(); options.parse(buf); Assert.assertEquals("foo",Config.getProperty("test.jetty.start.text")); Assert.assertEquals("Eatagramovabits",Config.getProperty("test.jetty.start.quote")); } /* * Test for SUBJECT "=" for assigning System Properties */ @Test public void testSubjectAssignSystemProperty() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("test.jetty.start.text=foo\n"); buf.append("test.jetty.start.quote=Eatagramovabits\n"); Config options = new Config(); options.parse(buf); Assert.assertEquals("foo",System.getProperty("test.jetty.start.text")); Assert.assertEquals("Eatagramovabits",System.getProperty("test.jetty.start.quote")); } /* * Test for SUBJECT ending with "/**", all jar and zip components in dir (deep, recursive) */ @Test public void testSubjectComponentDirDeep() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("$(jetty.home)/lib/**\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath actual = options.getClasspath(); Classpath expected = new Classpath(); File lib = new File(getJettyHomeDir(),"lib"); expected.addComponent(new File(lib,"core.jar")); expected.addComponent(new File(lib,"example.jar")); expected.addComponent(new File(lib,"http.jar")); expected.addComponent(new File(lib,"io.jar")); expected.addComponent(new File(lib,"JSR.ZIP")); expected.addComponent(new File(lib,"LOGGING.JAR")); expected.addComponent(new File(lib,"server.jar")); expected.addComponent(new File(lib,"spec.zip")); expected.addComponent(new File(lib,"util.jar")); expected.addComponent(new File(lib,"xml.jar")); File ext = new File(lib,"ext"); expected.addComponent(new File(ext,"custom-impl.jar")); File foo = new File(lib,"foo"); File bar = new File(foo,"bar"); expected.addComponent(new File(bar,"foobar.jar")); assertEquals("Components (Deep)",expected,actual); } /* * Test for SUBJECT ending with "/*", all jar and zip components in dir (shallow, no recursion) */ @Test public void testSubjectComponentDirShallow() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("# Example of any shallow components in /lib/\n"); buf.append("$(jetty.home)/lib/*\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath actual = options.getClasspath(); Classpath expected = new Classpath(); File lib = new File(getJettyHomeDir(),"lib"); expected.addComponent(new File(lib,"core.jar")); expected.addComponent(new File(lib,"example.jar")); expected.addComponent(new File(lib,"http.jar")); expected.addComponent(new File(lib,"io.jar")); expected.addComponent(new File(lib,"JSR.ZIP")); expected.addComponent(new File(lib,"LOGGING.JAR")); expected.addComponent(new File(lib,"server.jar")); expected.addComponent(new File(lib,"spec.zip")); expected.addComponent(new File(lib,"util.jar")); expected.addComponent(new File(lib,"xml.jar")); assertEquals("Components (Shallow)",expected,actual); } /* * Test for SUBJECT ending with ".class", a Main Class */ @Test public void testSubjectMainClass() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("org.eclipse.jetty.xml.XmlConfiguration.class"); Config options = new Config(); options.parse(buf); Assert.assertEquals("org.eclipse.jetty.xml.XmlConfiguration",options.getMainClassname()); } /* * Test for SUBJECT ending with ".class", a Main Class */ @Test public void testSubjectMainClassConditionalPropertySet() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("org.eclipse.jetty.xml.XmlConfiguration.class\n"); buf.append("${start.class}.class property start.class"); Config options = new Config(); options.setProperty("start.class","net.company.server.Start"); options.parse(buf); Assert.assertEquals("net.company.server.Start",options.getMainClassname()); } /* * Test for SUBJECT ending with ".class", a Main Class */ @Test public void testSubjectMainClassConditionalPropertyUnset() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("org.eclipse.jetty.xml.XmlConfiguration.class\n"); buf.append("${start.class}.class property start.class"); Config options = new Config(); // The "start.class" property is unset. options.parse(buf); Assert.assertEquals("org.eclipse.jetty.xml.XmlConfiguration",options.getMainClassname()); } /* * Test for SUBJECT ending with "/", a simple Classpath Entry */ @Test public void testSubjectSimpleComponent() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("$(jetty.home)/resources/\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath actual = options.getClasspath(); Classpath expected = new Classpath(); expected.addComponent(new File(getJettyHomeDir(),"resources")); assertEquals("Simple Component",expected,actual); } /* * Test for SUBJECT ending with "/", a simple Classpath Entry */ @Test public void testSubjectSimpleComponentMultiple() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("$(jetty.home)/resources/\n"); buf.append("$(jetty.home)/etc/\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath actual = options.getClasspath(); Classpath expected = new Classpath(); expected.addComponent(new File(getJettyHomeDir(),"resources")); expected.addComponent(new File(getJettyHomeDir(),"etc")); assertEquals("Simple Component",expected,actual); } /* * Test for SUBJECT ending with "/", a simple Classpath Entry */ @Test public void testSubjectSimpleComponentNotExists() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("$(jetty.home)/resources/\n"); buf.append("$(jetty.home)/foo/\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath actual = options.getClasspath(); Classpath expected = new Classpath(); expected.addComponent(new File(getJettyHomeDir(),"resources")); assertEquals("Simple Component",expected,actual); } /* * Test for SUBJECT ending with ".xml", an XML Configuration File */ @Test public void testSubjectXmlConfigAlt() throws IOException { StringBuffer buf = new StringBuffer(); // Doesn't exist buf.append("$(jetty.home)/etc/jetty.xml nargs == 0\n"); // test-alt does exist. buf.append("./src/test/resources/test-alt.xml nargs == 0 AND ! exists $(jetty.home)/etc/jetty.xml"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); List<String> actual = options.getXmlConfigs(); String expected = new File("src/test/resources/test-alt.xml").getAbsolutePath(); Assert.assertEquals("XmlConfig.size",1,actual.size()); Assert.assertEquals(expected,actual.get(0)); } /* * Test for SUBJECT ending with ".xml", an XML Configuration File */ @Test public void testSubjectXmlConfigDefault() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("$(jetty.home)/etc/test-jetty.xml nargs == 0\n"); buf.append("./jetty-server/src/main/config/etc/test-jetty.xml nargs == 0 AND ! exists $(jetty.home)/etc/test-jetty.xml"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); List<String> actual = options.getXmlConfigs(); String expected = getJettyEtcFile("test-jetty.xml"); Assert.assertEquals("XmlConfig.size",1,actual.size()); Assert.assertEquals(expected,actual.get(0)); } /* * Test for SUBJECT ending with ".xml", an XML Configuration File. */ @Test public void testSubjectXmlConfigMultiple() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("$(jetty.home)/etc/test-jetty.xml nargs == 0\n"); buf.append("$(jetty.home)/etc/test-jetty-ssl.xml nargs == 0\n"); buf.append("$(jetty.home)/etc/test-jetty-security.xml nargs == 0\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); List<String> actual = options.getXmlConfigs(); List<String> expected = new ArrayList<String>(); expected.add(getJettyEtcFile("test-jetty.xml")); expected.add(getJettyEtcFile("test-jetty-ssl.xml")); expected.add(getJettyEtcFile("test-jetty-security.xml")); assertEquals("Multiple XML Configs",expected,actual); } /* * Test Section Handling */ @Test public void testSectionClasspathSingle() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("[All]\n"); buf.append("$(jetty.home)/lib/core-test.jar\n"); buf.append("$(jetty.home)/lib/util.jar\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath defaultClasspath = options.getClasspath(); Assert.assertNotNull("Default Classpath should not be null",defaultClasspath); Classpath foocp = options.getSectionClasspath("Foo"); Assert.assertNull("Foo Classpath should not exist",foocp); Classpath allcp = options.getSectionClasspath("All"); Assert.assertNotNull("Classpath section 'All' should exist",allcp); File lib = new File(getJettyHomeDir(),"lib"); Classpath expected = new Classpath(); expected.addComponent(new File(lib,"core-test.jar")); expected.addComponent(new File(lib,"util.jar")); assertEquals("Single Classpath Section",expected,allcp); } /* * Test Section Handling */ @Test public void testSectionClasspathAvailable() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("[All]\n"); buf.append("$(jetty.home)/lib/core.jar ! available org.eclipse.jetty.dummy.Handler\n"); buf.append("$(jetty.home)/lib/util.jar ! available org.eclipse.jetty.dummy.StringUtils\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath defaultClasspath = options.getClasspath(); Assert.assertNotNull("Default Classpath should not be null",defaultClasspath); Classpath foocp = options.getSectionClasspath("Foo"); Assert.assertNull("Foo Classpath should not exist",foocp); Classpath allcp = options.getSectionClasspath("All"); Assert.assertNotNull("Classpath section 'All' should exist",allcp); File lib = new File(getJettyHomeDir(),"lib"); Classpath expected = new Classpath(); expected.addComponent(new File(lib,"core.jar")); expected.addComponent(new File(lib,"util.jar")); assertEquals("Single Classpath Section",expected,allcp); } /* * Test Section Handling, with multiple defined sections. */ @Test public void testSectionClasspathMultiples() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("# default\n"); buf.append("$(jetty.home)/lib/spec.zip\n"); buf.append("\n"); buf.append("[*]\n"); buf.append("$(jetty.home)/lib/io.jar\n"); buf.append("$(jetty.home)/lib/util.jar\n"); buf.append("\n"); buf.append("[All,server,default]\n"); buf.append("$(jetty.home)/lib/core.jar\n"); buf.append("$(jetty.home)/lib/server.jar\n"); buf.append("$(jetty.home)/lib/http.jar\n"); buf.append("\n"); buf.append("[All,xml,default]\n"); buf.append("$(jetty.home)/lib/xml.jar\n"); buf.append("\n"); buf.append("[All,logging]\n"); buf.append("$(jetty.home)/lib/LOGGING.JAR\n"); String jettyHome = getTestableJettyHome(); Config cfg = new Config(); cfg.setProperty("jetty.home",jettyHome); cfg.parse(buf); Classpath defaultClasspath = cfg.getClasspath(); Assert.assertNotNull("Default Classpath should not be null",defaultClasspath); Classpath foocp = cfg.getSectionClasspath("Foo"); Assert.assertNull("Foo Classpath should not exist",foocp); // Test if entire section list can be fetched Set<String> sections = cfg.getSectionIds(); Set<String> expected = new HashSet<String>(); expected.add(Config.DEFAULT_SECTION); expected.add("*"); expected.add("All"); expected.add("server"); expected.add("default"); expected.add("xml"); expected.add("logging"); assertEquals("Multiple Section IDs",expected,sections); // Test fetch of specific section by name works Classpath cpAll = cfg.getSectionClasspath("All"); Assert.assertNotNull("Classpath section 'All' should exist",cpAll); File lib = new File(getJettyHomeDir(),"lib"); Classpath expectedAll = new Classpath(); expectedAll.addComponent(new File(lib,"core.jar")); expectedAll.addComponent(new File(lib,"server.jar")); expectedAll.addComponent(new File(lib,"http.jar")); expectedAll.addComponent(new File(lib,"xml.jar")); expectedAll.addComponent(new File(lib,"LOGGING.JAR")); assertEquals("Classpath 'All' Section",expectedAll,cpAll); // Test combined classpath fetch of multiple sections works List<String> activated = new ArrayList<String>(); activated.add("server"); activated.add("logging"); Classpath cpCombined = cfg.getCombinedClasspath(activated); Classpath expectedCombined = new Classpath(); // from default expectedCombined.addComponent(new File(lib,"spec.zip")); // from 'server' expectedCombined.addComponent(new File(lib,"core.jar")); expectedCombined.addComponent(new File(lib,"server.jar")); expectedCombined.addComponent(new File(lib,"http.jar")); // from 'logging' expectedCombined.addComponent(new File(lib,"LOGGING.JAR")); // from '*' expectedCombined.addComponent(new File(lib,"io.jar")); expectedCombined.addComponent(new File(lib,"util.jar")); assertEquals("Classpath combined 'server,logging'",expectedCombined,cpCombined); } @Test public void testDynamicSection() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("[All,default,=$(jetty.home)/lib/*]\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath defaultClasspath = options.getClasspath(); Assert.assertNotNull("Default Classpath should not be null",defaultClasspath); Classpath foocp = options.getSectionClasspath("foo"); Assert.assertNotNull("Foo Classpath should not exist",foocp); Classpath allcp = options.getSectionClasspath("All"); Assert.assertNotNull("Classpath section 'All' should exist",allcp); Classpath extcp = options.getSectionClasspath("ext"); Assert.assertNotNull("Classpath section 'ext' should exist", extcp); Assert.assertEquals("Deep Classpath Section",0,foocp.count()); File lib = new File(getJettyHomeDir(),"lib"); File ext = new File(lib, "ext"); Classpath expected = new Classpath(); expected.addComponent(new File(ext,"custom-impl.jar")); assertEquals("Single Classpath Section",expected,extcp); } @Test public void testDeepDynamicSection() throws IOException { StringBuffer buf = new StringBuffer(); buf.append("[All,default,=$(jetty.home)/lib/**]\n"); String jettyHome = getTestableJettyHome(); Config options = new Config(); options.setProperty("jetty.home",jettyHome); options.parse(buf); Classpath defaultClasspath = options.getClasspath(); Assert.assertNotNull("Default Classpath should not be null",defaultClasspath); Classpath foocp = options.getSectionClasspath("foo"); Assert.assertNotNull("Foo Classpath should not exist",foocp); Classpath allcp = options.getSectionClasspath("All"); Assert.assertNotNull("Classpath section 'All' should exist",allcp); Classpath extcp = options.getSectionClasspath("ext"); Assert.assertNotNull("Classpath section 'ext' should exist", extcp); File lib = new File(getJettyHomeDir(),"lib"); Classpath expected = new Classpath(); File foo = new File(lib, "foo"); File bar = new File(foo, "bar"); expected.addComponent(new File(bar,"foobar.jar")); assertEquals("Deep Classpath Section",expected,foocp); File ext = new File(lib, "ext"); expected = new Classpath(); expected.addComponent(new File(ext,"custom-impl.jar")); assertEquals("Single Classpath Section",expected,extcp); } }
35.546154
130
0.629561