method2testcases
stringlengths 118
6.63k
|
---|
### Question:
LoginVM { public Boolean isRememberMe() { return rememberMe; } String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); Boolean isRememberMe(); void setRememberMe(Boolean rememberMe); @Override String toString(); }### Answer:
@Test public void isRememberMeTest(){ LoginVM vm = new LoginVM(); assertNull(vm.isRememberMe()); vm.setRememberMe(true); assertTrue(vm.isRememberMe()); }
|
### Question:
LoginVM { public void setRememberMe(Boolean rememberMe) { this.rememberMe = rememberMe; } String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); Boolean isRememberMe(); void setRememberMe(Boolean rememberMe); @Override String toString(); }### Answer:
@Test public void setRememberMeTest(){ LoginVM vm = new LoginVM(); assertNull(vm.isRememberMe()); vm.setRememberMe(null); assertNull(vm.isRememberMe()); vm.setRememberMe(true); assertTrue(vm.isRememberMe()); }
|
### Question:
LoginVM { @Override public String toString() { return "LoginVM{" + "username='" + username + '\'' + ", rememberMe=" + rememberMe + '}'; } String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); Boolean isRememberMe(); void setRememberMe(Boolean rememberMe); @Override String toString(); }### Answer:
@Test public void toStringTest(){ LoginVM vm = new LoginVM(); assertTrue(vm.toString().startsWith(LoginVM.class.getSimpleName())); String json = vm.toString().replace(LoginVM.class.getSimpleName(), ""); assertTrue(TestUtils.isValid(json)); vm = new LoginVM(); vm.setUsername("fakeUsername"); vm.setPassword("fakePassword"); vm.setRememberMe(true); json = vm.toString().replace(LoginVM.class.getSimpleName(), ""); assertTrue(TestUtils.isValid(json)); }
|
### Question:
UserVM { public String getLogin() { return login; } UserVM(); UserVM(String login, Set<String> authorities); String getLogin(); Set<String> getAuthorities(); @Override String toString(); }### Answer:
@Test public void getLoginTest() { UserVM vm = new UserVM(); assertNull(vm.getLogin()); vm = new UserVM("login", null); assertEquals("login", vm.getLogin()); }
|
### Question:
UserVM { public Set<String> getAuthorities() { return authorities; } UserVM(); UserVM(String login, Set<String> authorities); String getLogin(); Set<String> getAuthorities(); @Override String toString(); }### Answer:
@Test public void getAuthoritiesTest() throws Exception { UserVM vm = new UserVM(); assertNull(vm.getAuthorities()); Set<String> set = new HashSet<>(); set.add("authorities1"); set.add("authorities2"); vm = new UserVM("login", set); assertEquals(set, vm.getAuthorities()); }
|
### Question:
UserVM { @Override public String toString() { return "UserVM{" + "login='" + login + '\'' + ", authorities=" + authorities + "}"; } UserVM(); UserVM(String login, Set<String> authorities); String getLogin(); Set<String> getAuthorities(); @Override String toString(); }### Answer:
@Test public void toStringTest() throws Exception { UserVM vm = new UserVM(); assertTrue(vm.toString().startsWith(UserVM.class.getSimpleName())); String json = vm.toString().replace(UserVM.class.getSimpleName(), ""); assertTrue(TestUtils.isValid(json)); Set<String> set = new HashSet<>(); set.add("authorities1"); set.add("authorities2"); vm = new UserVM("fakeLogin",set); json = vm.toString().replace(UserVM.class.getSimpleName(), ""); assertTrue(TestUtils.isValid(json)); }
|
### Question:
WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(ConfigurableEmbeddedServletContainer container); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer:
@Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); }
@Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); }
|
### Question:
WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); mappings.add("html", "text/html;charset=utf-8"); mappings.add("json", "text/html;charset=utf-8"); container.setMimeMappings(mappings); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && container instanceof UndertowEmbeddedServletContainerFactory) { ((UndertowEmbeddedServletContainerFactory) container) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(ConfigurableEmbeddedServletContainer container); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer:
@Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); }
@Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); }
|
### Question:
WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); } if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties, HazelcastInstance hazelcastInstance); @Override void onStartup(ServletContext servletContext); @Override void customize(ConfigurableEmbeddedServletContainer container); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer:
@Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); }
@Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); }
|
### Question:
SnapshotCreationService { public void createSnapshotEvents(final String eventType, String filter) { final SnapshotEventGenerator snapshotEventGenerator = snapshotEventProviders.get(eventType); if (snapshotEventGenerator == null) { throw new UnknownEventTypeException(eventType); } Object lastProcessedId = null; do { final List<Snapshot> snapshots = snapshotEventGenerator.generateSnapshots(lastProcessedId, filter); if (snapshots.isEmpty()) { break; } for (final Snapshot snapshot : snapshots) { eventLogWriter.fireSnapshotEvent(eventType, snapshot.getDataType(), snapshot.getData()); lastProcessedId = snapshot.getId(); } } while (true); } SnapshotCreationService(List<SnapshotEventGenerator> snapshotEventGenerators,
EventLogWriter eventLogWriter); void createSnapshotEvents(final String eventType, String filter); Set<String> getSupportedEventTypes(); }### Answer:
@Test public void testCreateSnapshotEvents() { final String filter = "exampleFilter"; when(snapshotEventGenerator.generateSnapshots(null, filter)).thenReturn( singletonList(new Snapshot(1, PUBLISHER_DATA_TYPE, eventPayload))); snapshotCreationService.createSnapshotEvents(PUBLISHER_EVENT_TYPE, filter); verify(eventLogWriter).fireSnapshotEvent(eq(PUBLISHER_EVENT_TYPE), eq(PUBLISHER_DATA_TYPE), listEventLogCaptor.capture()); assertThat(listEventLogCaptor.getValue(), is(eventPayload)); }
@Test public void testSnapshotSavedInBatches() { final String filter = "exampleFilter2"; final List<Snapshot> eventPayloads = Fixture.mockSnapshotList(5); when(snapshotEventGenerator.generateSnapshots(null, filter)).thenReturn(eventPayloads.subList(0, 3)); when(snapshotEventGenerator.generateSnapshots(2, filter)).thenReturn(eventPayloads.subList(3, 5)); when(snapshotEventGenerator.generateSnapshots(4, filter)).thenReturn(emptyList()); snapshotCreationService.createSnapshotEvents(PUBLISHER_EVENT_TYPE, filter); verify(eventLogWriter, times(5)).fireSnapshotEvent(eq(PUBLISHER_EVENT_TYPE), eq(PUBLISHER_DATA_TYPE), isA(MockPayload.class)); }
|
### Question:
MockNakadiPublishingClient implements NakadiPublishingClient { public synchronized List<String> getSentEvents(String eventType) { ArrayList<String> events = new ArrayList<>(); List<String> sentEvents = this.sentEvents.get(eventType); if (sentEvents != null) { events.addAll(sentEvents); } return events; } MockNakadiPublishingClient(); MockNakadiPublishingClient(ObjectMapper objectMapper); @Override synchronized void publish(String eventType, List<?> nakadiEvents); synchronized List<String> getSentEvents(String eventType); synchronized void clearSentEvents(); }### Answer:
@Test public void returnsEmptyResultIfNoEventsHaveBeenSent() { assertThat(mockNakadiPublishingClient.getSentEvents("myEventType"), is(empty())); }
|
### Question:
EventBatcher { public void finish() { if (!batch.isEmpty()) { this.publisher.accept(batch); } } EventBatcher(ObjectMapper objectMapper, Consumer<List<BatchItem>> publisher); void pushEvent(EventLog eventLogEntry, NakadiEvent nakadiEvent); void finish(); }### Answer:
@Test public void shouldNotPublishEmptyBatches() { eventBatcher.finish(); verify(publisher, never()).accept(any()); }
|
### Question:
EventBatcher { public void pushEvent(EventLog eventLogEntry, NakadiEvent nakadiEvent) { long eventSize; try { eventSize = objectMapper.writeValueAsBytes(nakadiEvent).length; } catch (Exception e) { log.error("Could not serialize event {} of type {}, skipping it.", eventLogEntry.getId(), eventLogEntry.getEventType(), e); return; } if (!batch.isEmpty() && (hasAnotherEventType(batch, eventLogEntry) || batchWouldBecomeTooBig(aggregatedBatchSize, eventSize))) { this.publisher.accept(batch); batch = new ArrayList<>(); aggregatedBatchSize = 0; } batch.add(new BatchItem(eventLogEntry, nakadiEvent)); aggregatedBatchSize += eventSize; } EventBatcher(ObjectMapper objectMapper, Consumer<List<BatchItem>> publisher); void pushEvent(EventLog eventLogEntry, NakadiEvent nakadiEvent); void finish(); }### Answer:
@Test public void shouldPublishNonFilledBatchOnEventTypeChange() throws JsonProcessingException { EventLog eventLogEntry1 = eventLogEntry(1, "type1"); EventLog eventLogEntry2 = eventLogEntry(2, "type2"); NakadiEvent nakadiEvent1 = nakadiEvent("1"); NakadiEvent nakadiEvent2 = nakadiEvent("2"); when(objectMapper.writeValueAsBytes(any())).thenReturn(new byte[500]); eventBatcher.pushEvent(eventLogEntry1, nakadiEvent1); eventBatcher.pushEvent(eventLogEntry2, nakadiEvent2); verify(publisher).accept(eq(singletonList(new BatchItem(eventLogEntry1, nakadiEvent1)))); }
@Test public void shouldPublishFilledBatchOnSubmissionOfNewEvent() throws JsonProcessingException { EventLog eventLogEntry1 = eventLogEntry(1, "type1"); EventLog eventLogEntry2 = eventLogEntry(2, "type1"); EventLog eventLogEntry3 = eventLogEntry(3, "type1"); NakadiEvent nakadiEvent1 = nakadiEvent("1"); NakadiEvent nakadiEvent2 = nakadiEvent("2"); NakadiEvent nakadiEvent3 = nakadiEvent("3"); when(objectMapper.writeValueAsBytes(any())).thenReturn(new byte[15000000]); eventBatcher.pushEvent(eventLogEntry1, nakadiEvent1); eventBatcher.pushEvent(eventLogEntry2, nakadiEvent2); eventBatcher.pushEvent(eventLogEntry3, nakadiEvent3); verify(publisher) .accept(eq(asList( new BatchItem(eventLogEntry1, nakadiEvent1), new BatchItem(eventLogEntry2, nakadiEvent2) ))); }
@Test public void shouldTryPublishEventsIndividuallyWhenTheyExceedBatchThresholdThe() throws JsonProcessingException { EventLog eventLogEntry1 = eventLogEntry(1, "type1"); EventLog eventLogEntry2 = eventLogEntry(2, "type1"); NakadiEvent nakadiEvent1 = nakadiEvent("1"); NakadiEvent nakadiEvent2 = nakadiEvent("2"); when(objectMapper.writeValueAsBytes(any())) .thenReturn(new byte[45000000]) .thenReturn(new byte[450]); eventBatcher.pushEvent(eventLogEntry1, nakadiEvent1); eventBatcher.pushEvent(eventLogEntry2, nakadiEvent2); verify(publisher).accept(eq(singletonList(new BatchItem(eventLogEntry1, nakadiEvent1)))); }
|
### Question:
TracerFlowIdComponent implements FlowIdComponent { @Override public void startTraceIfNoneExists() { if (tracer != null) { try { tracer.get(X_FLOW_ID).getValue(); } catch (IllegalArgumentException e) { log.warn("No trace was configured for the name {}. Returning null. " + "To configure Tracer provide an application property: " + "tracer.traces.X-Flow-ID=flow-id", X_FLOW_ID); } catch (IllegalStateException e) { tracer.start(); } } else { log.warn("No bean of class Tracer was found."); } } TracerFlowIdComponent(Tracer tracer); String getXFlowIdKey(); @Override String getXFlowIdValue(); @Override void startTraceIfNoneExists(); }### Answer:
@Test public void makeSureTraceWillBeStartedIfNoneHasBeenStartedBefore() { TracerFlowIdComponent flowIdComponent = new TracerFlowIdComponent(tracer); when(tracer.get("X-Flow-ID").getValue()).thenThrow(new IllegalStateException()); flowIdComponent.startTraceIfNoneExists(); verify(tracer).start(); }
@Test public void wontFailIfTraceHasNotBeenConfiguredInStartTrace() { TracerFlowIdComponent flowIdComponent = new TracerFlowIdComponent(tracer); when(tracer.get("X-Flow-ID")).thenThrow(new IllegalArgumentException()); flowIdComponent.startTraceIfNoneExists(); }
@Test public void makeSureTraceWillNotStartedIfOneExists() { TracerFlowIdComponent flowIdComponent = new TracerFlowIdComponent(tracer); when(tracer.get("X-Flow-ID").getValue()).thenReturn("A_FUNKY_VALUE"); flowIdComponent.startTraceIfNoneExists(); verify(tracer, never()).start(); }
|
### Question:
BaseRemoteAccessApi { public DefaultCrumbIssuer getCrumb() throws ApiException { ApiResponse<DefaultCrumbIssuer> resp = getCrumbWithHttpInfo(); return resp.getData(); } BaseRemoteAccessApi(); BaseRemoteAccessApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); com.squareup.okhttp.Call getCrumbCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener); DefaultCrumbIssuer getCrumb(); ApiResponse<DefaultCrumbIssuer> getCrumbWithHttpInfo(); com.squareup.okhttp.Call getCrumbAsync(final ApiCallback<DefaultCrumbIssuer> callback); }### Answer:
@Test public void getCrumbTest() throws ApiException { DefaultCrumbIssuer response = api.getCrumb(); }
|
### Question:
XmlModelLoader extends ModelLoader<XmlModel, InputStream> { @Override public XmlModel loadModel(InputStream xmlStream) throws ModelException { if (xmlStream == null) { throw new ModelException("XML model is not valid [null]."); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(xmlStream); return new XmlModel(new XmlDocument(doc)); } catch (IOException ioe) { logger.error(ioe, "Cannot load XML model."); throw new XmlModelException("Cannot load XML model", ioe); } catch (ParserConfigurationException pce) { logger.error(pce, "Cannot parse XML file model."); throw new XmlModelException("Cannot parse XML model", pce); } catch (SAXException se) { logger.error(se, "Cannot parse XML file model."); throw new XmlModelException("Cannot parse XML model.", se); } } @Override XmlModel loadModel(InputStream xmlStream); }### Answer:
@Test public void testLoadXML() throws Exception { XmlModelLoader loader = new XmlModelLoader(); File file = new File("conf/test/xml/sample.xml"); XmlModel model = loader.loadModel(new FileInputStream(file)); Assert.assertNotNull(model); Assert.assertEquals(1, model.getDocuments().size()); Document doc = model.getDocuments().get(0).getDocument(); Assert.assertNotNull(doc); Element element = doc.getDocumentElement(); Assert.assertNotNull(element); }
|
### Question:
UmlModelLoader extends ModelLoader<UmlModel, File> { @Override public UmlModel loadModel(File modelFile) throws UmlModelException { if (modelFile == null) { return new UmlModel(UmlModelProducer.getInstance().createUmlModel(null)); } try { Model model = getUmlRootModel(modelFile); UmlModel umlModel = new UmlModel(model); return umlModel; } catch (IOException e) { logger.error(e, "Canot load Template " + modelFile.getName()); throw new UmlModelException("Cannot load Template " + modelFile.getName(), e); } catch (RuntimeException re) { logger.error(re, "Canot load Template " + modelFile.getName()); throw new UmlModelException("Cannot load Template " + modelFile.getName(), re); } } @Override UmlModel loadModel(File modelFile); }### Answer:
@Test public void testLoadModel() throws ModelException { UmlModelLoader loader = new UmlModelLoader(); UmlModel umlModel = loader.loadModel(new File("conf/template/uml/sample.uml")); Assert.assertNotNull(umlModel); Assert.assertNotNull(umlModel.getModel()); Assert.assertSame(ModelImpl.class, umlModel.getModel().getClass()); }
|
### Question:
ReceiverServiceImpl implements ReceiverService { @Override public void receive(ProbeJson probeJson) { concurrentDataList.addProbeJson(probeJson); } @Override void receive(ProbeJson probeJson); @Override @Scheduled(cron = "0 0/20 7-23 * * ?") void commit(); @Override RealTimeJson statLatest(); }### Answer:
@Test public void receive() throws Exception { receiverService.receive(new ProbeJson()); Thread.sleep(1000); System.out.println(ConcurrentDataList.instance().getAll().size()); }
|
### Question:
UserDaoImpl implements UserDao { @Override public UserEntity save(UserEntity userEntity) { return userRepository.save(userEntity); } @Override UserEntity findById(int id); @Override UserEntity findByName(String name); @Override UserEntity findByNameAndPassword(String name, String password); @Override UserEntity save(UserEntity userEntity); @Override void delete(int id); }### Answer:
@Test @Rollback @Transactional public void save() throws Exception { }
|
### Question:
UserDaoImpl implements UserDao { @Override public void delete(int id) { userRepository.delete(id); } @Override UserEntity findById(int id); @Override UserEntity findByName(String name); @Override UserEntity findByNameAndPassword(String name, String password); @Override UserEntity save(UserEntity userEntity); @Override void delete(int id); }### Answer:
@Test public void delete() throws Exception { }
|
### Question:
NewOldServiceImpl implements NewOldService { @Override public List<NewOldVo> getNewOldStat(int startHour, QueryThreshold threshold, int startRange, String probeId) throws ParamException { if (threshold==null) throw new ParamException(ServerCode.PARAM_FORMAT,"threshold","threshold cannot be null"); return newOldDao.getNewOldStat(startHour, threshold, startRange, probeId); } @Override List<NewOldVo> getNewOldStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override NewOldVo findById(int id); @Override NewOldVo save(NewOldCustomElement newOldCustomElement); }### Answer:
@Test public void getNewOldStat() throws Exception { System.out.println(newOldService .getNewOldStat((int)(System.currentTimeMillis()/(3600*1000)-1), QueryThreshold.HOUR,10,null)); }
|
### Question:
NewOldServiceImpl implements NewOldService { @Override public List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId) { return ObjectMapper.convertToChartData(newOldDao.findByHourAndProbe(hour, probeId)); } @Override List<NewOldVo> getNewOldStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override NewOldVo findById(int id); @Override NewOldVo save(NewOldCustomElement newOldCustomElement); }### Answer:
@Test public void findByHourAndProbe() throws Exception { }
|
### Question:
NewOldServiceImpl implements NewOldService { @Override public NewOldVo findById(int id) throws ServerException { NewOldEntity entity = newOldDao.findById(id); if (entity == null) throw new ServerException(ServerCode.NOT_FOUND); return new NewOldVo(entity); } @Override List<NewOldVo> getNewOldStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override NewOldVo findById(int id); @Override NewOldVo save(NewOldCustomElement newOldCustomElement); }### Answer:
@Test public void findById() throws Exception { }
|
### Question:
NewOldServiceImpl implements NewOldService { @Override public NewOldVo save(NewOldCustomElement newOldCustomElement) { NewOldEntity entity = new NewOldEntity(); entity.setWifiProb(newOldCustomElement.getWifiProb()); entity.setHour(new Timestamp(newOldCustomElement.getHour()*3600*1000)); entity.setNewCustomer(newOldCustomElement.getNewCustomer()); entity.setOldCustomer(newOldCustomElement.getOldCustomer()); return new NewOldVo(newOldDao.save(entity)); } @Override List<NewOldVo> getNewOldStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override NewOldVo findById(int id); @Override NewOldVo save(NewOldCustomElement newOldCustomElement); }### Answer:
@Test public void save() throws Exception { }
|
### Question:
UserServiceImpl implements UserService { @Override public UserVo login(String username, String password) throws ServerException { UserEntity userEntity = userDao.findByName(username); if (userEntity==null) throw new ServerException(ServerCode.USER_NOT_FOUND); if (!userEntity.getPassword().equals(password)) throw new ServerException(ServerCode.ERROR_PASSWORD); return new UserVo(userEntity); } @Override UserVo login(String username, String password); @Override UserVo register(String username, String password); @Override UserVo changePassword(String username, String oldPassword, String newPassword); }### Answer:
@Test public void login() throws Exception { System.out.println(userService.login("admin","admin")); try { userService.login("admin","ha"); fail(); } catch (ServerException e) { System.out.println(e.getMessage()); } }
|
### Question:
ActivenessServiceImpl implements ActivenessService { @Override public List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int startRange, String probeId) throws ParamException { if (threshold==null) throw new ParamException(ServerCode.PARAM_FORMAT,"threshold","threshold cannot be null"); return activenessDao.getActivenessStat(startHour, threshold, startRange, probeId); } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override ActivenessVo findById(int id); @Override ActivenessVo save(CustomerActivenessElement activenessElement); }### Answer:
@Test public void getActivenessStat() throws Exception { System.out.println(activenessService .getActivenessStat((int)(System.currentTimeMillis()/(3600*1000)), QueryThreshold.HOUR,10,null)); }
|
### Question:
ActivenessServiceImpl implements ActivenessService { @Override public List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId) { ActivenessEntity activenessEntity = activenessDao.findByHourAndProbe(hour, probeId); return ObjectMapper.convertToChartData(activenessEntity); } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override ActivenessVo findById(int id); @Override ActivenessVo save(CustomerActivenessElement activenessElement); }### Answer:
@Test public void findByHourAndProbe() throws Exception { System.out.println(activenessService.findByHourAndProbe((int)(System.currentTimeMillis()/(3600*1000)),"1s12sz")); }
|
### Question:
ActivenessServiceImpl implements ActivenessService { @Override public ActivenessVo findById(int id) throws ServerException { ActivenessEntity entity = activenessDao.findById(id); if (entity==null) throw new ServerException(ServerCode.NOT_FOUND); return new ActivenessVo(entity); } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override ActivenessVo findById(int id); @Override ActivenessVo save(CustomerActivenessElement activenessElement); }### Answer:
@Test public void findById() throws Exception { System.out.println(activenessService.findById(1)); }
|
### Question:
ReceiverServiceImpl implements ReceiverService { @Override @Scheduled(cron = "0 0/20 7-23 * * ?") public void commit() { new Thread( () -> { try { if (concurrentDataList.getSize()>0) { int sleep = (int) (Math.random()*60000); try { Thread.sleep(sleep); } catch (InterruptedException e) { e.printStackTrace(); } List<ProbeJson> probeJsons = concurrentDataList.getAll(); InputStream inputStream = new ByteArrayInputStream(GsonTool.convertObjectToJson(probeJsons).getBytes()); try { Calendar c = Calendar.getInstance(); HDFSTool.uploadFiles(inputStream, String.valueOf(c.get(Calendar.YEAR)) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DATE) + "/" + c.get(Calendar.MILLISECOND) + "-" + receiverConfig.getName()+".json"); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } }).start(); } @Override void receive(ProbeJson probeJson); @Override @Scheduled(cron = "0 0/20 7-23 * * ?") void commit(); @Override RealTimeJson statLatest(); }### Answer:
@Test public void commit() throws Exception { }
|
### Question:
ActivenessServiceImpl implements ActivenessService { @Override public ActivenessVo save(CustomerActivenessElement activenessElement) { ActivenessEntity entity = new ActivenessEntity(); entity.setWifiProb(activenessElement.getWifiProb()); entity.setHour(new Timestamp(activenessElement.getHour()*3600*1000)); entity.setNumOfHighActive(activenessElement.getNumOfHighActive()); entity.setNumOfMedianActive(activenessElement.getNumOfMedianActive()); entity.setNumOfLowActive(activenessElement.getNumOfLowActive()); entity.setNumOfSleepActive(activenessElement.getNumOfSleepActive()); return new ActivenessVo(activenessDao.save(entity)); } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override ActivenessVo findById(int id); @Override ActivenessVo save(CustomerActivenessElement activenessElement); }### Answer:
@Test public void save() throws Exception { }
|
### Question:
VisitCircleServiceImpl implements VisitCircleService { @Override public List<VisitCircleVo> getVisitCircleStat(int startHour, QueryThreshold threshold, int startRange, String probeId) throws ParamException { if (threshold==null) throw new ParamException(ServerCode.PARAM_FORMAT,"threshold","threshold cannot be null"); return visitCircleDao.getVisitCircleStat(startHour, threshold, startRange, probeId); } @Override List<VisitCircleVo> getVisitCircleStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override VisitCircleVo findById(int id); @Override VisitCircleVo save(VisitingCycleElement visitingCycleElement); }### Answer:
@Test public void getVisitCircleStat() throws Exception { System.out.println(visitCircleService .getVisitCircleStat((int)(System.currentTimeMillis()/(3600*1000)-1), QueryThreshold.HOUR,10,null)); }
|
### Question:
VisitCircleServiceImpl implements VisitCircleService { @Override public List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId) { return ObjectMapper.convertToViewData( ObjectMapper.convertToChartData(visitCircleDao.findByHourAndProbe(hour, probeId)), ConvertType.circle); } @Override List<VisitCircleVo> getVisitCircleStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override VisitCircleVo findById(int id); @Override VisitCircleVo save(VisitingCycleElement visitingCycleElement); }### Answer:
@Test public void findByHourAndProbe() throws Exception { System.out.println((int)(System.currentTimeMillis()/(3600*1000)-1)); System.out.println(visitCircleService.findByHourAndProbe((int)(System.currentTimeMillis()/(3600*1000)),"1s12sz")); }
|
### Question:
VisitCircleServiceImpl implements VisitCircleService { @Override public VisitCircleVo findById(int id) throws ServerException { VisitCircleEntity visitCircleEntity = visitCircleDao.findById(id); if (visitCircleEntity==null) throw new ServerException(ServerCode.NOT_FOUND); return new VisitCircleVo(visitCircleEntity); } @Override List<VisitCircleVo> getVisitCircleStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override VisitCircleVo findById(int id); @Override VisitCircleVo save(VisitingCycleElement visitingCycleElement); }### Answer:
@Test public void findById() throws Exception { }
|
### Question:
VisitCircleServiceImpl implements VisitCircleService { @Override public VisitCircleVo save(VisitingCycleElement visitingCycleElement) { VisitCircleEntity entity = new VisitCircleEntity(); entity.setWifiProb(visitingCycleElement.getWifiProb()); entity.setHour(new Timestamp(visitingCycleElement.getHour()*3600*1000)); List<Tuple<Long,Integer>> data = visitingCycleElement.getStatistic(); int setIndex = 0; Field[] fields = VisitCircleEntity.class.getDeclaredFields(); for (;setIndex<fields.length-3 && setIndex < data.size(); setIndex++) { Field field = fields[setIndex+3]; field.setAccessible(true); try { field.set(entity,data.get(setIndex).getY()); } catch (IllegalAccessException e) { System.out.println(); } field.setAccessible(false); } return new VisitCircleVo(visitCircleDao.save(entity)); } @Override List<VisitCircleVo> getVisitCircleStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override VisitCircleVo findById(int id); @Override VisitCircleVo save(VisitingCycleElement visitingCycleElement); }### Answer:
@Test public void save() throws Exception { }
|
### Question:
ProbeServiceImpl implements ProbeService { @Override public Page<ProbeVo> findAll(int page, int size) { Page<ProbeEntity> probeEntities = probeDao.findAll(page, size); return new PageImpl<>(probeEntities.getContent().stream().map(ProbeVo::new).collect(Collectors.toList()), probeEntities.nextPageable(),probeEntities.getTotalElements()); } @Override Page<ProbeVo> findAll(int page, int size); @Override ProbeVo findById(int id); }### Answer:
@Test public void findAll() throws Exception { System.out.println(probeService.findAll(0,10).getContent()); }
|
### Question:
ProbeServiceImpl implements ProbeService { @Override public ProbeVo findById(int id) throws ServerException { ProbeEntity probeEntity = probeDao.findById(id); if (probeEntity==null) throw new ServerException(ServerCode.NOT_FOUND); return new ProbeVo(probeEntity); } @Override Page<ProbeVo> findAll(int page, int size); @Override ProbeVo findById(int id); }### Answer:
@Test public void findById() throws Exception { System.out.println(probeService.findById(1)); }
|
### Question:
FlowServiceImpl implements FlowService { @Override public List<FlowVo> getFStat(int startHour, QueryThreshold threshold, int startRange, String probeId) throws ParamException { if (threshold==null) throw new ParamException(ServerCode.PARAM_FORMAT,"threshold","threshold cannot be null"); return flowDao.getFlowStat(startHour, threshold, startRange, probeId); } @Override List<FlowVo> getFStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override FlowVo findById(int id); @Override FlowVo save(CustomerFlowElement flowElement); }### Answer:
@Test public void getFStat() throws Exception { System.out.println(flowService .getFStat((int)(System.currentTimeMillis()/(3600*1000)-1), QueryThreshold.HOUR,10,null)); }
|
### Question:
FlowServiceImpl implements FlowService { @Override public List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId) { return ObjectMapper.convertToChartData(flowDao.findByHourAndProbe(hour, probeId)); } @Override List<FlowVo> getFStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override FlowVo findById(int id); @Override FlowVo save(CustomerFlowElement flowElement); }### Answer:
@Test public void findByHourAndProbe() throws Exception { System.out.println(flowService.findByHourAndProbe((int)(System.currentTimeMillis()/(3600*1000)-1),"1s12sz")); }
|
### Question:
FlowServiceImpl implements FlowService { @Override public FlowVo findById(int id) throws ServerException { FlowEntity entity = flowDao.findById(id); if (entity==null) throw new ServerException(ServerCode.NOT_FOUND); return new FlowVo(entity); } @Override List<FlowVo> getFStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override FlowVo findById(int id); @Override FlowVo save(CustomerFlowElement flowElement); }### Answer:
@Test public void findById() throws Exception { }
|
### Question:
HttpTools { public static URLConnection sendGet(String url) { try { URL realUrl = new URL(url); URLConnection connection = realUrl.openConnection(); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setConnectTimeout(200); connection.connect(); return connection; } catch (IOException e) { return null; } } static URLConnection sendGet(String url); static String getLocalIp(); }### Answer:
@Test public void sendGet() throws Exception { URLConnection connection = HttpTools.sendGet("http: Map<String, List<String>> map = connection.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } }
|
### Question:
FlowServiceImpl implements FlowService { @Override public FlowVo save(CustomerFlowElement flowElement) { FlowEntity flowEntity = new FlowEntity(); flowEntity.setWifiProb(flowElement.getWifiProb()); flowEntity.setHour(new Timestamp(flowElement.getHour()*3600*1000)); flowEntity.setInNoOutWifi(flowElement.getInNoOutWifi()); flowEntity.setInNoOutStore(flowElement.getInNoOutStore()); flowEntity.setOutNoInWifi(flowElement.getOutNoInWifi()); flowEntity.setOutNoInStore(flowElement.getOutNoInStore()); flowEntity.setInAndOutWifi(flowElement.getInAndOutWifi()); flowEntity.setIntAndOutStore(flowElement.getInAndOutStore()); flowEntity.setStayInWifi(flowElement.getStayInWifi()); flowEntity.setStayInStore(flowElement.getStayInStore()); flowEntity.setJumpRate(flowElement.getJumpRate()); flowEntity.setInStoreRate(flowElement.getInStoreRate()); flowEntity.setDeepVisit(flowElement.getDeepVisit()); return new FlowVo(flowDao.save(flowEntity)); } @Override List<FlowVo> getFStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override FlowVo findById(int id); @Override FlowVo save(CustomerFlowElement flowElement); }### Answer:
@Test public void save() throws Exception { }
|
### Question:
StoreHoursServiceImpl implements StoreHoursService { @Override public List<StoreHoursVo> getStoreHoursStat(int startHour, QueryThreshold threshold, int startRange, String probeId) throws ParamException { if (threshold==null) throw new ParamException(ServerCode.PARAM_FORMAT,"threshold","threshold cannot be null"); return storeHoursDao.getStoreHoursStat(startHour, threshold, startRange, probeId); } @Override List<StoreHoursVo> getStoreHoursStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override StoreHoursVo findById(int id); @Override StoreHoursVo save(InStoreHoursElement storeHoursElement); }### Answer:
@Test public void getStoreHoursStat() throws Exception { System.out.println(storeHoursService .getStoreHoursStat((int)(System.currentTimeMillis()/(3600*1000)-1000), QueryThreshold.DAY,30,null)); }
|
### Question:
StoreHoursServiceImpl implements StoreHoursService { @Override public List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId) { return ObjectMapper.convertToViewData( ObjectMapper.convertToChartData(storeHoursDao.findByHourAndProbe(hour, probeId)), ConvertType.store); } @Override List<StoreHoursVo> getStoreHoursStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override StoreHoursVo findById(int id); @Override StoreHoursVo save(InStoreHoursElement storeHoursElement); }### Answer:
@Test public void findByHourAndProbe() throws Exception { System.out.println(storeHoursService.findByHourAndProbe((int)(System.currentTimeMillis()/(3600*1000)),"1s12sz")); }
|
### Question:
StoreHoursServiceImpl implements StoreHoursService { @Override public StoreHoursVo findById(int id) throws ServerException { StoreHoursEntity entity = storeHoursDao.findById(id); if (entity==null) throw new ServerException(ServerCode.NOT_FOUND); return new StoreHoursVo(entity); } @Override List<StoreHoursVo> getStoreHoursStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override StoreHoursVo findById(int id); @Override StoreHoursVo save(InStoreHoursElement storeHoursElement); }### Answer:
@Test public void findById() throws Exception { }
|
### Question:
StoreHoursServiceImpl implements StoreHoursService { @Override public StoreHoursVo save(InStoreHoursElement storeHoursElement) { StoreHoursEntity entity = new StoreHoursEntity(); entity.setWifiProb(storeHoursElement.getWifiProb()); entity.setHour(new Timestamp(storeHoursElement.getHour()*3600*1000)); List<Tuple<Long,Integer>> data = storeHoursElement.getStatistic(); int setIndex = 0; Field[] fields = StoreHoursEntity.class.getDeclaredFields(); for (;setIndex<fields.length-3 && setIndex < data.size(); setIndex++) { Field field = fields[setIndex+3]; field.setAccessible(true); try { field.set(entity,data.get(setIndex).getY()); } catch (IllegalAccessException e) { e.printStackTrace(); } field.setAccessible(false); } return new StoreHoursVo(storeHoursDao.save(entity)); } @Override List<StoreHoursVo> getStoreHoursStat(int startHour, QueryThreshold threshold, int startRange, String probeId); @Override List<Tuple<String, Number>> findByHourAndProbe(int hour, String probeId); @Override StoreHoursVo findById(int id); @Override StoreHoursVo save(InStoreHoursElement storeHoursElement); }### Answer:
@Test public void save() throws Exception { }
|
### Question:
HttpTools { public static String getLocalIp() { InputStream inputStream = HttpTools.class.getClassLoader().getResourceAsStream("config/ipconfig"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { String config = reader.readLine(); Enumeration<NetworkInterface> netInterfaces; try { netInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { e.printStackTrace(); return null; } while (netInterfaces.hasMoreElements()) { NetworkInterface ni = netInterfaces.nextElement(); if (ni.getDisplayName().equals(config)) { Enumeration<InetAddress> ia = ni.getInetAddresses(); while (ia.hasMoreElements()) { InetAddress ip = ia.nextElement(); String ipStr = ip.getHostAddress(); if (ipStr.length() < 17) return ipStr; } } } } catch (IOException e) { e.printStackTrace(); } return null; } static URLConnection sendGet(String url); static String getLocalIp(); }### Answer:
@Test public void getLocalIp() throws Exception { System.out.println(HttpTools.getLocalIp()); }
|
### Question:
ActivenessDaoImpl implements ActivenessDao { @Override public List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int statRange, String probeId) { String isProbeSelected = probeId==null || probeId.isEmpty()? "": "AND wifiProb = :probeId "; String sqlQuery = "SELECT wifiProb,DATE_FORMAT(hour,:dateFormat),sum(numOfHighActive)," + "sum(numOfMedianActive),sum(numOfLowActive),sum(numOfSleepActive) " + "FROM activeness " + "WHERE UNIX_TIMESTAMP(hour) >= (:startHour*3600) " + isProbeSelected+ " GROUP BY wifiProb,DATE_FORMAT(hour,:dateFormat) " + "LIMIT 0,:statRange"; Query query = entityManager.createNativeQuery(sqlQuery); query.setParameter("dateFormat", ThresholdUtil.convertToString(threshold)); query.setParameter("startHour",startHour); if (!isProbeSelected.isEmpty()) query.setParameter("probeId",probeId); query.setParameter("statRange",statRange>=1? statRange: 10); List resultList = query.getResultList(); List<ActivenessVo> activenessVos = new LinkedList<>(); for (Object object: resultList) { activenessVos.add((ActivenessVo) ObjectMapper.arrayToObject(ActivenessVo.class,object)); } return activenessVos; } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int statRange, String probeId); @Override ActivenessEntity findByHourAndProbe(int hour, String probeId); @Override ActivenessEntity findById(int id); @Override ActivenessEntity save(ActivenessEntity entity); }### Answer:
@Test public void getActivenessStat() throws Exception { long time = System.currentTimeMillis(); int hour = (int) (time/(1000*60*60)); System.out.println(activenessDao.getActivenessStat(hour, QueryThreshold.HOUR, 10, null)); }
|
### Question:
ActivenessDaoImpl implements ActivenessDao { @Override public ActivenessEntity findByHourAndProbe(int hour, String probeId) { Timestamp timestamp = new Timestamp(((long) hour)*3600*1000); System.out.println(timestamp.getTime()); return activenessRepository.findByHourAndWifiProb(timestamp,probeId); } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int statRange, String probeId); @Override ActivenessEntity findByHourAndProbe(int hour, String probeId); @Override ActivenessEntity findById(int id); @Override ActivenessEntity save(ActivenessEntity entity); }### Answer:
@Test public void findByHourAndProbe() throws Exception { }
|
### Question:
ActivenessDaoImpl implements ActivenessDao { @Override public ActivenessEntity findById(int id) { return activenessRepository.findOne(id); } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int statRange, String probeId); @Override ActivenessEntity findByHourAndProbe(int hour, String probeId); @Override ActivenessEntity findById(int id); @Override ActivenessEntity save(ActivenessEntity entity); }### Answer:
@Test public void findById() throws Exception { }
|
### Question:
ActivenessDaoImpl implements ActivenessDao { @Override public ActivenessEntity save(ActivenessEntity entity) { return activenessRepository.save(entity); } @Override List<ActivenessVo> getActivenessStat(int startHour, QueryThreshold threshold, int statRange, String probeId); @Override ActivenessEntity findByHourAndProbe(int hour, String probeId); @Override ActivenessEntity findById(int id); @Override ActivenessEntity save(ActivenessEntity entity); }### Answer:
@Test public void save() throws Exception { }
|
### Question:
UserDaoImpl implements UserDao { @Override public UserEntity findById(int id) { return userRepository.findOne(id); } @Override UserEntity findById(int id); @Override UserEntity findByName(String name); @Override UserEntity findByNameAndPassword(String name, String password); @Override UserEntity save(UserEntity userEntity); @Override void delete(int id); }### Answer:
@Test public void findById() throws Exception { System.out.println(userDao.findById(1).getUsername()); }
|
### Question:
UserDaoImpl implements UserDao { @Override public UserEntity findByName(String name) { return userRepository.findByUsername(name); } @Override UserEntity findById(int id); @Override UserEntity findByName(String name); @Override UserEntity findByNameAndPassword(String name, String password); @Override UserEntity save(UserEntity userEntity); @Override void delete(int id); }### Answer:
@Test public void findByName() throws Exception { System.out.println(userDao.findByName("admin")); }
|
### Question:
PotentiometerSimulator implements ISimulatorUpdater { public boolean isSetup() { return mIsSetup; } PotentiometerSimulator(IAnalogInWrapper aWrapper, IPwmWrapper aSpeedController); void setParameters(double aThrow, double aMinVoltage, double aMaxVoltage); @Override void update(); boolean isSetup(); @Override Object getConfig(); }### Answer:
@Test public void testIncompletePotSim() { PotentiometerSimulator pot = new PotentiometerSimulator(null, null); Assertions.assertFalse(pot.isSetup()); new AnalogInput(0); pot = new PotentiometerSimulator(SensorActuatorRegistry.get().getAnalogIn().get(0), null); Assertions.assertFalse(pot.isSetup()); }
|
### Question:
CompressorWrapper extends ASensorWrapper { public CompressorWrapper() { super("Compressor"); mAirPressure = 120; mChargeRate = .25; } CompressorWrapper(); void setChargeRate(double aChargeRate); void solenoidFired(double aPressure); void update(); double getAirPressure(); }### Answer:
@Test public void testCompressorWrapper() { CompressorWrapper compressor = new CompressorWrapper(); compressor.setChargeRate(.1); Assertions.assertEquals(120, compressor.getAirPressure(), DOUBLE_EPSILON); compressor.solenoidFired(60); Assertions.assertEquals(60, compressor.getAirPressure(), DOUBLE_EPSILON); simulateForTime(2, () -> { compressor.update(); }); Assertions.assertEquals(70, compressor.getAirPressure(), DOUBLE_EPSILON); compressor.solenoidFired(90); Assertions.assertEquals(0, compressor.getAirPressure(), DOUBLE_EPSILON); simulateForTime(30, () -> { compressor.update(); }); Assertions.assertEquals(120, compressor.getAirPressure(), DOUBLE_EPSILON); }
|
### Question:
JoystickFactory { private JoystickFactory() { mJoystickMap = new IMockJoystick[DriverStation.kJoystickPorts]; for (int i = 0; i < DriverStation.kJoystickPorts; ++i) { mJoystickMap[i] = new NullJoystick(); } mControllerConfig = JoystickDiscoverer.rediscoverJoysticks(); loadSticks(); } private JoystickFactory(); static JoystickFactory getInstance(); Map<String, ControllerConfiguration> getControllerConfiguration(); void setSpecialization(String aName, Class<? extends IMockJoystick> aClass); void setSpecialization(String aName, Class<? extends IMockJoystick> aClass, boolean aAutoSave); IMockJoystick[] getAll(); IMockJoystick get(int aJoystickIndex); void setJoysticks(int aJoystickIndex, String aControllerName); void setJoysticks(int aJoystickIndex, String aControllerName, boolean aAutoSave); void registerJoystickCreated(int aPort); static final String sJOYSTICK_CONFIG_FILE; }### Answer:
@Test public void testJoystickFactory() { File configFile = new File(JoystickFactory.sJOYSTICK_CONFIG_FILE); if (configFile.exists()) { Assertions.assertTrue(configFile.delete()); } if (!configFile.getParentFile().exists()) { Assertions.assertTrue(configFile.getParentFile().mkdirs()); } JoystickFactory factory = JoystickFactory.getInstance(); Map<String, ControllerConfiguration> config = factory.getControllerConfiguration(); Assertions.assertEquals(0, config.size()); for (int i = 0; i < DriverStation.kJoystickPorts; ++i) { Assertions.assertTrue(factory.get(i) instanceof NullJoystick); } config.put("X", new ControllerConfiguration(new MockController(), XboxJoystick.class)); config.put("Y", new ControllerConfiguration(new MockController(), Ps4Joystick.class)); config.put("Z", new ControllerConfiguration(new MockController(), KeyboardJoystick.class)); factory.setJoysticks(0, "X"); factory.setJoysticks(3, "Y"); factory.setJoysticks(5, "Z"); Assertions.assertTrue(factory.get(0) instanceof XboxJoystick); Assertions.assertTrue(factory.get(1) instanceof NullJoystick); Assertions.assertTrue(factory.get(2) instanceof NullJoystick); Assertions.assertTrue(factory.get(3) instanceof Ps4Joystick); Assertions.assertTrue(factory.get(4) instanceof NullJoystick); Assertions.assertTrue(factory.get(5) instanceof KeyboardJoystick); Properties properties = new Properties(); try (InputStream inputStream = new FileInputStream(JoystickFactory.sJOYSTICK_CONFIG_FILE)) { properties.load(inputStream); } catch (IOException e) { Assertions.fail(e.getMessage()); } Assertions.assertEquals("X---com.snobot.simulator.joysticks.joystick_specializations.XboxJoystick", properties.getProperty("Joystick_0")); Assertions.assertEquals("Null Joystick---null", properties.getProperty("Joystick_1")); Assertions.assertEquals("Null Joystick---null", properties.getProperty("Joystick_2")); Assertions.assertEquals("Y---com.snobot.simulator.joysticks.joystick_specializations.Ps4Joystick", properties.getProperty("Joystick_3")); Assertions.assertEquals("Null Joystick---null", properties.getProperty("Joystick_4")); Assertions.assertEquals("Z---com.snobot.simulator.joysticks.joystick_specializations.KeyboardJoystick", properties.getProperty("Joystick_5")); }
|
### Question:
XboxJoystick extends BaseJoystick { @Override public float[] getAxisValues() { float[] output = super.getAxisValues(); float triggerValue = output[2]; if (triggerValue < 0) { output[2] = 0; output[3] = triggerValue; } else { output[2] = triggerValue; output[3] = 0; } return output; } XboxJoystick(Controller aController); XboxJoystick(Controller aController, String aName); @Override float[] getAxisValues(); }### Answer:
@Test public void testKeyboardJoystick() throws Exception { XboxJoystick joystick = new XboxJoystick(new MockController()); float[] axisValues = joystick.getAxisValues(); short[] povValues = joystick.getPovValues(); int buttonMask = joystick.getButtonMask(); Assertions.assertEquals(6, axisValues.length); Assertions.assertEquals(1, povValues.length); Assertions.assertEquals(0, buttonMask); }
|
### Question:
KeyboardJoystick extends BaseJoystick { public KeyboardJoystick(Controller aController) { this(aController, "Keyboard"); } KeyboardJoystick(Controller aController); KeyboardJoystick(Controller aController, String aName); @Override float[] getAxisValues(); @Override short[] getPovValues(); }### Answer:
@Test public void testKeyboardJoystick() throws Exception { MockController controller = new MockController(); KeyboardJoystick joystick = new KeyboardJoystick(controller); short[] povValues = joystick.getPovValues(); Assertions.assertEquals(-1, povValues[0]); testAxis(joystick, 0, 0, 0, 0, 0, 0); reset(controller); controller.setValueForComponent(Identifier.Key.W, 1); testAxis(joystick, 0, -1, 0, 0, 0, 0); reset(controller); controller.setValueForComponent(Identifier.Key.S, 1); testAxis(joystick, 0, 1, 0, 0, 0, 0); reset(controller); controller.setValueForComponent(Identifier.Key.A, 1); testAxis(joystick, -1, 0, 0, 0, 0, 0); reset(controller); controller.setValueForComponent(Identifier.Key.D, 1); testAxis(joystick, 1, 0, 0, 0, 0, 0); reset(controller); controller.setValueForComponent(Identifier.Key.I, 1); testAxis(joystick, 0, 0, 0, 0, 0, -1); reset(controller); controller.setValueForComponent(Identifier.Key.K, 1); testAxis(joystick, 0, 0, 0, 0, 0, 1); reset(controller); controller.setValueForComponent(Identifier.Key.J, 1); testAxis(joystick, 0, 0, 0, 0, -1, 0); reset(controller); controller.setValueForComponent(Identifier.Key.L, 1); testAxis(joystick, 0, 0, 0, 0, 1, 0); reset(controller); controller.setValueForComponent(Identifier.Key.C, 1); testAxis(joystick, 0, 0, 1, 0, 0, 0); reset(controller); controller.setValueForComponent(Identifier.Key.N, 1); testAxis(joystick, 0, 0, 0, 1, 0, 0); reset(controller); testPovs(joystick, -1); reset(controller); controller.setValueForComponent(Identifier.Key.UP, 1); testPovs(joystick, 0); reset(controller); controller.setValueForComponent(Identifier.Key.UP, 1); controller.setValueForComponent(Identifier.Key.RIGHT, 1); testPovs(joystick, 45); reset(controller); controller.setValueForComponent(Identifier.Key.RIGHT, 1); testPovs(joystick, 90); reset(controller); controller.setValueForComponent(Identifier.Key.RIGHT, 1); controller.setValueForComponent(Identifier.Key.DOWN, 1); testPovs(joystick, 135); reset(controller); controller.setValueForComponent(Identifier.Key.DOWN, 1); testPovs(joystick, 180); reset(controller); controller.setValueForComponent(Identifier.Key.DOWN, 1); controller.setValueForComponent(Identifier.Key.LEFT, 1); testPovs(joystick, 225); reset(controller); controller.setValueForComponent(Identifier.Key.LEFT, 1); testPovs(joystick, 270); reset(controller); controller.setValueForComponent(Identifier.Key.UP, 1); controller.setValueForComponent(Identifier.Key.LEFT, 1); testPovs(joystick, -45); }
|
### Question:
GuavaUtils { public static <T> boolean isPresent(T t){ Optional<T>optionalObj = Optional.fromNullable(t); return optionalObj.isPresent(); } static boolean isPresent(T t); }### Answer:
@Test public void isPresentTest(){ B1 b = null; assertEquals(false, GuavaUtils.isPresent(b)); b = new B1(); assertEquals(true, GuavaUtils.isPresent(b)); }
|
### Question:
DozerUtils { public static <T> T convertSourceObjToDesObj(Object source,Class<T> destinationClass){ return mapper.map(source, destinationClass); } static T convertSourceObjToDesObj(Object source,Class<T> destinationClass); static void main(String[] args); }### Answer:
@Test public void testDozer(){ B1 b = new B1(); b.setName("sa"); B2 b2 = DozerUtils.convertSourceObjToDesObj(b, B2.class); Assert.assertEquals("sa", b2.getAge()); }
|
### Question:
AgentMaster { private AgentMaster(SmartConf conf) throws IOException { String[] addresses = AgentUtils.getMasterAddress(conf); if (addresses == null) { throw new IOException("AgentMaster address not configured!"); } String address = addresses[0]; LOG.info("Agent master: " + address); Config config = AgentUtils.overrideRemoteAddress( ConfigFactory.load(AgentConstants.AKKA_CONF_FILE), address); CmdletDispatcherHelper.init(); this.agentManager = new AgentManager(); Props props = Props.create(MasterActor.class, null, agentManager); ActorSystemLauncher launcher = new ActorSystemLauncher(config, props); launcher.start(); } private AgentMaster(SmartConf conf); static AgentMaster getAgentMaster(); static AgentMaster getAgentMaster(SmartConf conf); boolean isAgentRegisterReady(SmartConf conf); boolean isTikvAlreadyLaunched(SmartConf conf); void sendLaunchTikvMessage(); static void setCmdletManager(CmdletManager statusUpdater); boolean canAcceptMore(); String launchCmdlet(LaunchCmdlet launch); void stopCmdlet(long cmdletId); void shutdown(); List<AgentInfo> getAgentInfos(); int getNumAgents(); static final Timeout TIMEOUT; }### Answer:
@Test public void testAgentMaster() throws Exception { AgentMaster master = AgentMaster.getAgentMaster(); while (master.getMasterActor() == null) { } String instId = "instance-0"; Object answer = master.askMaster(AgentToMaster.RegisterNewAgent.getInstance(instId)); assertTrue(answer instanceof MasterToAgent.AgentRegistered); MasterToAgent.AgentRegistered registered = (MasterToAgent.AgentRegistered) answer; assertEquals(instId, registered.getAgentId().getId()); }
|
### Question:
ActionDao { public List<ActionInfo> getAPageOfAction(long start, long offset, List<String> orderBy, List<Boolean> isDesc) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); boolean ifHasAid = false; String sql = "SELECT * FROM " + TABLE_NAME + " ORDER BY "; for (int i = 0; i < orderBy.size(); i++) { if (orderBy.get(i).equals("aid")) { ifHasAid = true; } sql = sql + orderBy.get(i); if (isDesc.size() > i) { if (isDesc.get(i)) { sql = sql + " desc "; } sql = sql + ","; } } if (!ifHasAid) { sql = sql + "aid,"; } sql = sql.substring(0, sql.length() - 1); sql = sql + " LIMIT " + start + "," + offset + ";"; return jdbcTemplate.query(sql, new ActionRowMapper()); } ActionDao(DataSource dataSource); void setDataSource(DataSource dataSource); List<ActionInfo> getAll(); Long getCountOfAction(); ActionInfo getById(long aid); List<ActionInfo> getByIds(List<Long> aids); List<ActionInfo> getByCid(long cid); List<ActionInfo> getByCondition(String aidCondition,
String cidCondition); List<ActionInfo> getLatestActions(int size); List<ActionInfo> getLatestActions(String actionName, int size); List<ActionInfo> getLatestActions(String actionName, int size,
boolean successful, boolean finished); List<ActionInfo> getLatestActions(String actionName, boolean successful,
int size); List<ActionInfo> getAPageOfAction(long start, long offset, List<String> orderBy,
List<Boolean> isDesc); List<ActionInfo> getAPageOfAction(long start, long offset); List<ActionInfo> searchAction(String path, long start, long offset, List<String> orderBy,
List<Boolean> isDesc, long[] retTotalNumActions); List<ActionInfo> getLatestActions(String actionType, int size,
boolean finished); void delete(long aid); void deleteCmdletActions(long cid); int[] batchDeleteCmdletActions(final List<Long> cids); void deleteAll(); void insert(ActionInfo actionInfo); void insert(ActionInfo[] actionInfos); int[] replace(final ActionInfo[] actionInfos); int update(final ActionInfo actionInfo); int[] update(final ActionInfo[] actionInfos); long getMaxId(); }### Answer:
@Test public void testGetAPageOfAction() { Map<String, String> args = new HashMap<>(); ActionInfo actionInfo = new ActionInfo(1, 1, "cache", args, "Test", "Test", false, 123213213L, true, 123123L, 100); ActionInfo actionInfo1 = new ActionInfo(2, 1, "cache", args, "Test", "Test", false, 123213213L, true, 123123L, 100); ActionInfo actionInfo2 = new ActionInfo(3, 1, "cache", args, "Test", "Test", false, 123213213L, true, 123123L, 100); ActionInfo actionInfo3 = new ActionInfo(4, 1, "cache", args, "Test", "Test", false, 123213213L, true, 123123L, 100); actionDao.insert(new ActionInfo[]{actionInfo, actionInfo1, actionInfo2, actionInfo3}); List<String> order = new ArrayList<>(); order.add("aid"); List<Boolean> desc = new ArrayList<>(); desc.add(false); Assert.assertTrue(actionDao.getAPageOfAction(2, 1, order, desc).get(0).equals(actionInfo2)); }
|
### Question:
NamespaceFetcher { public NamespaceFetcher(DFSClient client, MetaStore metaStore, ScheduledExecutorService service) { this(client, metaStore, DEFAULT_INTERVAL, service, new SmartConf()); } NamespaceFetcher(DFSClient client, MetaStore metaStore, ScheduledExecutorService service); NamespaceFetcher(DFSClient client, MetaStore metaStore, ScheduledExecutorService service, SmartConf conf); NamespaceFetcher(DFSClient client, MetaStore metaStore, long fetchInterval); NamespaceFetcher(DFSClient client, MetaStore metaStore, long fetchInterval,
ScheduledExecutorService service, SmartConf conf); void startFetch(); boolean fetchFinished(); void stop(); static final Logger LOG; }### Answer:
@Test public void testNamespaceFetcher() throws IOException, InterruptedException, MissingEventsException, MetaStoreException { final Configuration conf = new SmartConf(); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(2).build(); try { final DistributedFileSystem dfs = cluster.getFileSystem(); dfs.mkdir(new Path("/user"), new FsPermission("777")); dfs.create(new Path("/user/user1")); dfs.create(new Path("/user/user2")); dfs.mkdir(new Path("/tmp"), new FsPermission("777")); DFSClient client = dfs.getClient(); MetaStore adapter = Mockito.mock(MetaStore.class); final List<String> pathesInDB = new ArrayList<>(); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocationOnMock) { try { Object[] objects = invocationOnMock.getArguments(); for (FileInfo fileInfo : (FileInfo[]) objects[0]) { pathesInDB.add(fileInfo.getPath()); } } catch (Throwable t) { t.printStackTrace(); } return null; } }).when(adapter).insertFiles(any(FileInfo[].class)); NamespaceFetcher fetcher = new NamespaceFetcher(client, adapter, 100); fetcher.startFetch(); List<String> expected = Arrays.asList("/", "/user", "/user/user1", "/user/user2", "/tmp"); while (!fetcher.fetchFinished()) { Thread.sleep(100); } Assert.assertTrue(pathesInDB.size() == expected.size() && pathesInDB.containsAll(expected)); fetcher.stop(); } finally { cluster.shutdown(); } }
|
### Question:
ListFileAction extends HdfsAction { @Override public void init(Map<String, String> args) { super.init(args); this.srcPath = args.get(FILE_PATH); } @Override void init(Map<String, String> args); }### Answer:
@Test public void testRemoteFileList() throws Exception { final String srcPath = "/testList"; final String file1 = "file1"; final String file2 = "file2"; final String dir = "/childDir"; final String dirFile1 = "childDirFile1"; dfs.mkdirs(new Path(srcPath)); dfs.mkdirs(new Path(srcPath + dir)); FSDataOutputStream out1 = dfs.create(new Path(dfs.getUri() + srcPath + "/" + file1)); out1.writeChars("test"); out1.close(); out1 = dfs.create(new Path(dfs.getUri() + srcPath + "/" + file2)); out1.writeChars("test"); out1.close(); out1 = dfs.create(new Path(dfs.getUri() + srcPath + dir + "/" + dirFile1)); out1.writeChars("test"); out1.close(); Assert.assertTrue(dfsClient.exists(srcPath + "/" + file1)); Assert.assertTrue(dfsClient.exists(srcPath + "/" + file2)); Assert.assertTrue(dfsClient.exists(srcPath + dir + "/" + dirFile1)); ListFileAction listFileAction = new ListFileAction(); listFileAction.setDfsClient(dfsClient); listFileAction.setContext(smartContext); Map<String , String> args = new HashMap<>(); args.put(ListFileAction.FILE_PATH , dfs.getUri() + srcPath); listFileAction.init(args); listFileAction.run(); Assert.assertTrue(listFileAction.getExpectedAfterRun()); listFileAction = new ListFileAction(); listFileAction.setDfsClient(dfsClient); listFileAction.setContext(smartContext); args = new HashMap<>(); args.put(ListFileAction.FILE_PATH , dfs.getUri() + srcPath + "/" + file1); listFileAction.init(args); listFileAction.run(); Assert.assertTrue(listFileAction.getExpectedAfterRun()); }
@Test public void testLocalFileList() throws Exception { final String srcPath = "/testList"; final String file1 = "file1"; final String file2 = "file2"; final String dir = "/childDir"; final String dirFile1 = "childDirFile1"; dfs.mkdirs(new Path(srcPath)); dfs.mkdirs(new Path(srcPath + dir)); FSDataOutputStream out1 = dfs.create(new Path(dfs.getUri() + srcPath + "/" + file1)); out1.writeChars("test"); out1.close(); out1 = dfs.create(new Path(srcPath + "/" + file2)); out1.writeChars("test"); out1.close(); out1 = dfs.create(new Path(srcPath + dir + "/" + dirFile1)); out1.writeChars("test"); out1.close(); Assert.assertTrue(dfsClient.exists(srcPath + "/" + file1)); Assert.assertTrue(dfsClient.exists(srcPath + "/" + file2)); Assert.assertTrue(dfsClient.exists(srcPath + dir + "/" + dirFile1)); ListFileAction listFileAction = new ListFileAction(); listFileAction.setDfsClient(dfsClient); listFileAction.setContext(smartContext); Map<String , String> args = new HashMap<>(); args.put(ListFileAction.FILE_PATH , srcPath); listFileAction.init(args); listFileAction.run(); Assert.assertTrue(listFileAction.getExpectedAfterRun()); listFileAction = new ListFileAction(); listFileAction.setDfsClient(dfsClient); listFileAction.setContext(smartContext); args = new HashMap<>(); args.put(ListFileAction.FILE_PATH , srcPath + "/" + file1); listFileAction.init(args); listFileAction.run(); Assert.assertTrue(listFileAction.getExpectedAfterRun()); }
|
### Question:
FileInfo { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FileInfo fileInfo = (FileInfo) o; return fileId == fileInfo.fileId && length == fileInfo.length && isdir == fileInfo.isdir && blockReplication == fileInfo.blockReplication && blocksize == fileInfo.blocksize && modificationTime == fileInfo.modificationTime && accessTime == fileInfo.accessTime && permission == fileInfo.permission && storagePolicy == fileInfo.storagePolicy && Objects.equals(path, fileInfo.path) && Objects.equals(owner, fileInfo.owner) && Objects.equals(group, fileInfo.group); } FileInfo(String path, long fileId, long length, boolean isdir,
short blockReplication, long blocksize, long modificationTime,
long accessTime, short permission, String owner, String group,
byte storagePolicy); String getPath(); void setPath(String path); long getFileId(); void setFileId(long fileId); long getLength(); void setLength(long length); boolean isdir(); void setIsdir(boolean isdir); short getBlockReplication(); void setBlockReplication(short blockReplication); long getBlocksize(); void setBlocksize(long blocksize); long getModificationTime(); void setModificationTime(long modificationTime); long getAccessTime(); void setAccessTime(long accessTime); short getPermission(); void setPermission(short permission); String getOwner(); void setOwner(String owner); String getGroup(); void setGroup(String group); byte getStoragePolicy(); void setStoragePolicy(byte storagePolicy); @Override boolean equals(Object o); @Override int hashCode(); static Builder newBuilder(); @Override String toString(); }### Answer:
@Test public void testEquals() throws Exception { FileInfo fileInfo = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", " ", (byte) 1); Assert.assertEquals(true, fileInfo.equals(fileInfo)); FileInfo fileInfo1 = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", " ", (byte) 1); Assert.assertEquals(true, fileInfo.equals(fileInfo1)); FileInfo fileInfo2 = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 1, null, " ", (byte) 1); Assert.assertEquals(false, fileInfo.equals(fileInfo2)); Assert.assertEquals(false, fileInfo2.equals(fileInfo)); FileInfo fileInfo3 = new FileInfo(null, 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", " ", (byte) 1); Assert.assertEquals(false, fileInfo.equals(fileInfo3)); Assert.assertEquals(false, fileInfo3.equals(fileInfo)); FileInfo fileInfo4 = new FileInfo(null, 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", null, (byte) 1); Assert.assertEquals(false, fileInfo.equals(fileInfo4)); Assert.assertEquals(false, fileInfo4.equals(fileInfo)); FileInfo fileInfo5 = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 2, " ", " ", (byte) 1); Assert.assertEquals(false, fileInfo.equals(fileInfo5)); }
|
### Question:
StringUtil { public static List<String> parseCmdletString(String cmdlet) throws ParseException { if (cmdlet == null || cmdlet.length() == 0) { return new ArrayList<>(); } char[] chars = (cmdlet + " ").toCharArray(); List<String> blocks = new ArrayList<String>(); char c; char[] token = new char[chars.length]; int tokenlen = 0; boolean sucing = false; boolean string = false; for (int idx = 0; idx < chars.length; idx++) { c = chars[idx]; if (c == ' ' || c == '\t') { if (string) { token[tokenlen++] = c; } if (sucing) { blocks.add(String.valueOf(token, 0, tokenlen)); tokenlen = 0; sucing = false; } } else if (c == ';') { if (string) { throw new ParseException("Unexpected break of string", idx); } if (sucing) { blocks.add(String.valueOf(token, 0, tokenlen)); tokenlen = 0; sucing = false; } } else if (c == '\\') { boolean tempAdded = false; if (sucing || string) { token[tokenlen++] = chars[++idx]; tempAdded = true; } if (!tempAdded && !sucing) { sucing = true; token[tokenlen++] = chars[++idx]; } } else if (c == '"') { if (sucing) { throw new ParseException("Unexpected \"", idx); } if (string) { if (chars[idx + 1] != '"') { string = false; blocks.add(String.valueOf(token, 0, tokenlen)); tokenlen = 0; } else { idx++; } } else { string = true; } } else if (c == '\r' || c == '\n') { if (sucing) { sucing = false; blocks.add(String.valueOf(token, 0, tokenlen)); tokenlen = 0; } if (string) { throw new ParseException("String cannot in more than one line", idx); } } else { if (string) { token[tokenlen++] = chars[idx]; } else { sucing = true; token[tokenlen++] = chars[idx]; } } } if (string) { throw new ParseException("Unexpected tail of string", chars.length); } return blocks; } static String join(CharSequence delimiter,
Iterable<? extends CharSequence> elements); static String getBaseDir(String path); static String globString2SqlLike(String str); static long pharseTimeString(String str); static List<String> parseCmdletString(String cmdlet); }### Answer:
@Test public void testCmdletString() throws Exception { Map<String, Integer> strs = new HashMap<>(); strs.put("int a b -c d -e f \"gg ' kk ' ff\" \" mn \"", 9); strs.put("cat /dir/file ", 2); List<String> items; for (String str : strs.keySet()) { items = StringUtil.parseCmdletString(str); Assert.assertTrue(strs.get(str) == items.size()); System.out.println(items.size() + " -> " + str); } }
|
### Question:
SecurityUtil { public static void loginUsingKeytab(SmartConf conf) throws IOException{ String keytabFilename = conf.get(SmartConfKeys.SMART_SERVER_KEYTAB_FILE_KEY); if (keytabFilename == null || keytabFilename.length() == 0) { throw new IOException("Running in secure mode, but config doesn't have a keytab"); } File keytabPath = new File(keytabFilename); String principal = conf.get(SmartConfKeys.SMART_SERVER_KERBEROS_PRINCIPAL_KEY); try { SecurityUtil.loginUsingKeytab(principal, keytabPath.getAbsolutePath()); } catch (IOException e) { LOG.error("Fail to login using keytab. " + e); throw new IOException("Fail to login using keytab. " + e); } LOG.info("Login successful for user: " + principal); } static synchronized Subject loginUserFromTgtTicket(String smartSecurity); static Subject loginUsingTicketCache(String principal); static void loginUsingKeytab(SmartConf conf); static void loginUsingKeytab(String keytabFilename, String principal); static Subject loginUsingKeytab(
String principal, File keytabFile); static Configuration useTicketCache(String principal, String ticketCacheFileName); static Configuration useKeytab(String principal, File keytabFile); static boolean isSecurityEnabled(SmartConf conf); static final Logger LOG; static final boolean ENABLE_DEBUG; }### Answer:
@Test public void loginUsingKeytab() throws Exception { File keytabFile = generateKeytab(keytabFileName, principal); Subject subject = SecurityUtil.loginUsingKeytab(principal, keytabFile); Assert.assertEquals(principal, subject.getPrincipals().iterator().next().getName()); System.out.println("Login successful for user: " + subject.getPrincipals().iterator().next()); }
|
### Question:
CustomerOrderExtractor implements PayloadWrapperExtractor<CustomerOrderPayload, CustomerOrder> { @Override public CustomerOrder extractData(PayloadWrapper<CustomerOrderPayload> payloadWrapper) { CustomerOrder value = null; if (payloadWrapper.hasPayload()) { value = new CustomerOrder(); CustomerOrderPayload payload = payloadWrapper.getPayload(); value.setCustomerId(payload.getCustomerId()); value.setShippingAddress(payload.getShippingAddress()); value.setOrderDate(payload.getOrderDate()); value.setItemSet(payload.getItemSet()); } return value; } @Override CustomerOrder extractData(PayloadWrapper<CustomerOrderPayload> payloadWrapper); }### Answer:
@Test public void testExtractData() { CustomerOrderExtractor extractor = new CustomerOrderExtractor(); PayloadWrapper<CustomerOrderPayload> payloadWrapper = new PayloadWrapper<CustomerOrderPayload>(null); assertThat(extractor.extractData(payloadWrapper)).isNull(); Date orderDate = new Date(); List<String> items = Arrays.asList("item1", "item2"); CustomerOrderPayload payload = new CustomerOrderPayload(); payload.setId("id"); payload.setCustomerId("customerId"); payload.setOrderDate(orderDate.getTime()); payload.setShippingAddress("shippingAddress"); payload.setItemSet(new HashSet<>(items)); payloadWrapper = new PayloadWrapper<CustomerOrderPayload>(payload); CustomerOrder expected = new CustomerOrder(); expected.setCustomerId("customerId"); expected.setOrderDate(orderDate.getTime()); expected.setShippingAddress("shippingAddress"); expected.setItemSet(new HashSet<>(items)); assertThat(extractor.extractData(payloadWrapper)).isEqualTo(expected); }
|
### Question:
ItemExtractor implements PayloadWrapperExtractor<ItemPayload, Item> { @Override public Item extractData(PayloadWrapper<ItemPayload> payloadWrapper) { Item value = null; if (payloadWrapper.hasPayload()) { value = new Item(); ItemPayload payload = payloadWrapper.getPayload(); value.setName(payload.getName()); value.setDescription(payload.getDescription()); value.setPrice(payload.getPrice().toString()); } return value; } @Override Item extractData(PayloadWrapper<ItemPayload> payloadWrapper); }### Answer:
@Test public void testExtractData() { ItemExtractor extractor = new ItemExtractor(); PayloadWrapper<ItemPayload> payloadWrapper = new PayloadWrapper<ItemPayload>(null); assertThat(extractor.extractData(payloadWrapper)).isNull(); ItemPayload payload = new ItemPayload(); payload.setId("id"); payload.setName("name"); payload.setDescription("description"); payload.setPrice(new BigDecimal("9.99")); payloadWrapper = new PayloadWrapper<ItemPayload>(payload); Item expected = new Item(); expected.setName("name"); expected.setDescription("description"); expected.setPrice("9.99"); assertThat(extractor.extractData(payloadWrapper)).isEqualTo(expected); }
|
### Question:
CustomerExtractor implements PayloadWrapperExtractor<CustomerPayload, Customer> { @Override public Customer extractData(PayloadWrapper<CustomerPayload> payloadWrapper) { Customer value = null; if (payloadWrapper.hasPayload()) { value = new Customer(); CustomerPayload payload = payloadWrapper.getPayload(); value.setName(payload.getName()); } return value; } @Override Customer extractData(PayloadWrapper<CustomerPayload> payloadWrapper); }### Answer:
@Test public void testExtractData() { CustomerExtractor extractor = new CustomerExtractor(); PayloadWrapper<CustomerPayload> payloadWrapper = new PayloadWrapper<CustomerPayload>(null); assertThat(extractor.extractData(payloadWrapper)).isNull(); CustomerPayload payload = new CustomerPayload(); payload.setId("id"); payload.setName("name"); payloadWrapper = new PayloadWrapper<CustomerPayload>(payload); Customer expected = new Customer(); expected.setName("name"); assertThat(extractor.extractData(payloadWrapper)).isEqualTo(expected); }
|
### Question:
ItemResultSetExtractor implements ResultSetExtractor<PayloadWrapper<ItemPayload>> { @Override public PayloadWrapper<ItemPayload> extractData(ResultSet rs) throws SQLException, DataAccessException { ItemPayload itemPayload = null; if (rs.next()) { itemPayload = new ItemPayload(); itemPayload.setId(rs.getString("ID")); itemPayload.setName(rs.getString("NAME")); itemPayload.setPrice(rs.getBigDecimal("PRICE")); itemPayload.setDescription(rs.getString("DESCRIPTION")); } return new PayloadWrapper<>(itemPayload); } @Override PayloadWrapper<ItemPayload> extractData(ResultSet rs); }### Answer:
@Test public void testExtractData() throws SQLException { ItemResultSetExtractor extractor = new ItemResultSetExtractor(); ResultSet rs = mock(ResultSet.class); given(rs.next()).willReturn(true).willReturn(false); given(rs.getString("ID")).willReturn("item1"); given(rs.getString("NAME")).willReturn("item name"); given(rs.getString("DESCRIPTION")).willReturn("description"); given(rs.getBigDecimal("PRICE")).willReturn(new BigDecimal("1.99")); ItemPayload payload = new ItemPayload(); payload.setId("item1"); payload.setName("item name"); payload.setDescription("description"); payload.setPrice(new BigDecimal("1.99")); PayloadWrapper<ItemPayload> payloadWrapper = new PayloadWrapper<ItemPayload>(payload); assertThat(extractor.extractData(rs)).isEqualTo(payloadWrapper); }
|
### Question:
CustomerResultSetExtractor implements ResultSetExtractor<PayloadWrapper<CustomerPayload>> { @Override public PayloadWrapper<CustomerPayload> extractData(ResultSet rs) throws SQLException, DataAccessException { CustomerPayload customerPayload = null; if (rs.next()) { customerPayload = new CustomerPayload(); customerPayload.setId(rs.getString("ID")); customerPayload.setName(rs.getString("NAME")); } return new PayloadWrapper<>(customerPayload); } @Override PayloadWrapper<CustomerPayload> extractData(ResultSet rs); }### Answer:
@Test public void testExtractData() throws DataAccessException, SQLException { CustomerResultSetExtractor extractor = new CustomerResultSetExtractor(); ResultSet rs = mock(ResultSet.class); given(rs.next()).willReturn(true).willReturn(false); given(rs.getString("ID")).willReturn("customer1"); given(rs.getString("NAME")).willReturn("customer name"); CustomerPayload payload = new CustomerPayload(); payload.setId("customer1"); payload.setName("customer name"); PayloadWrapper<CustomerPayload> payloadWrapper = new PayloadWrapper<CustomerPayload>(payload); assertThat(extractor.extractData(rs)).isEqualTo(payloadWrapper); }
|
### Question:
CustomerOrderResultSetExtractor implements ResultSetExtractor<PayloadWrapper<CustomerOrderPayload>> { @Override public PayloadWrapper<CustomerOrderPayload> extractData(ResultSet rs) throws SQLException, DataAccessException { CustomerOrderPayload result = null; while (rs.next()) { if (result == null) { result = new CustomerOrderPayload(); result.setId(rs.getString("ID")); result.setCustomerId(rs.getString("CUSTOMER_ID")); result.setShippingAddress(rs.getString("S_ADDRESS")); result.setOrderDate(rs.getDate("ORDER_TS").getTime()); result.setItemSet(new HashSet<String>()); } result.getItemSet().add(rs.getString("ITEM_ID")); } return new PayloadWrapper<>(result); } @Override PayloadWrapper<CustomerOrderPayload> extractData(ResultSet rs); }### Answer:
@Test public void testExtractData() throws DataAccessException, SQLException { Date orderDate = new Date(12345L); List<String> items = Arrays.asList("item1", "item2"); CustomerOrderResultSetExtractor extractor = new CustomerOrderResultSetExtractor(); ResultSet rs = mock(ResultSet.class); given(rs.next()).willReturn(true).willReturn(true).willReturn(false); given(rs.getString("ID")).willReturn("order1"); given(rs.getString("CUSTOMER_ID")).willReturn("customer1"); given(rs.getString("S_ADDRESS")).willReturn("address"); given(rs.getDate("ORDER_TS")).willReturn(orderDate); given(rs.getString("ITEM_ID")).willReturn("item1").willReturn("item2"); CustomerOrderPayload payload = new CustomerOrderPayload(); payload.setId("order1"); payload.setCustomerId("customer1"); payload.setOrderDate(orderDate.getTime()); payload.setShippingAddress("address"); payload.setItemSet(new HashSet<>(items)); PayloadWrapper<CustomerOrderPayload> payloadWrapper = new PayloadWrapper<CustomerOrderPayload>(payload); assertThat(extractor.extractData(rs)).isEqualTo(payloadWrapper); }
|
### Question:
GeodeMessageAggregator { @Aggregator public GeodeDataWrapper output(List<Message<PayloadWrapper>> messages) { GeodeDataWrapper geodeDataWrapper = new GeodeDataWrapper(); for (Message<PayloadWrapper> message : messages) { String geodeRegionName = (String) message.getHeaders().get("srcGroup"); Object geodeKey = message.getHeaders().get("srcKey"); PayloadWrapper<?> payloadWrapper = message.getPayload(); PayloadWrapperExtractor extractor = (PayloadWrapperExtractor) context.getBean(geodeRegionName + "Extractor"); if(payloadWrapper.hasPayload()){ geodeDataWrapper.getKeySetForRemove().remove(geodeKey); geodeDataWrapper.getDataMapForPut().put(geodeKey, extractor.extractData(payloadWrapper)); } else { geodeDataWrapper.getDataMapForPut().remove(geodeKey); geodeDataWrapper.getKeySetForRemove().add(geodeKey); } } return geodeDataWrapper; } GeodeMessageAggregator(ApplicationContext context, int groupCount, int batchSize); @Aggregator GeodeDataWrapper output(List<Message<PayloadWrapper>> messages); @CorrelationStrategy String correlation(Message<?> message); @ReleaseStrategy boolean canMessagesBeReleased(List<Message<?>> messages); }### Answer:
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testOutput() { List<Message<PayloadWrapper>> messages = new ArrayList<>(); Message<PayloadWrapper> message1 = MessageBuilder .withPayload(new PayloadWrapper(new Object())) .setHeader("srcGroup", "foo") .setHeader("srcKey", "key1") .build(); messages.add(message1); Message<PayloadWrapper> message2 = MessageBuilder .withPayload(new PayloadWrapper(new Object())) .setHeader("srcGroup", "foo") .setHeader("srcKey", "key2") .build(); messages.add(message2); Message<PayloadWrapper> message3 = MessageBuilder .withPayload(new PayloadWrapper(null)) .setHeader("srcGroup", "foo") .setHeader("srcKey", "key1") .build(); messages.add(message3); GeodeDataWrapper geodeDataWrapper = geodeMessageAggregator.output(messages); assertThat(geodeDataWrapper.getDataMapForPut().containsKey("key1"), is(false)); assertThat(geodeDataWrapper.getDataMapForPut().containsKey("key2"), is(true)); }
|
### Question:
GeodeMessageAggregator { @CorrelationStrategy public String correlation(Message<?> message) { int hashCode = message.getHeaders().get("srcKey").hashCode(); int divisor = groupCount; return "[" + (String) message.getHeaders().get("srcGroup") + "]" + ",[" + Math.floorMod(hashCode, divisor) + "]"; } GeodeMessageAggregator(ApplicationContext context, int groupCount, int batchSize); @Aggregator GeodeDataWrapper output(List<Message<PayloadWrapper>> messages); @CorrelationStrategy String correlation(Message<?> message); @ReleaseStrategy boolean canMessagesBeReleased(List<Message<?>> messages); }### Answer:
@Test public void testCorrelation() { Message<PayloadWrapper<Object>> message = MessageBuilder .withPayload(new PayloadWrapper<Object>(new Object())) .setHeader("srcGroup", "foo") .setHeader("srcKey", "key1") .build(); String expectedResult = "[foo],[" + Math.floorMod("key1".hashCode(), groupCount) + "]"; assertThat(geodeMessageAggregator.correlation(message), is(expectedResult)); }
|
### Question:
GeodeMessageAggregator { @ReleaseStrategy public boolean canMessagesBeReleased(List<Message<?>> messages) { return messages.size() >= batchSize; } GeodeMessageAggregator(ApplicationContext context, int groupCount, int batchSize); @Aggregator GeodeDataWrapper output(List<Message<PayloadWrapper>> messages); @CorrelationStrategy String correlation(Message<?> message); @ReleaseStrategy boolean canMessagesBeReleased(List<Message<?>> messages); }### Answer:
@Test public void testCanMessagesBeReleased() { List<Message<?>> messages = new ArrayList<>(); Message<PayloadWrapper<Object>> message1 = MessageBuilder .withPayload(new PayloadWrapper<Object>(null)) .setHeader("srcGroup", "foo") .setHeader("srcKey", "key1") .build(); messages.add(message1); assertThat(geodeMessageAggregator.canMessagesBeReleased(messages), is(false)); Message<PayloadWrapper<Object>> message2 = MessageBuilder .withPayload(new PayloadWrapper<>(new Object())) .setHeader("srcGroup", "foo") .setHeader("srcKey", "key2") .build(); messages.add(message2); assertThat(geodeMessageAggregator.canMessagesBeReleased(messages), is(true)); }
|
### Question:
GeodeMessageHandler { public void handleMessage(Message<GeodeDataWrapper> message) { MessageHeaders headers = message.getHeaders(); GeodeDataWrapper payload = message.getPayload(); String regionName = (String) headers.get("srcGroup"); Region<Object, Object> region = clientCache.getRegion(regionName); region.putAll(payload.getDataMapForPut()); region.removeAll(payload.getKeySetForRemove()); } GeodeMessageHandler(ClientCache clientCache); void handleMessage(Message<GeodeDataWrapper> message); }### Answer:
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testHandleMessage() { GeodeDataWrapper geodeDataWrapper = new GeodeDataWrapper(); geodeDataWrapper.getDataMapForPut().put("key1", "value1"); geodeDataWrapper.getDataMapForPut().put("key2", "value2"); geodeDataWrapper.getKeySetForRemove().add("key1"); Message<GeodeDataWrapper> message = MessageBuilder .withPayload(geodeDataWrapper) .setHeader("srcGroup", "foo") .build(); geodeMessageHandler.handleMessage(message); ArgumentCaptor<Map> mapCaptor = ArgumentCaptor.forClass(Map.class); verify(region, times(1)).putAll(mapCaptor.capture()); assertThat(geodeDataWrapper.getDataMapForPut(), is(mapCaptor.getValue())); ArgumentCaptor<Set> setCaptor = ArgumentCaptor.forClass(Set.class); verify(region, times(1)).removeAll(setCaptor.capture()); assertThat(geodeDataWrapper.getDataMapForPut(), is(mapCaptor.getValue())); }
|
### Question:
DropboxAPI { public Account accountInfo() throws DropboxException { assertAuthenticated(); @SuppressWarnings("unchecked") Map<String, Object> accountInfo = (Map<String, Object>) RESTUtility.request(RequestMethod.GET, session.getAPIServer(), "/account/info", VERSION, new String[] {"locale", session.getLocale().toString()}, session); return new Account(accountInfo); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void accountInfo() throws Exception { Account info = api.accountInfo(); assert info.country != null : "No country for account"; assert info.displayName != null : "No displayName for account"; assert info.quota > 0 : "0 quota in account"; assert info.quotaNormal > 0 : "0 normal quota in account"; assert info.referralLink != null : "No referral link for account"; assert info.uid > 0 : "No uid for account"; }
|
### Question:
DropboxAPI { public Entry copy(String fromPath, String toPath) throws DropboxException { assertAuthenticated(); String[] params = {"root", session.getAccessType().toString(), "from_path", fromPath, "to_path", toPath, "locale", session.getLocale().toString()}; @SuppressWarnings("unchecked") Map<String, Object> resp = (Map<String, Object>)RESTUtility.request( RequestMethod.POST, session.getAPIServer(), "/fileops/copy", VERSION, params, session); return new Entry(resp); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void copy() throws Exception { String fromPath = TESTS_DIR + "/copyFrom.jpg"; String toPath = TESTS_DIR + "/copyTo.jpg"; uploadFile(frog, fromPath); Entry ent = api.copy(fromPath, toPath); assertFile(ent, frog, toPath); ent = api.metadata(toPath, 1, null, false, null); assertFile(ent, frog, toPath); }
|
### Question:
DropboxAPI { public Entry move(String fromPath, String toPath) throws DropboxException { assertAuthenticated(); String[] params = {"root", session.getAccessType().toString(), "from_path", fromPath, "to_path", toPath, "locale", session.getLocale().toString()}; @SuppressWarnings("unchecked") Map<String, Object> resp = (Map<String, Object>)RESTUtility.request( RequestMethod.POST, session.getAPIServer(), "/fileops/move", VERSION, params, session); return new Entry(resp); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void move() throws Exception { String fromPath = TESTS_DIR + "/moveFrom.jpg"; String toPath = TESTS_DIR + "/moveTo.jpg"; uploadFile(frog, fromPath); Entry moveEnt = api.move(fromPath, toPath); assertFile(moveEnt, frog, toPath); moveEnt = api.metadata(toPath, 1, null, false, null); assertFile(moveEnt, frog, toPath); Entry oldEnt = api.metadata(fromPath, 1, null, false, null); assertEquals(oldEnt.isDeleted, true); assertEquals(oldEnt.bytes, 0); assert oldEnt.isDeleted; }
|
### Question:
DropboxAPI { public DropboxLink media(String path, boolean ssl) throws DropboxException { assertAuthenticated(); String target = "/media/" + session.getAccessType() + path; @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)RESTUtility.request(RequestMethod.GET, session.getAPIServer(), target, VERSION, new String[] {"locale", session.getLocale().toString()}, session); return new DropboxLink(map, ssl); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void media() throws Exception { String path = TESTS_DIR + "/dropbox_song.mp3"; uploadFile(song, path); DropboxLink link = api.media(path, true); assert link.url != null : "No url for streamed file"; link = api.media(path, false); assert link.url != null : "No insecure url for streamed file"; }
|
### Question:
DropboxAPI { public DropboxLink share(String path) throws DropboxException { assertAuthenticated(); String target = "/shares/" + session.getAccessType() + path; @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)RESTUtility.request(RequestMethod.GET, session.getAPIServer(), target, VERSION, new String[] {"locale", session.getLocale().toString()}, session); String url = (String)map.get("url"); Date expires = RESTUtility.parseDate((String)map.get("expires")); if (url == null || expires == null) { throw new DropboxParseException("Could not parse share response."); } return new DropboxLink(map); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void share() throws Exception{ String path = TESTS_DIR + "/dropbox_song.mp3"; uploadFile(song, path); DropboxLink link = api.share(path); assert link.url != null : "No url for streamed file"; }
|
### Question:
DropboxAPI { public Entry metadata(String path, int fileLimit, String hash, boolean list, String rev) throws DropboxException { assertAuthenticated(); if (fileLimit <= 0) { fileLimit = METADATA_DEFAULT_LIMIT; } String[] params = { "file_limit", String.valueOf(fileLimit), "hash", hash, "list", String.valueOf(list), "rev", rev, "locale", session.getLocale().toString() }; String url_path = "/metadata/" + session.getAccessType() + path; @SuppressWarnings("unchecked") Map<String, Object> dirinfo = (Map<String, Object>) RESTUtility.request(RequestMethod.GET, session.getAPIServer(), url_path, VERSION, params, session); return new Entry(dirinfo); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void getMetadataBad() throws Exception { try { String path = TESTS_DIR + "iDoNotExist.txt"; Entry ent = api.metadata(path, 1000, null, true, null); assert ent.isDeleted: "The " + path + " directory should not exist"; } catch (DropboxServerException e) { if (e.error != DropboxServerException._404_NOT_FOUND) { assert false: "Unexpected Dropbox Server Error: " + e.toString(); } } catch (DropboxException e) { assert false: "Unexpected Dropbox Error: " + e.toString(); } }
@Test public void getMetadata() throws Exception { String path = TESTS_DIR + "/metadatasong.mp3"; uploadFile(song, path); api.metadata(path, 1000, null, true, null); }
@Test public void getMetadataCached() throws Exception { try { Entry ent = api.metadata(TESTS_DIR, 1000, null, true, null); api.metadata(TESTS_DIR, 1000, ent.hash, true, null); assert false : "Directory should have been cached"; } catch (DropboxServerException e) { if (e.error != DropboxServerException._304_NOT_MODIFIED) { assert false: "Unexpected Dropbox Server Error: " + e.toString(); } } catch (DropboxException e) { assert false: "Unexpected Dropbox Error: " + e.toString(); } }
|
### Question:
DropboxAPI { public Entry createFolder(String path) throws DropboxException { assertAuthenticated(); String[] params = {"root", session.getAccessType().toString(), "path", path, "locale", session.getLocale().toString()}; @SuppressWarnings("unchecked") Map<String, Object> resp = (Map<String, Object>) RESTUtility.request( RequestMethod.POST, session.getAPIServer(), "/fileops/create_folder", VERSION, params, session); return new Entry(resp); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void createFolder() throws Exception { String path = TESTS_DIR + "createdFolder"; Entry ent = api.createFolder(path); assertEquals(ent.isDir, true); }
@Test public void createFolderDupe() throws Exception { try { api.createFolder(TESTS_DIR); assert false : "Able to create duplicate folder"; } catch (DropboxServerException e) { if (e.error != DropboxServerException._403_FORBIDDEN) { assert false: "Unexpected Dropbox Server Error: " + e.toString(); } } catch (DropboxException e) { assert false: "Unexpected Dropbox Error: " + e.toString(); } }
|
### Question:
DropboxAPI { public Entry putFile(String path, InputStream is, long length, String parentRev, ProgressListener listener) throws DropboxException { UploadRequest request = putFileRequest(path, is, length, parentRev, listener); return request.upload(); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void putFile() throws Exception { assertPutFile(foo, TESTS_DIR + "/putfoo.txt"); assertPutFile(frog, TESTS_DIR + "/putfrog.jpg"); assertPutFile(song, TESTS_DIR + "/putsong.mp3"); }
|
### Question:
DropboxAPI { public DropboxFileInfo getFile(String path, String rev, OutputStream os, ProgressListener listener) throws DropboxException { DropboxInputStream dis = getFileStream(path, rev); dis.copyStreamToOutput(os, listener); return dis.getFileInfo(); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void getFile() throws Exception { assertGetFile(foo, TESTS_DIR + "/getfoo.txt"); assertGetFile(song, TESTS_DIR + "/getsong.mp3"); assertGetFile(frog, TESTS_DIR + "/getfrog.jpg"); }
|
### Question:
DropboxAPI { public DropboxFileInfo getThumbnail(String path, OutputStream os, ThumbSize size, ThumbFormat format, ProgressListener listener) throws DropboxException { DropboxInputStream thumb = getThumbnailStream(path, size, format); thumb.copyStreamToOutput(os, listener); return thumb.getFileInfo(); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void getThumbnail() throws Exception { String path = TESTS_DIR + "/thumbnailfrog.jpg"; uploadFile(frog, path); OutputStream out = new ByteArrayOutputStream(); DropboxFileInfo info = api.getThumbnail(path, out, ThumbSize.BESTFIT_480x320, ThumbFormat.JPEG, null); assert info != null : "No info returned"; assert info.getFileSize() > 0 : "Thumbnail length 0"; assert info.getMetadata().bytes > 0 : "Original file size 0"; assert info.getFileSize() != info.getMetadata().bytes : "Thumbnail equals original file size."; }
|
### Question:
DropboxAPI { public DropboxInputStream getThumbnailStream(String path, ThumbSize size, ThumbFormat format) throws DropboxException { assertAuthenticated(); String target = "/thumbnails/" + session.getAccessType() + path; String[] params = {"size", size.toAPISize(), "format", format.toString(), "locale", session.getLocale().toString()}; RequestAndResponse rr = RESTUtility.streamRequest(RequestMethod.GET, session.getContentServer(), target, VERSION, params, session); return new DropboxInputStream(rr.request, rr.response); } DropboxAPI(SESS_T session); ChunkedUploader getChunkedUploader(InputStream is, long length); ChunkedUploader getChunkedUploader(InputStream is, long length, int chunkSize); ChunkedUploadRequest chunkedUploadRequest(InputStream is, long length,
ProgressListener listener,
long offset, String uploadId); SESS_T getSession(); Account accountInfo(); DropboxFileInfo getFile(String path, String rev, OutputStream os,
ProgressListener listener); DropboxInputStream getFileStream(String path, String rev); Entry putFile(String path, InputStream is, long length,
String parentRev, ProgressListener listener); UploadRequest putFileRequest(String path, InputStream is,
long length, String parentRev, ProgressListener listener); Entry putFileOverwrite(String path, InputStream is, long length,
ProgressListener listener); UploadRequest putFileOverwriteRequest(String path, InputStream is,
long length, ProgressListener listener); DropboxFileInfo getThumbnail(String path, OutputStream os,
ThumbSize size, ThumbFormat format, ProgressListener listener); DropboxInputStream getThumbnailStream(String path, ThumbSize size,
ThumbFormat format); Entry metadata(String path, int fileLimit, String hash,
boolean list, String rev); @SuppressWarnings("unchecked") List<Entry> revisions(String path, int revLimit); List<Entry> search(String path, String query, int fileLimit,
boolean includeDeleted); Entry move(String fromPath, String toPath); Entry copy(String fromPath, String toPath); Entry createFolder(String path); void delete(String path); Entry restore(String path, String rev); DropboxLink media(String path, boolean ssl); DropboxLink share(String path); DeltaPage<Entry> delta(String cursor); CreatedCopyRef createCopyRef(String sourcePath); Entry addFromCopyRef(String sourceCopyRef, String targetPath); static final int VERSION; static final String SDK_VERSION; static final long MAX_UPLOAD_SIZE; }### Answer:
@Test public void getThumbnailStream() throws Exception { String path = TESTS_DIR + "/thumbnailstreamfrog.jpg"; uploadFile(frog, path); DropboxInputStream is = api.getThumbnailStream(path, ThumbSize.BESTFIT_480x320, ThumbFormat.JPEG); assert is != null : "No info returned"; assert is.getFileInfo().getFileSize() > 0 : "Thumbnail length 0"; assert is.getFileInfo().getMetadata().bytes > 0 : "Original file size 0"; }
|
### Question:
RollingNumber { public double getAvg(CounterDataType counterDataType) { long latestRollingSum = getTotalSum(counterDataType); return (double)(latestRollingSum) / intervals; } RollingNumber(); void addOne(CounterDataType dataType); void add(CounterDataType dataType, long value); long getTotalSum(CounterDataType dataType); double getAvg(CounterDataType counterDataType); }### Answer:
@Test public void test() { for (int i = 0; i < 10; i++) { new Thread(() -> { while (true) { testMock(); } }).start(); } new Thread(() -> { try { while (true) { Thread.sleep(1000); System.out.println(rollingNumber.getAvg(CounterDataType.PASSED)); } } catch (Exception e) { } }).start(); try { System.in.read(); } catch (Exception e) { } System.out.println("程序退出"); }
|
### Question:
FileUtils { public static List<File> getFileListByPath(String path) { return getFileListByPath(path, null); } static String getExtension(String fileName); static void writeByteArrayToFile(File file, byte[] data, boolean append); static byte[] readFileToByteArray(File file); static void writeStringToFile(File file, String data, String encoding, boolean append); static String readFileToString(File file, String encoding); static String byteCountToDisplaySize(long size); static void moveDirectoryToDirectory(File src, File destDir, boolean isCover); static void moveFileToDirectory(File srcFile, File destDir, boolean isCover); static void moveFile(File srcFile, File destFile, boolean isCover); static void copyDirectoryToDirectory(File srcDir, File destDir); static void copyDirectoryToDirectory(File srcDir, File destDir, FileFilter filter); static void copyFileToDirectory(File srcFile, File destDir); static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate); static void copyFile(File srcFile, File destFile); static void copyFile(File srcFile, File destFile, boolean preserveFileDate); static void deleteFileOrDirectoryQuietly(String filePath); static void deleteFileOrDirectory(String filePath, boolean deleteThisPath); static List<File> getFileListByPath(String path); static List<File> getFileListByPath(String path, FileFilter filter); static Properties readProperties(String path); static Properties readProperties(InputStream in); static void writeProperties(String path, Properties properties); static final String EMPTY; static final long ONE_KB; static final long ONE_MB; static final long ONE_GB; static final long ONE_TB; static final long ONE_PB; static final long ONE_EB; }### Answer:
@Test public void testGetFileListByPath() { List<File> fileList = FileUtils.getFileListByPath("/Users/xuan/Desktop/xuan"); for (File f : fileList) { System.out.println(f.getName()); } }
|
### Question:
Validators { public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } static boolean isAlphanumeric(String str); static boolean isBlank(String str); static boolean isDate(String str); static boolean isDateTime(String str); static boolean isEmail(String str); static boolean isEmpty(Object[] args); static boolean isEmpty(String str); static boolean isEmpty(Collection<T> collection); static boolean isEmptyMap(Map<K, V> map); static boolean isIdCardNumber(String str); static boolean isNumber(String str); static boolean isNumber(String str, int min, int max); static boolean isNumeric(String str); static boolean isNumeric(String str, int fractionNum); static boolean isPostcode(String str); static boolean isString(String str, int minLength, int maxLength); static boolean isTime(String str); static boolean isSimpleChinese(String str); static boolean isRegexMatch(String str, String regex); }### Answer:
@Test public void testIsBlank(){ Assert.assertTrue(Validators.isBlank(null)); Assert.assertTrue(Validators.isBlank("")); Assert.assertTrue(Validators.isBlank(" ")); Assert.assertTrue(!Validators.isBlank("bob")); Assert.assertTrue(!Validators.isBlank(" bob ")); }
|
### Question:
MathUtils { public static double add(double v1, double v2) { BigDecimal b1 = createBigDecimal(v1); BigDecimal b2 = createBigDecimal(v2); return b1.add(b2).doubleValue(); } static double add(double v1, double v2); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static boolean isInvalidDouble(double v); static double mul(double v1, double v2); static double round(double v, int scale); static double sub(double v1, double v2); }### Answer:
@Test public void testAdd() { System.out.println(MathUtils.add(1.1d, 1.2d)); }
|
### Question:
Diverter { public boolean isHit(long bizId) { return hitNum(bizId) >= 0; } Diverter(DiverterConfig config); boolean isHit(long bizId); long hitNum(long bizId); }### Answer:
@Test public void test() { for (long i = 0; i < 100; i++) { boolean hit = diverter.isHit(i); System.out.println("i=" + i + ".hit=" + hit); } }
|
### Question:
UUIDUtils { public static String uuid() { return uuid.generateHex(); } private UUIDUtils(); byte[] generateBytes(); static String uuid(); }### Answer:
@Test public void testUuid() { Set<String> idSet = new HashSet<>(); for (int i = 0; i < 50; i++) { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 30000; i++) { String uuid = UUIDUtils.uuid(); if (idSet.contains(uuid)) { System.out.println("++++++++++uuid重复:" + uuid); } } } }).start(); } }
|
### Question:
LocalKvUtils { public static String get(String path, String key) { Properties properties = getPropertiesFromPath(path); if (null == properties) { return null; } return properties.getProperty(key); } static void put(String path, String key, String value); static void put(String path, Map<String, String> map); static String get(String path, String key); static void remove(String path, String key); static void removeAll(String path); static void writeProperties(String path, Properties properties); }### Answer:
@Test public void testGet() { String install = LocalKvUtils.get(path, "install"); System.out.println("==========>" + install); }
|
### Question:
LocalKvUtils { public static void put(String path, String key, String value) { Properties properties = getPropertiesFromPath(path); if (null == properties) { return; } properties.put(key, value); writeProperties(path, properties); } static void put(String path, String key, String value); static void put(String path, Map<String, String> map); static String get(String path, String key); static void remove(String path, String key); static void removeAll(String path); static void writeProperties(String path, Properties properties); }### Answer:
@Test public void testPut() { LocalKvUtils.put(path, "install", "2"); LocalKvUtils.put(path, "test", "200"); }
|
### Question:
LocalKvUtils { public static void remove(String path, String key) { Properties properties = getPropertiesFromPath(path); if (null == properties) { return; } properties.remove(key); writeProperties(path, properties); } static void put(String path, String key, String value); static void put(String path, Map<String, String> map); static String get(String path, String key); static void remove(String path, String key); static void removeAll(String path); static void writeProperties(String path, Properties properties); }### Answer:
@Test public void testRemove() { LocalKvUtils.remove(path, "test"); }
|
### Question:
LocalKvUtils { public static void removeAll(String path) { if (null == path) { return; } File file = new File(path); if (file.exists()) { file.delete(); } } static void put(String path, String key, String value); static void put(String path, Map<String, String> map); static String get(String path, String key); static void remove(String path, String key); static void removeAll(String path); static void writeProperties(String path, Properties properties); }### Answer:
@Test public void testRemoveAll() { LocalKvUtils.removeAll(path); }
|
### Question:
Map2BeanUtils { public static <T> T map2Bean(Map<String, Object> map, Class<T> beanClass) { T obj; try { obj = beanClass.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(beanClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (!map.containsKey(key)) { continue; } Object value = map.get(key); Method setter = property.getWriteMethod(); setter.invoke(obj, value); } } catch (Exception e) { throw new RuntimeException(e); } return obj; } static T map2Bean(Map<String, Object> map, Class<T> beanClass); static Map<String, Object> bean2Map(Object obj); }### Answer:
@Test public void testMap2Bean() { Map<String, Object> map = new HashMap<>(); map.put("name", "xuan"); map.put("age", 18); map.put("sonName", "xuanson"); Son user = Map2BeanUtils.map2Bean(map, Son.class); System.out.println("++++++++++user:" + user.getName() + "---" + user.getAge() + "---" + user.getSonName()); }
|
### Question:
Map2BeanUtils { public static Map<String, Object> bean2Map(Object obj) { if (obj == null) { return null; } Map<String, Object> map = new HashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (key.equals("class")) { continue; } Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, value); } } catch (Exception e) { throw new RuntimeException(e); } return map; } static T map2Bean(Map<String, Object> map, Class<T> beanClass); static Map<String, Object> bean2Map(Object obj); }### Answer:
@Test public void testBean2Map(){ Son user = new Son(); user.setName("xuan"); user.setAge(20); user.setSonName("xuanson"); Map map = Map2BeanUtils.bean2Map(user); System.out.println("++++++++++map:" + map); }
@Test public void testBean2Map2(){ Son son = new Son(); son.setSonName("sonName"); son.setAge(20); son.setName("name"); Son2 son2 = new Son2(); son2.setSon2Name("son2Name"); son2.setAge(22); son2.setName("name2"); Father father = new Father(); father.setAge(88); father.setName("name3"); Family family = new Family(); family.setSon(son); family.setSon2(son2); family.setFather(father); Map map = Map2BeanUtils.bean2Map(family); System.out.println("++++++++++map:" + map); }
|
### Question:
JavaCommOpenHandler extends CommOpenHandler { public Handler<Message>[] getKernelControlChanelHandlers(String targetName){ if(TargetNamesEnum.KERNEL_CONTROL_CHANNEL.getTargetName().equalsIgnoreCase(targetName)){ return (Handler<Message>[]) KERNEL_CONTROL_CHANNEL_HANDLERS; }else{ return (Handler<Message>[]) new Handler<?>[0]; } } JavaCommOpenHandler(KernelFunctionality kernel); Handler<Message>[] getKernelControlChanelHandlers(String targetName); }### Answer:
@Test public void getControlHandlersWithEmptyString_returnEmptyHandlersArray() throws Exception { Handler<Message>[] handlers = commOpenHandler.getKernelControlChanelHandlers(""); Assertions.assertThat(handlers).isEmpty(); }
@Test public void getControlHandlersWithTargetName_returnNotEmptyHandlersArray() throws Exception { Handler<Message>[] handlers = commOpenHandler.getKernelControlChanelHandlers(targetName); Assertions.assertThat(handlers).isNotEmpty(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.