method2testcases stringlengths 118 3.08k |
|---|
### Question:
FlickrPhotosExporter implements Exporter<AuthData, PhotosContainerResource> { @VisibleForTesting static String toMimeType(String flickrFormat) { switch (flickrFormat) { case "jpg": case "jpeg": return "image/jpeg"; case "png": return "image/png"; case "gif": return "image/gif"; default: throw new IllegalArgumentException("Don't know how to map: " + flickrFormat); } } FlickrPhotosExporter(AppCredentials appCredentials, TransferServiceConfig serviceConfig); @VisibleForTesting FlickrPhotosExporter(Flickr flickr, TransferServiceConfig serviceConfig); @Override ExportResult<PhotosContainerResource> export(
UUID jobId, AuthData authData, Optional<ExportInformation> exportInformation); }### Answer:
@Test public void getMimeType() { assertThat(FlickrPhotosExporter.toMimeType("jpeg")).isEqualTo("image/jpeg"); assertThat(FlickrPhotosExporter.toMimeType("gif")).isEqualTo("image/gif"); } |
### Question:
GoogleJobStore extends JobStoreWithValidator { @VisibleForTesting static String getDataKeyName(UUID jobId, String key) { return String.format("%s-%s", jobId, key); } @Inject GoogleJobStore(
Datastore datastore, GoogleTempFileStore googleTempFileStore, ObjectMapper objectMapper); @Override void createJob(UUID jobId, PortabilityJob job); @Override void updateJob(UUID jobId, PortabilityJob job); @Override void addErrorsToJob(UUID jobId, Collection<ErrorDetail> errors); @Override void remove(UUID jobId); @Override PortabilityJob findJob(UUID jobId); @Override UUID findFirst(JobAuthorization.State jobState); @Override void create(UUID jobId, String key, T model); @Override void update(UUID jobId, String key, T model); @Override T findData(UUID jobId, String key, Class<T> type); @Override void create(UUID jobId, String key, InputStream stream); @Override void addCounts(UUID jobId, Map<String, Integer> newCounts); @Override Map<String, Integer> getCounts(UUID jobId); @Override InputStreamWrapper getStream(UUID jobId, String key); }### Answer:
@Test public void getDataKeyName() throws Exception { assertEquals( JOB_ID + "-tempTaskData", GoogleJobStore.getDataKeyName(JOB_ID, "tempTaskData")); assertEquals( JOB_ID + "-tempCalendarData", GoogleJobStore.getDataKeyName(JOB_ID, "tempCalendarData")); } |
### Question:
GoogleCloudIdempotentImportExecutor implements IdempotentImportExecutor { @Override public <T extends Serializable> T getCachedValue(String idempotentId) throws IllegalArgumentException { if (!knownValues.containsKey(idempotentId)) { throw new IllegalArgumentException( idempotentId + " is not a known key, known keys: " + Joiner.on(", ").join(knownValues.keySet())); } return (T) knownValues.get(idempotentId); } GoogleCloudIdempotentImportExecutor(Datastore datastore, Monitor monitor); @Override T executeAndSwallowIOExceptions(
String idempotentId, String itemName, Callable<T> callable); @Override T executeOrThrowException(
String idempotentId, String itemName, Callable<T> callable); @Override T getCachedValue(String idempotentId); @Override boolean isKeyCached(String idempotentId); @Override Collection<ErrorDetail> getErrors(); @Override void setJobId(UUID jobId); }### Answer:
@Test public void getCachedValue() throws Exception { googleExecutor.setJobId(JOB_ID); googleExecutor.executeAndSwallowIOExceptions("id1", ITEM_NAME, () -> "idempotentId1"); assertEquals(googleExecutor.getCachedValue("id1"), "idempotentId1"); } |
### Question:
LocalJobStore extends JobStoreWithValidator { @Override public Map<String, Integer> getCounts(UUID jobId) { return counts.computeIfAbsent(jobId, k -> new ConcurrentHashMap<>()); } LocalJobStore(); LocalJobStore(Monitor monitor); @Override void createJob(UUID jobId, PortabilityJob job); @Override void updateJob(UUID jobId, PortabilityJob job); @Override void addErrorsToJob(UUID jobId, Collection<ErrorDetail> errors); @Override void remove(UUID jobId); @Override PortabilityJob findJob(UUID jobId); @Override synchronized UUID findFirst(JobAuthorization.State jobState); @Override void addCounts(UUID jobId, Map<String, Integer> newCounts); @Override Map<String, Integer> getCounts(UUID jobId); @Override void addBytes(UUID jobId, Long bytes); @Override Long getBytes(UUID jobId); @Override void create(UUID jobId, String key, T model); @Override void update(UUID jobId, String key, T model); @Override T findData(UUID jobId, String key, Class<T> type); @Override void create(UUID jobId, String key, InputStream stream); @Override InputStreamWrapper getStream(UUID jobId, String key); }### Answer:
@Test public void canAddNewKeysToTheCurrentCountsTest() { addItemToJobStoreCounts(ITEM_NAME); final Map<String, Integer> counts = localJobStore.getCounts(jobId); Truth.assertThat(counts.size()).isEqualTo(1); Truth.assertThat(counts.get(ITEM_NAME)).isEqualTo(1); }
@Test public void canAddExistingKeysToCurrentCountsTest() { addItemToJobStoreCounts(ITEM_NAME); addItemToJobStoreCounts(ITEM_NAME); final Map<String, Integer> counts = localJobStore.getCounts(jobId); Truth.assertThat(counts.size()).isEqualTo(1); Truth.assertThat(counts.get(ITEM_NAME)).isEqualTo(2); } |
### Question:
ObjectValidator { public ValidationResult validate(String pid) { if (pid == null) { throw new NullPointerException("pid may not be null."); } ObjectInfo object = null; try { object = objectSource.getValidationObject(pid); } catch (ObjectSourceException e) { } if (object == null) { ValidationResult result = new ValidationResult(new BasicObjectInfo(pid)); result.addNote(ValidationResultNotation.objectNotFound(pid)); return result; } else { return validate(object); } } ObjectValidator(ObjectSource objectSource); ValidationResult validate(String pid); ValidationResult validate(ObjectInfo object); }### Answer:
@Test(expected = NullPointerException.class) public void nullArgumentToValidatePid() { validator.validate((String) null); }
@Test public void gettingFromPidThrowsException() { objectSource.throwObjectSourceExceptionOnPid(SAMPLE_PID); ValidationResult expected = expectedResult(new BasicObjectInfo(SAMPLE_PID), ValidationResultNotation .objectNotFound(SAMPLE_PID)); ValidationResult actual = validator.validate(SAMPLE_PID); assertEquals("result", expected, actual); }
@Test public void pidReturnsNullObject() { ValidationResult expected = expectedResult(new BasicObjectInfo(SAMPLE_PID), ValidationResultNotation .objectNotFound(SAMPLE_PID)); ValidationResult actual = validator.validate(SAMPLE_PID); assertEquals("result", expected, actual); }
@Test public void simpleSuccessFromPid() { ValidationResult expected = expectedResult(OBJECT_SIMPLE_SAMPLE); ValidationResult actual = validator.validate(OBJECT_SIMPLE_SAMPLE.getPid()); assertEquals("result", expected, actual); }
@Test(expected = NullPointerException.class) public void nullArgumentToValidateObject() { validator.validate((ObjectInfo) null); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { public void replaceObject(String objectKey, InputStream content, Map<String, String> hints) throws LowlevelStorageException { replace(objectStore, objectKey, content, forceSafeObjectOverwrites, hints); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testReplaceNonExistingObject() throws Exception { instance.replaceObject(OBJ_KEY, toStream(OBJ_CONTENT)); }
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testReplaceNonExistingObjectSafely() throws Exception { safeInstance.replaceObject(OBJ_KEY, toStream(OBJ_CONTENT)); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public InputStream retrieveDatastream(String dsKey) throws LowlevelStorageException { return retrieve(datastreamStore, dsKey); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testRetrieveNonExistingDatastream() throws Exception { instance.retrieveDatastream(DS_KEY); }
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testRetrieveNonExistingObject() throws Exception { instance.retrieveDatastream(OBJ_KEY); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public Iterator<String> listDatastreams() { return list(datastreamStore); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testListDatastreams() throws Exception { List<String> list; list = toList(instance.listDatastreams()); assertEquals(0, list.size()); instance.addDatastream(DS_KEY, toStream(DS_CONTENT)); list = toList(instance.listDatastreams()); assertEquals(1, list.size()); assertEquals(DS_KEY, list.get(0)); instance.removeDatastream(DS_KEY); list = toList(instance.listDatastreams()); assertEquals(0, list.size()); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public Iterator<String> listObjects() { return list(objectStore); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testListObjects() throws Exception { List<String> list; list = toList(instance.listObjects()); assertEquals(0, list.size()); instance.addObject(OBJ_KEY, toStream(OBJ_CONTENT)); list = toList(instance.listObjects()); assertEquals(1, list.size()); assertEquals(OBJ_KEY, list.get(0)); instance.removeObject(OBJ_KEY); list = toList(instance.listObjects()); assertEquals(0, list.size()); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public long getDatastreamSize(String dsKey) throws LowlevelStorageException { return getSize(datastreamStore, dsKey); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testGetDatastreamSize() throws Exception { instance.addDatastream(DS_KEY, toStream(DS_CONTENT)); assertEquals(DS_CONTENT.getBytes("UTF-8").length, instance.getDatastreamSize(DS_KEY)); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { public void addObject(String objectKey, InputStream content, Map<String, String> hints) throws LowlevelStorageException { add(objectStore, objectKey, content, hints); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testAddObjectWithHints() throws Exception { FedoraStorageHintProvider provider = new MockFedoraHintsProvider(); Map<String, String> hints = provider.getHintsForAboutToBeStoredObject(null); instance.addObject(OBJ_KEY, toStream(OBJ_CONTENT), hints); }
@Test public void testAddNonExistingObject() throws Exception { instance.addObject(OBJ_KEY, toStream(OBJ_CONTENT)); } |
### Question:
ValidationUtility { private static void validatePOLICY(InputStream content) throws ValidationException { logger.debug("Validating POLICY datastream"); policyParser.copy().parse(content, true); logger.debug("POLICY datastream is valid"); } static void validateURL(String url, String controlGroup); static void setPolicyParser(PolicyParser parser); static void setFeslPolicyParser(PolicyParser parser); static void setValidateFeslPolicy(boolean validate); static void validateReservedDatastreams(DOReader reader); static void validateReservedDatastream(PID pid,
String dsId,
Datastream ds); }### Answer:
@Test(expected=NullPointerException.class) public void testValidatePolicyParserNotSet() throws IOException, SAXException, ValidationException { validatePolicy(null, POLICY_GOODENOUGH); }
@Test(expected=ValidationException.class) public void testValidatePolicyBad() throws IOException, SAXException, ValidationException { validatePolicy(new MockPolicyParser(), POLICY_QUESTIONABLE); }
@Test public void testValidatePolicyGood() throws IOException, SAXException, ValidationException { validatePolicy(new MockPolicyParser(), POLICY_GOODENOUGH); } |
### Question:
ValidationUtility { private static void validateRELS(PID pid, String dsId, InputStream content) throws ValidationException { logger.debug("Validating " + dsId + " datastream"); new RelsValidator().validate(pid, dsId, content); logger.debug(dsId + " datastream is valid"); } static void validateURL(String url, String controlGroup); static void setPolicyParser(PolicyParser parser); static void setFeslPolicyParser(PolicyParser parser); static void setValidateFeslPolicy(boolean validate); static void validateReservedDatastreams(DOReader reader); static void validateReservedDatastream(PID pid,
String dsId,
Datastream ds); }### Answer:
@Test(expected=ValidationException.class) public void testValidateRelsExtBad() throws ValidationException { validateRels("RELS-EXT", ""); }
@Test(expected=ValidationException.class) public void testValidateRelsIntBad() throws ValidationException { validateRels("RELS-INT", ""); }
@Test public void testValidateRelsExtGood() throws ValidationException { validateRels("RELS-EXT", RELSEXT_GOOD); }
@Test public void testValidateRelsIntGood() throws ValidationException { validateRels("RELS-INT", RELSINT_GOOD); } |
### Question:
DateTimeParam extends AbstractParam<Date> { @Override public String toString() { return DateUtility.convertDateToXSDString(getValue()); } DateTimeParam(String param); @Override String toString(); }### Answer:
@Test public void testToString() { DateTimeParam param = new DateTimeParam(EPOCH_DT); assertEquals("1970-01-01T00:00:00Z", param.toString()); } |
### Question:
ProxyFactory { public static Object getProxy(Object target, Object[] invocationHandlers) throws Exception { if (invocationHandlers != null && invocationHandlers.length > 0) { Object proxy = target; for (int i = 0; i < invocationHandlers.length; i++) { proxy = getProxy(target, (AbstractInvocationHandler) invocationHandlers[i], proxy); } return proxy; } else { return target; } } static Object getProxy(Object target, Object[] invocationHandlers); }### Answer:
@Test public void testGetProxy() throws Exception { Object[] chainA = {new FlipBooleanHandler(), new ReverseStringHandler()}; Object[] chainB = {new ReverseStringHandler(), new PrefixStringWithXHandler()}; Object[] chainC = {new PrefixStringWithXHandler(), new ReverseStringHandler()}; TargetInterface proxy = (TargetInterface) ProxyFactory.getProxy(target, chainA); assertTrue(proxy.bar(false)); assertEquals("olleh", proxy.baz("hello")); proxy = (TargetInterface) ProxyFactory.getProxy(target, chainB); assertEquals("ollehX", proxy.baz("hello")); proxy = (TargetInterface) ProxyFactory.getProxy(target, chainC); assertEquals("Xolleh", proxy.baz("hello")); } |
### Question:
ParameterHelper implements JournalConstants { public static String getOptionalStringParameter(Map<String, String> parameters, String parameterName, String defaultValue) { validateParameters(parameters); validateParameterName(parameterName); String value = parameters.get(parameterName); return value == null ? defaultValue : value; } private ParameterHelper(); static String getOptionalStringParameter(Map<String, String> parameters,
String parameterName,
String defaultValue); static boolean getOptionalBooleanParameter(Map<String, String> parameters,
String parameterName,
boolean defaultValue); static File parseParametersForWritableDirectory(Map<String, String> parameters,
String parameterName); static String parseParametersForFilenamePrefix(Map<String, String> parameters); static long parseParametersForSizeLimit(Map<String, String> parameters); static long parseParametersForAgeLimit(Map<String, String> parameters); }### Answer:
@Test public void testGetOptionalStringParameter_Value() { parameters.put("fred", "theValue"); String result = ParameterHelper.getOptionalStringParameter(parameters, "fred", "WhoCares?"); assertEquals("theValue", result); }
@Test public void testGetOptionalStringParameter_Default() { String result = ParameterHelper.getOptionalStringParameter(parameters, "fred", "WhoCares?"); assertEquals("WhoCares?", result); } |
### Question:
ParameterHelper implements JournalConstants { public static String parseParametersForFilenamePrefix(Map<String, String> parameters) { return getOptionalStringParameter(parameters, PARAMETER_JOURNAL_FILENAME_PREFIX, DEFAULT_FILENAME_PREFIX); } private ParameterHelper(); static String getOptionalStringParameter(Map<String, String> parameters,
String parameterName,
String defaultValue); static boolean getOptionalBooleanParameter(Map<String, String> parameters,
String parameterName,
boolean defaultValue); static File parseParametersForWritableDirectory(Map<String, String> parameters,
String parameterName); static String parseParametersForFilenamePrefix(Map<String, String> parameters); static long parseParametersForSizeLimit(Map<String, String> parameters); static long parseParametersForAgeLimit(Map<String, String> parameters); }### Answer:
@Test public void testParseParametersForFilenamePrefix_Value() { parameters.put(PARAMETER_JOURNAL_FILENAME_PREFIX, "somePrefix"); String result = ParameterHelper.parseParametersForFilenamePrefix(parameters); assertEquals("somePrefix", result); }
@Test public void testParseParametersForFilenamePrefix_Default() { String result = ParameterHelper.parseParametersForFilenamePrefix(parameters); assertEquals(DEFAULT_FILENAME_PREFIX, result); } |
### Question:
RmiJournalReceiver extends UnicastRemoteObject implements RmiJournalReceiverInterface { public void closeFile() throws JournalException { if (journalFile == null) { throw logAndGetException("Attempting to close a file " + "when no file is open."); } try { writer.close(); journalFile.close(); } catch (IOException e) { throw logAndGetException("Problem closing the file '" + journalFile.getName() + "'", e); } logger.debug("closing file: '" + journalFile.getName() + "'"); journalFile = null; } RmiJournalReceiver(RmiJournalReceiverArguments arguments); void exportAndBind(); void openFile(String repositoryHash, String filename); void writeText(String indexedHash, String text); void closeFile(); static void main(String[] args); }### Answer:
@Test public void testCloseWithoutOpen() throws RemoteException, JournalException { RmiJournalReceiver receiver = createReceiver(new String[] { journalDirectory.getAbsolutePath(), "1234", "1235", "FATAL"}); try { receiver.closeFile(); fail("Expected an exception."); } catch (JournalException e) { } } |
### Question:
RmiJournalReceiver extends UnicastRemoteObject implements RmiJournalReceiverInterface { public void openFile(String repositoryHash, String filename) throws JournalException { if (journalFile != null) { throw logAndGetException("Attempting to open file '" + filename + "' when file '" + journalFile.getName() + "' has not been closed."); } try { journalFile = new TransportOutputFile(directory, filename); writer = journalFile.open(); } catch (IOException e) { throw logAndGetException("Problem opening" + filename + "'", e); } currentRepositoryHash = repositoryHash; itemIndex = 0; logger.debug("opened file '" + filename + "', hash is '" + repositoryHash + "'"); } RmiJournalReceiver(RmiJournalReceiverArguments arguments); void exportAndBind(); void openFile(String repositoryHash, String filename); void writeText(String indexedHash, String text); void closeFile(); static void main(String[] args); }### Answer:
@Test public void testCantCreateFile() throws RemoteException, JournalException { RmiJournalReceiver receiver = createReceiver(new String[] { journalDirectory.getAbsolutePath(), "1234", "1235", "FATAL"}); try { receiver.openFile("RepoHash", ":"); fail("Expected an exception."); } catch (JournalException e) { } } |
### Question:
RmiTransport extends Transport { @Override public void openFile(String repositoryHash, String filename, Date currentDate) throws JournalException { try { super.testStateChange(State.FILE_OPEN); writer = new RmiTransportWriter(receiver, repositoryHash, filename); xmlWriter = new IndentingXMLEventWriter(XMLOutputFactory .newInstance() .createXMLEventWriter(new BufferedWriter(writer, bufferSize))); parent.writeDocumentHeader(xmlWriter, repositoryHash, currentDate); super.setState(State.FILE_OPEN); } catch (XMLStreamException e) { throw new JournalException(e); } catch (FactoryConfigurationError e) { throw new JournalException(e); } } RmiTransport(Map<String, String> parameters,
boolean crucial,
TransportParent parent); protected RmiTransport(Map<String, String> parameters,
boolean crucial,
TransportParent parent,
RmiJournalReceiverInterface rx); @Override void openFile(String repositoryHash,
String filename,
Date currentDate); @Override XMLEventWriter getWriter(); @Override void closeFile(); @Override void shutdown(); static final String PARAMETER_HOST_NAME; static final String PARAMETER_PORT_NUMBER; static final String PARAMETER_SERVICE_NAME; static final String PARAMETER_BUFFER_SIZE; static final int DEFAULT_PORT_NUMBER; static final int DEFAULT_BUFFER_SIZE; }### Answer:
@Ignore @Test(expected = JournalException.class) public void testReceiverThrowsException() throws IOException, JournalException { startMockRmiJournalReceiver(true); RmiTransport transport = new RmiTransport(parameters, CRUCIAL, parent); transport.openFile("someHash", "aFileName", new Date()); fail("Expected an exception."); } |
### Question:
OptionDefinition { public static OptionDefinition get(String id, InstallOptions options) { String label = _PROPS.getProperty(id + ".label"); String description = _PROPS.getProperty(id + ".description"); String[] validValues = getArray(id + ".validValues"); String defaultValue = _PROPS.getProperty(id + ".defaultValue"); if (id.equals(InstallOptions.FEDORA_HOME)) { String eFH = System.getenv("FEDORA_HOME"); if (eFH != null && eFH.length() != 0) { defaultValue = eFH; } } if (id.equals(InstallOptions.TOMCAT_HOME)) { String eCH = System.getenv("CATALINA_HOME"); if (eCH != null && eCH.length() != 0) { defaultValue = eCH; } else if (options.getValue(InstallOptions.SERVLET_ENGINE) .equals(InstallOptions.INCLUDED)) { defaultValue = options.getValue(InstallOptions.FEDORA_HOME) + File.separator + "tomcat"; } } return new OptionDefinition(id, label, description, validValues, defaultValue, options); } private OptionDefinition(String id,
String label,
String description,
String[] validValues,
String defaultValue,
InstallOptions options); static OptionDefinition get(String id, InstallOptions options); String getId(); String getLabel(); String getDescription(); String[] getValidValues(); String getDefaultValue(); void validateValue(String value); void validateValue(String value, boolean unattended); }### Answer:
@Test public void testGet() throws Exception { Map<String, String> oMap = new HashMap<String, String>(); oMap.put(InstallOptions.APIA_AUTH_REQUIRED, Boolean.toString(false)); InstallOptions installOpts = new InstallOptions(new MockDistribution(), oMap); OptionDefinition opt = OptionDefinition.get( InstallOptions.APIA_AUTH_REQUIRED, installOpts); assertNotNull(opt); } |
### Question:
RmiTransportWriter extends Writer { @Override public void close() throws IOException { try { if (!m_closed) { receiver.closeFile(); m_closed= true; } } catch (JournalException e) { throw new IOException(e); } } RmiTransportWriter(RmiJournalReceiverInterface receiver,
String repositoryHash,
String filename); @Override void write(char[] cbuf, int off, int len); @Override void close(); @Override void flush(); }### Answer:
@Test public void testConstructorOpensConnection() throws JournalException, IOException { RmiTransportWriter rtw = new RmiTransportWriter(receiver, repositoryHash, "theFilename"); rtw.close(); assertCorrectNumberOfCalls(receiver, 1, 0, 0); assertEquals(repositoryHash, receiver.getRepositoryHash()); assertEquals("theFilename", receiver.getFilename()); }
@Test(expected = JournalException.class) public void testConstructorGetsException() throws JournalException, IOException { receiver.setOpenFileThrowsException(true); RmiTransportWriter rtw = new RmiTransportWriter(receiver, repositoryHash, "theFilename"); rtw.close(); }
@Test public void testCloseClosesFile() throws JournalException, IOException { RmiTransportWriter writer = new RmiTransportWriter(receiver, repositoryHash, "theFilename"); writer.close(); assertCorrectNumberOfCalls(receiver, 1, 0, 1); }
@Test(expected = IOException.class) public void testCloseThrowsException() throws JournalException, IOException { receiver.setCloseFileThrowsException(true); RmiTransportWriter writer = new RmiTransportWriter(receiver, repositoryHash, "theFilename"); writer.close(); } |
### Question:
LocalDirectoryTransport extends Transport { @Override public void openFile(String repositoryHash, String filename, Date currentDate) throws JournalException { try { super.testStateChange(State.FILE_OPEN); journalFile = new TransportOutputFile(directory, filename); xmlWriter = new IndentingXMLEventWriter(XMLOutputFactory.newInstance() .createXMLEventWriter(journalFile.open())); parent.writeDocumentHeader(xmlWriter, repositoryHash, currentDate); super.setState(State.FILE_OPEN); } catch (FactoryConfigurationError e) { throw new JournalException(e); } catch (XMLStreamException e) { throw new JournalException(e); } catch (IOException e) { throw new JournalException(e); } } LocalDirectoryTransport(Map<String, String> parameters,
boolean crucial,
TransportParent parent); @Override void openFile(String repositoryHash,
String filename,
Date currentDate); @Override XMLEventWriter getWriter(); @Override void closeFile(); @Override void shutdown(); static final String PARAMETER_DIRECTORY_PATH; }### Answer:
@Test public void testUnableToCreateFile() throws JournalException { LocalDirectoryTransport transport = new LocalDirectoryTransport(parameters, CRUCIAL, null); try { transport.openFile("firstSillyHash", ":", new Date()); fail("expecting JournalException"); } catch (JournalException e) { } }
@Test public void testOpenAfterOpen() throws JournalException { Transport transport = new LocalDirectoryTransport(parameters, CRUCIAL, parent); transport.openFile("firstSillyHash", "Open", new Date()); try { transport.openFile("firstSillyHash", "OpenOpen", new Date()); fail("Expected a JournalException"); } catch (JournalException e) { } } |
### Question:
LocalDirectoryTransport extends Transport { @Override public void shutdown() throws JournalException { super.testStateChange(State.SHUTDOWN); if (super.getState() != State.SHUTDOWN) { super.setState(State.SHUTDOWN); } } LocalDirectoryTransport(Map<String, String> parameters,
boolean crucial,
TransportParent parent); @Override void openFile(String repositoryHash,
String filename,
Date currentDate); @Override XMLEventWriter getWriter(); @Override void closeFile(); @Override void shutdown(); static final String PARAMETER_DIRECTORY_PATH; }### Answer:
@Test public void testShutdownAfterShutdown() throws JournalException { Transport transport = new LocalDirectoryTransport(parameters, CRUCIAL, parent); transport.shutdown(); transport.shutdown(); } |
### Question:
DCFields extends DefaultHandler implements Constants { public String getAsXML() { return getAsXML((String)null); } DCFields(); DCFields(InputStream in); @Override void startElement(String uri,
String localName,
String qName,
Attributes attrs); @Override void characters(char[] ch, int start, int length); @Override void endElement(String uri, String localName, String qName); Map<RDFName, List<DCField>> getMap(); List<DCField> titles(); List<DCField> creators(); List<DCField> subjects(); List<DCField> descriptions(); List<DCField> publishers(); List<DCField> contributors(); List<DCField> dates(); List<DCField> types(); List<DCField> formats(); List<DCField> identifiers(); List<DCField> sources(); List<DCField> languages(); List<DCField> relations(); List<DCField> coverages(); List<DCField> rights(); String getAsXML(); void getAsXML(Writer out); String getAsXML(String targetPid); void getAsXML(String targetPid, Writer out); }### Answer:
@Test public void testDCFieldsInputStream() throws Exception { DCFields dc; Document dcXML; dc = new DCFields(new ByteArrayInputStream(dcWithXmlLang.getBytes("UTF-8"))); dcXML = XMLUnit.buildControlDocument(dc.getAsXML()); assertEquals("Time interval", engine.evaluate(" assertEquals("Tidsinterval", engine.evaluate(" dc = new DCFields(); dcXML = XMLUnit.buildControlDocument(dc.getAsXML()); assertEquals("Expected empty element", "", engine.evaluate(" } |
### Question:
SQLRebuilder implements Rebuilder { @Override public void start(Map<String, String> options) throws Exception { blankExistingTables(); try { m_server = Rebuild.getServer(); ConnectionPoolManager cpm = (ConnectionPoolManager) m_server .getModule("org.fcrepo.server.storage.ConnectionPoolManager"); if (cpm == null) { throw new ModuleInitializationException("ConnectionPoolManager not loaded.", "ConnectionPoolManager"); } m_connectionPool = cpm.getPool(); ensureFedoraTables(); m_now = System.currentTimeMillis(); startStatus(m_now); m_context = ReadOnlyContext.getContext("utility", "fedoraAdmin", "", ReadOnlyContext.DO_OP); ILowlevelStorage llstore = (ILowlevelStorage) m_server .getModule("org.fcrepo.server.storage.lowlevel.ILowlevelStorage"); try { llstore.rebuildObject(); llstore.rebuildDatastream(); } catch (LowlevelStorageException e) { e.printStackTrace(); } } catch (InitializationException ie) { logger.error("Error initializing", ie); throw ie; } } @Override String getAction(); @Override boolean shouldStopServer(); @Override void setServerConfiguration(ServerConfiguration serverConfig); @Override void setServerDir(File serverBaseDir); @Override void init(); @Override Map<String, String> getOptions(); @Override void start(Map<String, String> options); static List<String> getExistingTables(Connection conn); void blankExistingTables(); void ensureFedoraTables(); @Override void addObject(DigitalObject obj); @Override void finish(); static final String CREATE_REBUILD_STATUS; static final String UPDATE_REBUILD_STATUS; static final String DBSPEC_LOCATION; }### Answer:
@Test public void testBadRebuild() throws Exception { test.start(new HashMap<String, String>()); verify(mockCreateStmt).setBoolean(1, false); verify(mockCreateStmt).execute(); verify(mockUpdateStmt, never()).setBoolean(1, true); verify(mockUpdateStmt, never()).execute(); } |
### Question:
Tomcat5ServerXML extends XMLDocument { public void update() throws InstallationFailedException { setHTTPPort(); setShutdownPort(); setSSLPort(); setURIEncoding(); } Tomcat5ServerXML(File serverXML, InstallOptions installOptions); Tomcat5ServerXML(InputStream serverXML, InstallOptions installOptions); void update(); void setHTTPPort(); void setShutdownPort(); void setSSLPort(); void setURIEncoding(); }### Answer:
@Test public void testUpdate() throws Exception { TomcatServerXML serverXML; serverXML = new TomcatServerXML(is, installOptions); serverXML.update(); } |
### Question:
StringUtility { public static String prettyPrint(String in, int lineLength, String delim) { StringBuilder sb = new StringBuilder(in.length() + in.length()/lineLength); if (delim == null) { delim = " "; } StringTokenizer st = new StringTokenizer(in, delim); int charCount = 0; while (st.hasMoreTokens()) { String s = st.nextToken(); charCount = charCount + s.length(); if (charCount < lineLength) { sb.append(s); sb.append(' '); charCount++; } else { sb.append('\n'); sb.append(s); sb.append(' '); charCount = s.length() + 1; } } return sb.toString(); } StringUtility(); static String prettyPrint(String in, int lineLength, String delim); @Deprecated static String splitAndIndent(String str, int indent, int numChars); static void splitAndIndent(String str, int indent,
int numChars, PrintWriter writer); static String byteArraytoHexString(byte[] array); static byte[] hexStringtoByteArray(String str); static void main(String[] args); }### Answer:
@Test public void testPrettyPrint() { String src = "The;quick;brown;fox;jumped;over;the;lazy;dog"; String expected = "\n" + src.replace(";"," \n") + " "; assertEquals(expected, StringUtility.prettyPrint(src, 2, ";")); } |
### Question:
StreamUtility { public static String enc(String in) { if (in == null || in.isEmpty()) { return ""; } StringBuilder out = new StringBuilder(); enc(in, out); return out.toString(); } static String enc(String in); static void enc(String in, StringBuilder out); static void enc(String in, PrintStream out); static void enc(String in, Writer out); static void enc(char[] in, int start, int length, StringBuffer out); static void enc(char[] in, int start, int length, StringBuilder out); static void enc(char[] in, int start, int length, Writer out); static void enc(char in, StringBuffer out); static void enc(char in, StringBuilder out); static void enc(char in, PrintStream out); static void enc(char in, Writer out); static void pipeStream(InputStream in, OutputStream out, int bufSize); static byte[] getBytes(InputStream in); static InputStream getStream(String string); }### Answer:
@Test public void testEncoding() { String in = "\"foo"; String expected = ""foo"; String actual = StreamUtility.enc(in); assertEquals(expected, actual); in = "foo\""; expected = "foo""; actual = StreamUtility.enc(in); assertEquals(expected, actual); in = "&<foo>'\""; expected = "&<foo>'""; actual = StreamUtility.enc(in); assertEquals(expected, actual); in = "foo bar"; expected = in; actual = StreamUtility.enc(in); assertEquals(expected, actual); } |
### Question:
PolicyParser { private static InputStream getStream(String path) { try { return new FileInputStream(path); } catch (Exception e) { fail("File not found: " + path); return null; } } PolicyParser(InputStream schemaStream); private PolicyParser(Schema schema); private PolicyParser(SoftReferenceObjectPool<Validator> validators); PolicyParser copy(); AbstractPolicy parse(InputStream policyStream,
boolean schemaValidate); static void main(String[] args); }### Answer:
@Test (expected=SAXException.class) public void testConstructWithBadSchema() throws IOException, SAXException { new PolicyParser(StreamUtility.getStream(SCHEMA_BAD)); } |
### Question:
FedoraUsers implements Serializable, Constants { public static FedoraUsers getInstance() { return getInstance(fedoraUsersXML.toURI()); } FedoraUsers(); static FedoraUsers getInstance(); static FedoraUsers getInstance(URI fedoraUsersXML); List<Role> getRoles(); List<User> getUsers(); void addRole(Role role); void addUser(User user); void write(Writer outputWriter); static File fedoraUsersXML; }### Answer:
@Test public void testGetInstance() throws Exception { FedoraUsers fu = FedoraUsers.getInstance(); assertNotNull(fu); }
@Test public void testGetInstanceString() throws Exception { String fedoraUsersXML = "src/main/resources/fcfg/server/fedora-users.xml"; File f = new File(fedoraUsersXML); FedoraUsers fu = FedoraUsers.getInstance(f.toURI()); assertNotNull(fu); } |
### Question:
DefaultExternalContentManager extends Module implements ExternalContentManager { @Override public void initModule() throws ModuleInitializationException { try { Server s_server = getServer(); m_userAgent = getParameter("userAgent"); if (m_userAgent == null) { m_userAgent = "Fedora"; } fedoraServerPort = s_server.getParameter("fedoraServerPort"); fedoraServerHost = s_server.getParameter("fedoraServerHost"); fedoraServerRedirectPort = s_server.getParameter("fedoraRedirectPort"); m_httpconfig = s_server.getWebClientConfig(); if (m_httpconfig.getUserAgent() == null ) { m_httpconfig.setUserAgent(m_userAgent); } m_http = new WebClient(m_httpconfig); } catch (Throwable th) { throw new ModuleInitializationException("[DefaultExternalContentManager] " + "An external content manager " + "could not be instantiated. The underlying error was a " + th.getClass() .getName() + "The message was \"" + th.getMessage() + "\".", getRole(), th); } } DefaultExternalContentManager(Map<String, String> moduleParameters,
Server server,
String role); @Override void initModule(); @Override MIMETypedStream getExternalContent(ContentManagerParams params); }### Answer:
@Test public void testInit() throws ModuleInitializationException { when(mockClientConfig.getMaxConnPerHost()).thenReturn(5); when(mockClientConfig.getMaxTotalConn()).thenReturn(5); testObj.initModule(); } |
### Question:
DOValidatorXMLSchema implements Constants, EntityResolver { public void validate(File objectAsFile) throws ObjectValidityException, GeneralException { try { validate(new StreamSource(new FileInputStream(objectAsFile))); } catch (IOException e) { String msg = "DOValidatorXMLSchema returned error.\n" + "The underlying exception was a " + e.getClass().getName() + ".\n" + "The message was " + "\"" + e.getMessage() + "\""; throw new GeneralException(msg); } } DOValidatorXMLSchema(Schema schema); DOValidatorXMLSchema(String schemaPath); void validate(File objectAsFile); void validate(InputStream objectAsStream); InputSource resolveEntity(String publicId, String systemId); }### Answer:
@Test public void testFoxmlValidation() throws Exception { InputStream in = new FileInputStream(RESOURCES + "demo/demo-objects/foxml/local-server-demos/simple-image-demo/obj_demo_5.xml"); DOValidatorXMLSchema dov = new DOValidatorXMLSchema(RESOURCES + "xsd/foxml1-1.xsd"); dov.validate(in); }
@Test public void testMetsValidation() throws Exception { InputStream in = new FileInputStream(getDemoFile("mets/local-server-demos/simple-image-demo/obj_demo_5.xml")); DOValidatorXMLSchema dov = new DOValidatorXMLSchema(RESOURCES + "xsd/mets-fedora-ext1-1.xsd"); dov.validate(in); }
@Test public void testAtomValidation() throws Exception { InputStream in = new FileInputStream(getDemoFile("atom/local-server-demos/simple-image-demo/obj_demo_5.xml")); DOValidatorXMLSchema dov = new DOValidatorXMLSchema(RESOURCES + "xsd/atom.xsd"); dov.validate(in); } |
### Question:
HashPathIdMapper implements IdMapper { public URI getExternalId(URI internalId) throws NullPointerException { String fullPath = internalId.toString().substring( internalScheme.length() + 1); int i = fullPath.lastIndexOf('/'); String encodedURI; if (i == -1) encodedURI = fullPath; else encodedURI = fullPath.substring(i + 1); return URI.create(decode(encodedURI)); } HashPathIdMapper(String pattern); URI getExternalId(URI internalId); URI getInternalId(URI externalId); String getInternalPrefix(String externalPrefix); }### Answer:
@Test public void testGetExternalId() { IdMapper mapper = new HashPathIdMapper("##/##/##"); assertEquals(URI1, mapper.getExternalId(URI1_ENCODED)); assertEquals(URI2, mapper.getExternalId(URI2_ENCODED)); assertEquals(URI3, mapper.getExternalId(URI3_ENCODED)); } |
### Question:
HashPathIdMapper implements IdMapper { public URI getInternalId(URI externalId) throws NullPointerException { if (externalId == null) { throw new NullPointerException(); } String uri = externalId.toString(); StringBuilder buffer = new StringBuilder(uri.length() + 16); buffer.append(internalScheme + ":"); getPath(uri, buffer); encode(uri, buffer); return URI.create(buffer.toString()); } HashPathIdMapper(String pattern); URI getExternalId(URI internalId); URI getInternalId(URI externalId); String getInternalPrefix(String externalPrefix); }### Answer:
@Test public void testGetInternalId() { IdMapper mapper = new HashPathIdMapper("##/##/##"); assertEquals(URI1_ENCODED, mapper.getInternalId(URI1)); assertEquals(URI2_ENCODED, mapper.getInternalId(URI2)); assertEquals(URI3_ENCODED, mapper.getInternalId(URI3)); } |
### Question:
HashPathIdMapper implements IdMapper { public String getInternalPrefix(String externalPrefix) throws NullPointerException { if (externalPrefix == null) { throw new NullPointerException(); } if (pattern.length() == 0) { StringBuilder buffer = new StringBuilder(externalPrefix.length() + 16); buffer.append(internalScheme + ":"); encode(externalPrefix, buffer); return buffer.toString(); } else { return null; } } HashPathIdMapper(String pattern); URI getExternalId(URI internalId); URI getInternalId(URI externalId); String getInternalPrefix(String externalPrefix); }### Answer:
@Test (expected=NullPointerException.class) public void testGetInternalPrefixNull() { new HashPathIdMapper("").getInternalPrefix(null); }
@Test public void testGetInternalPrefixNoPattern() { assertEquals("file:urn%3Atest", new HashPathIdMapper("").getInternalPrefix("urn:test")); }
@Test public void testGetInternalPrefixWithPattern() { assertNull(new HashPathIdMapper("#").getInternalPrefix("urn:test")); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public void auditDatastream() throws LowlevelStorageException { audit(datastreamStore); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testAuditDatastream() throws Exception { instance.auditDatastream(); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public void auditObject() throws LowlevelStorageException { audit(objectStore); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testAuditObject() throws Exception { instance.auditObject(); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public void rebuildDatastream() throws LowlevelStorageException { rebuild(datastreamStore); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testRebuildDatastream() throws Exception { instance.rebuildDatastream(); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public void rebuildObject() throws LowlevelStorageException { rebuild(objectStore); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test public void testRebuildObject() throws Exception { instance.rebuildObject(); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public void removeDatastream(String dsKey) throws LowlevelStorageException { remove(datastreamStore, dsKey); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testRemoveNonExistingDatastream() throws Exception { instance.removeDatastream(DS_KEY); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { @Override public void removeObject(String objectKey) throws LowlevelStorageException { remove(objectStore, objectKey); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testRemoveNonExistingObject() throws Exception { instance.removeObject(OBJ_KEY); } |
### Question:
AkubraLowlevelStorage implements ILowlevelStorage, IListable, ISizable, ICheckable { public long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints) throws LowlevelStorageException { return replace(datastreamStore, dsKey, content, forceSafeDatastreamOverwrites, hints); } AkubraLowlevelStorage(BlobStore objectStore,
BlobStore datastreamStore,
boolean forceSafeObjectOverwrites,
boolean forceSafeDatastreamOverwrites); long addDatastream(String dsKey, InputStream content, Map<String, String> hints); long addDatastream(String pid, InputStream content); void addObject(String objectKey, InputStream content, Map<String, String> hints); void addObject(String pid, InputStream content); @Override void auditDatastream(); @Override void auditObject(); @Override void rebuildDatastream(); @Override void rebuildObject(); @Override void removeDatastream(String dsKey); @Override void removeObject(String objectKey); long replaceDatastream(String dsKey, InputStream content, Map<String, String> hints); long replaceDatastream(String pid, InputStream content); void replaceObject(String objectKey, InputStream content, Map<String, String> hints); void replaceObject(String pid, InputStream content); @Override InputStream retrieveDatastream(String dsKey); @Override InputStream retrieveObject(String objectKey); @Override Iterator<String> listDatastreams(); @Override Iterator<String> listObjects(); @Override long getDatastreamSize(String dsKey); @Override boolean objectExists(String objectKey); }### Answer:
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testReplaceNonExistingDatastream() throws Exception { instance.replaceDatastream(DS_KEY, toStream(DS_CONTENT)); }
@Test (expected=ObjectNotInLowlevelStorageException.class) public void testReplaceNonExistingDatastreamSafely() throws Exception { safeInstance.replaceDatastream(DS_KEY, toStream(DS_CONTENT)); } |
### Question:
Util { public static int compare(@Nullable String s1, @Nullable String s2) { if (s1 == s2) { return 0; } else if ((s1 == null) && (s2 != null)) { return -1; } else if ((s1 != null) && (s2 == null)) { return 1; } return s1.compareTo(s2); } static void setContextAndConfig(Context context, GameConfiguration config); static Context getContext(); static GameConfiguration getConfig(); static int compare(@Nullable String s1, @Nullable String s2); static String oxfordComma(String conjuction, Object... list); static T find(Collection<T> list, Requirement<T> test); static String join(String delimiter, Iterable it); static boolean isDeveloper(Context context); }### Answer:
@Test public void testCompare() throws Exception { assertTrue(Util.compare("foo", "bar") > 1); assertTrue(Util.compare("bar", "foo") < 1); assertEquals(0, Util.compare("foo", "foo")); assertEquals(-1, Util.compare(null, "foo")); assertEquals(1, Util.compare("foo", null)); assertEquals(0, Util.compare(null, null)); } |
### Question:
Util { public static String oxfordComma(String conjuction, Object... list) { StringBuilder rv = new StringBuilder(); for (int ii = 0; ii < (list.length - 1); ++ii) { if (ii > 0) rv.append(", "); rv.append(list[ii]); } if (list.length > 1) { if (conjuction == null) { rv.append(", "); } else { if (list.length > 2) rv.append(","); rv.append(" ").append(conjuction).append(" "); } } rv.append(list[list.length - 1]); return rv.toString(); } static void setContextAndConfig(Context context, GameConfiguration config); static Context getContext(); static GameConfiguration getConfig(); static int compare(@Nullable String s1, @Nullable String s2); static String oxfordComma(String conjuction, Object... list); static T find(Collection<T> list, Requirement<T> test); static String join(String delimiter, Iterable it); static boolean isDeveloper(Context context); }### Answer:
@Test public void testOxfordComma() throws Exception { assertEquals("foo", Util.oxfordComma("or", "foo")); assertEquals("foo or bar", Util.oxfordComma("or", "foo", "bar")); assertEquals("foo, bar, or baz", Util.oxfordComma("or", "foo", "bar", "baz")); assertEquals("foo, bar, baz, or blurfl", Util.oxfordComma("or", "foo", "bar", "baz", "blurfl")); assertEquals("foo", Util.oxfordComma(null, "foo")); assertEquals("foo, bar", Util.oxfordComma(null, "foo", "bar")); assertEquals("foo, bar, baz", Util.oxfordComma(null, "foo", "bar", "baz")); assertEquals("foo, bar, baz, blurfl", Util.oxfordComma(null, "foo", "bar", "baz", "blurfl")); } |
### Question:
RemoteChangesetVersionCommand extends AbstractCallableCommand<Integer, Exception> { public static String toString(final VersionSpec versionSpec) { if (versionSpec instanceof DateVersionSpec){ final DateVersionSpec dateVersionSpec = (DateVersionSpec) versionSpec; return DateUtil.toString(dateVersionSpec); } else if (versionSpec instanceof LabelVersionSpec) { final LabelVersionSpec labelVersionSpec = (LabelVersionSpec) versionSpec; final String label = labelVersionSpec.getLabel(); final String scope = labelVersionSpec.getScope(); final StringBuilder sb = new StringBuilder(1 + label.length() + Strings.nullToEmpty(scope).length()); sb.append('L'); sb.append(label); if (!Strings.isNullOrEmpty(scope)) { sb.append('@'); sb.append(scope); } return sb.toString(); } return versionSpec.toString(); } RemoteChangesetVersionCommand(
final ServerConfigurationProvider server, final String remotePath, final VersionSpec versionSpec); Callable<Integer, Exception> getCallable(); Integer call(); static String toString(final VersionSpec versionSpec); String parse(Reader consoleReader); }### Answer:
@Test public void getVersionSpecificationWhenDateVersionSpec() { final String actual = RemoteChangesetVersionCommand.toString(fixedPointInTime); assertEquals("D2013-07-02T15:40:50Z", actual); }
@Test public void getVersionSpecificationWhenChangesetVersionSpec() { final ChangesetVersionSpec versionSpec = new ChangesetVersionSpec(42); final String actual = RemoteChangesetVersionCommand.toString(versionSpec); assertEquals("C42", actual); }
@Test public void getVersionSpecificationWhenLabelVersionSpecWithoutScope() { final LabelVersionSpec versionSpec = new LabelVersionSpec(new LabelSpec("Foo", null)); final String actual = RemoteChangesetVersionCommand.toString(versionSpec); assertEquals("LFoo", actual); }
@Test public void getVersionSpecificationWhenLabelVersionSpecWithScope() { final LabelVersionSpec versionSpec = new LabelVersionSpec(new LabelSpec("Foo", "$/Bar")); final String actual = RemoteChangesetVersionCommand.toString(versionSpec); assertEquals("LFoo@$/Bar", actual); } |
### Question:
AbstractCallableCommand extends MasterToSlaveCallable<V, T> implements Serializable { public abstract <V, E extends Throwable> Callable<V, E> getCallable(); protected AbstractCallableCommand(final ServerConfigurationProvider serverConfig); Server createServer(); abstract Callable<V, E> getCallable(); }### Answer:
@Test public void verifySerializable() throws IOException { final ServerConfigurationProvider server = new ServerConfigurationProvider() { public String getUrl() { return null; } public String getUserName() { return null; } public String getUserPassword() { return null; } public TaskListener getListener() { return null; } public WebProxySettings getWebProxySettings() { final List<Pattern> patterns = Arrays.asList( Pattern.compile(".+\\.com"), Pattern.compile(".+\\.org") ); final Secret secret; final SecretOverride secretOverride = new SecretOverride(); try { secret = Secret.fromString("password"); } finally { try { secretOverride.close(); } catch (final IOException ignored) { } } return new WebProxySettings("localhost", 8080, patterns, "user", secret); } @Override public ExtraSettings getExtraSettings() { return ExtraSettings.DEFAULT; } }; final AbstractCallableCommand command = createCommand(server); final Callable<?, Exception> callable = command.getCallable(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(callable); } |
### Question:
KeyValueTextReader { public Map<String, String> parse(final String string) throws IOException { return parse(new BufferedReader(new StringReader(string))); } Map<String, String> parse(final String string); Map<String, String> parse(final BufferedReader reader); }### Answer:
@Test public void assertKeyContainsSpace() throws Exception { Map<String, String> map = new KeyValueTextReader().parse("Change set: 12492"); assertThat(map.get("Change set"), is("12492")); }
@Test public void assertMultilineDataIsRead() throws Exception { Map<String, String> map = new KeyValueTextReader().parse("Key:Data\n Some more information"); assertThat(map.get("Key"), is("Data\nSome more information")); }
@Test public void asserOnlyKeyIsReadIfValueContainsColon() throws Exception { Map<String, String> map = new KeyValueTextReader().parse("Key:Data 23:23:12"); assertThat(map.get("Key"), is("Data 23:23:12")); }
@Test public void assertValueBeginingOnNextRowIsParsedWithoutPrefixedEndline() throws Exception { Map<String, String> map = new KeyValueTextReader().parse("Comment:\n Reviewer: \n Approver: \n"); assertThat(map.get("Comment"), is("Reviewer:\nApprover:")); }
@Test public void assertKeysAreRead() throws Exception { Map<String, String> map = new KeyValueTextReader().parse("Key:Data\nOtherKey: More data"); assertThat(map.get("Key"), is("Data")); assertThat(map.get("OtherKey"), is("More data")); }
@Test public void assertValueIsTrimmed() throws Exception { Map<String, String> map = new KeyValueTextReader().parse("Changeset: 12492"); assertThat(map.get("Changeset"), is("12492")); } |
### Question:
AbstractCommand implements Command { protected void addServerArgument(ArgumentListBuilder arguments) { arguments.add(String.format("-server:%s", config.getUrl())); } AbstractCommand(ServerConfigurationProvider configurationProvider); ServerConfigurationProvider getConfig(); }### Answer:
@Test public void assertAddingServerArguments() { ServerConfigurationProvider config = mock(ServerConfigurationProvider.class); when(config.getUrl()).thenReturn("https: AbstractCommand command = new AbstractCommandImpl(config); ArgumentListBuilder builder = new ArgumentListBuilder(); command.addServerArgument(builder); assertEquals("The server URL was incorrect", "-server:https: } |
### Question:
TeamEventsEndpoint implements UnprotectedRootAction { public static Event deserializeEvent(final String input) throws IOException { final Event serviceHookEvent = EndpointHelper.MAPPER.readValue(input, Event.class); final String eventType = serviceHookEvent.getEventType(); if (StringUtils.isEmpty(eventType)) { throw new IllegalArgumentException("Payload did not contain 'eventType'."); } final Object resource = serviceHookEvent.getResource(); if (resource == null) { throw new IllegalArgumentException("Payload did not contain 'resource'."); } return serviceHookEvent; } @Override String getIconFileName(); @Override String getDisplayName(); @Override String getUrlName(); HttpResponse doIndex(final HttpServletRequest request); static Event deserializeEvent(final String input); @RequirePOST void doPing(
final StaplerRequest request,
final StaplerResponse response,
@StringBodyParameter @Nonnull final String body); @RequirePOST void doGitPullRequestMerged(
final StaplerRequest request,
final StaplerResponse response,
@StringBodyParameter @Nonnull final String body); @RequirePOST void doGitPush(
final StaplerRequest request,
final StaplerResponse response,
@StringBodyParameter @Nonnull final String body); @RequirePOST void doConnect(
final StaplerRequest request,
final StaplerResponse response,
@StringBodyParameter @Nonnull final String body); @RequirePOST void doRmwebhook(
final StaplerRequest request,
final StaplerResponse response,
@StringBodyParameter @Nonnull final String body); static T findTrigger(final Job<?, ?> job, final Class<T> tClass); static List<T> findTriggers(final Job<?, ?> job, final Class<T> tClass); static final String URL_NAME; }### Answer:
@Test public void deserializeEvent_sample() throws Exception { final Event actual = TeamEventsEndpoint.deserializeEvent(GIT_PUSH_SAMPLE_JSON); Assert.assertEquals("git.push", actual.getEventType()); final Map<String, ResourceContainer> containers = actual.getResourceContainers(); final ResourceContainer collection = containers.get("collection"); Assert.assertEquals("https: } |
### Question:
RemoveWorkspaceAction { public boolean remove(Server server) throws IOException, InterruptedException { Workspaces workspaces = server.getWorkspaces(); if (workspaces.exists(workspaceName)) { Workspace workspace = workspaces.getWorkspace(workspaceName); workspaces.deleteWorkspace(workspace); return true; } return false; } RemoveWorkspaceAction(String workspaceName); boolean remove(Server server); }### Answer:
@Test public void assertNoSuchWorkspaceNameDoesNothing() throws Exception { when(server.getWorkspaces()).thenReturn(workspaces); when(workspaces.exists(anyString())).thenReturn(false); RemoveWorkspaceAction action = new RemoveWorkspaceAction("workspace"); assertThat(action.remove(server), is(false)); verify(server).getWorkspaces(); verify(workspaces).exists("workspace"); verifyNoMoreInteractions(workspace); verifyNoMoreInteractions(workspaces); verifyNoMoreInteractions(server); }
@Test public void assertWorkspaceIsDeleted() throws Exception { when(server.getWorkspaces()).thenReturn(workspaces); when(workspaces.exists(anyString())).thenReturn(true); when(workspaces.getWorkspace(anyString())).thenReturn(workspace); RemoveWorkspaceAction action = new RemoveWorkspaceAction("workspace"); assertThat(action.remove(server), is(true)); verify(server).getWorkspaces(); verify(workspaces).exists("workspace"); verify(workspaces).getWorkspace("workspace"); verify(workspaces).deleteWorkspace(workspace); verifyNoMoreInteractions(workspace); verifyNoMoreInteractions(workspaces); verifyNoMoreInteractions(server); } |
### Question:
StringHelper { public static String determineContentTypeWithoutCharset(final String contentType) { if (contentType == null) { return null; } final int indexOfSemicolon = contentType.indexOf(';'); if (indexOfSemicolon != -1) { final String beforeCharset = contentType.substring(0, indexOfSemicolon); return beforeCharset.trim(); } return contentType; } static boolean endsWithIgnoreCase(final String haystack, final String needle); static boolean equal(final String a, final String b); static boolean equalIgnoringCase(final String a, final String b); static String determineContentTypeWithoutCharset(final String contentType); }### Answer:
@Test public void determineContentTypeWithoutCharset_null() throws Exception { final String actual = StringHelper.determineContentTypeWithoutCharset(null); Assert.assertEquals(null, actual); }
@Test public void determineContentTypeWithoutCharset_withoutCharset() throws Exception { final String input = "application/json"; final String actual = StringHelper.determineContentTypeWithoutCharset(input); Assert.assertEquals("application/json", actual); }
@Test public void determineContentTypeWithoutCharset_withCharset() throws Exception { final String input = "application/json; charset=utf-8"; final String actual = StringHelper.determineContentTypeWithoutCharset(input); Assert.assertEquals("application/json", actual); } |
### Question:
TextTableParser { public boolean nextRow() throws IOException { do { currentLine = reader.readLine(); } while ((currentLine != null) && (currentLine.length() < lastMandatoryColumnStart)); return (currentLine != null); } TextTableParser(Reader reader); TextTableParser(Reader reader, int optionalColumnCount); int getColumnCount(); String getColumn(int index); boolean nextRow(); }### Answer:
@Test public void assertThatReaderWithoutTableIsParsed() throws Exception { TextTableParser listParser = new TextTableParser(new StringReader("Just some text to be ignored")); assertFalse("There should not be any row", listParser.nextRow()); }
@Test public void assertNextRow() throws Exception { TextTableParser listParser = new TextTableParser(new StringReader("Just some text to be ignored\n" + "----- -- ------\n" + "AAAAA BB CCCCCC\n" + "LLLLL DD ZZZZZZ")); assertTrue("The nextLine() returned false", listParser.nextRow()); assertTrue("The nextLine() returned false", listParser.nextRow()); assertFalse("The nextLine() returned true", listParser.nextRow()); } |
### Question:
TextTableParser { public int getColumnCount() { return columns.size(); } TextTableParser(Reader reader); TextTableParser(Reader reader, int optionalColumnCount); int getColumnCount(); String getColumn(int index); boolean nextRow(); }### Answer:
@Test public void assertColumnCount() throws Exception { TextTableParser listParser = new TextTableParser(new StringReader("Just some text to be ignored\n" + "----- -- ------\n")); assertEquals("The column count was incorrect", 3, listParser.getColumnCount()); }
@Bug(4666) @Test public void assertDashInTextIsIgnored() throws Exception { TextTableParser listParser = new TextTableParser(new StringReader("Server: server-name\n" + "----- -- ------\n")); assertEquals("The column count was incorrect", 3, listParser.getColumnCount()); } |
### Question:
UriHelper { public static boolean areSame(final URI a, final URI b) { if (a == null) { return b == null; } if (b == null) { return false; } if (!StringHelper.equalIgnoringCase(a.getScheme(), b.getScheme())) { return false; } if (!StringHelper.equalIgnoringCase(a.getHost(), b.getHost())) { return false; } final int aPort = normalizePort(a); final int bPort = normalizePort(b); if (aPort != bPort) { return false; } final String aPath = normalizePath(a); final String bPath = normalizePath(b); if (!StringHelper.equal(aPath, bPath)) { return false; } if (!StringHelper.equal(a.getQuery(), b.getQuery())) { return false; } if (!StringHelper.equal(a.getFragment(), b.getFragment())) { return false; } return true; } static boolean areSame(final URI a, final URI b); static boolean areSameGitRepo(final URIish a, final URIish b); static boolean areSameGitRepo(final URI a, final URI b); static boolean hasPath(final URI uri); static boolean isWellFormedUriString(final String uriString); static URI join(final URI collectionUri, final Object... components); static URI join(final String collectionUrl, final Object... components); static String serializeParameters(final Map<String, String> parameters); static final String UTF_8; }### Answer:
@Test public void areSame_sameInstance() throws Exception { final URI uri = URI.create("http: Assert.assertTrue(UriHelper.areSame(uri, uri)); } |
### Question:
TeamRestClient { static String createAuthorization(final StandardUsernamePasswordCredentials credentials) { final String username = credentials.getUsername(); final Secret secretPassword = credentials.getPassword(); final String password = secretPassword.getPlainText(); final String credPair = username + ":" + password; final byte[] credBytes = credPair.getBytes(MediaType.UTF_8); final String base64enc = DatatypeConverter.printBase64Binary(credBytes); final String result = "Basic " + base64enc; return result; } TeamRestClient(final URI collectionUri); TeamRestClient(final URI collectionUri, final StandardUsernamePasswordCredentials credentials); TeamRestClient(final String collectionUri, final StandardUsernamePasswordCredentials credentials); static TResponse deserialize(final Class<TResponse> responseClass, final String stringResponseBody); String ping(); ListOfGitRepositories getRepositories(); TeamGitStatus addCommitStatus(final GitCodePushedEventArgs args, final TeamGitStatus status); WorkItem getWorkItem(final int workItemId); void addHyperlinkToWorkItem(final int workItemId, final String hyperlink); TeamGitStatus addPullRequestStatus(final PullRequestMergeCommitCreatedEventArgs args, final TeamGitStatus status); TeamGitStatus addPullRequestIterationStatus(final PullRequestMergeCommitCreatedEventArgs args, final TeamGitStatus status); void sendJobCompletionEvent(final JobCompletionEventArgs args); }### Answer:
@Test public void createAuthorization_typical() throws Exception { final String personalAccessToken = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; final StandardUsernamePasswordCredentials creds = new UsernamePasswordCredentialsImpl( CredentialsScope.SYSTEM, "buildAccount", null, "PAT", personalAccessToken); final String actual = TeamRestClient.createAuthorization(creds); Assert.assertEquals("Basic UEFUOmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE=", actual); } |
### Question:
UriHelper { public static boolean hasPath(final URI uri) { final String path = uri.getPath(); if (path != null) { if (path.length() > 0 && !path.equals("/")) { return true; } } return false; } static boolean areSame(final URI a, final URI b); static boolean areSameGitRepo(final URIish a, final URIish b); static boolean areSameGitRepo(final URI a, final URI b); static boolean hasPath(final URI uri); static boolean isWellFormedUriString(final String uriString); static URI join(final URI collectionUri, final Object... components); static URI join(final String collectionUrl, final Object... components); static String serializeParameters(final Map<String, String> parameters); static final String UTF_8; }### Answer:
@Test public void hasPath_hostOnly() throws Exception { final URI input = URI.create("https: final boolean actual = UriHelper.hasPath(input); Assert.assertEquals(false, actual); }
@Test public void hasPath_hostSlash() throws Exception { final URI input = URI.create("https: final boolean actual = UriHelper.hasPath(input); Assert.assertEquals(false, actual); }
@Test public void hasPath_path() throws Exception { final URI input = URI.create("https: final boolean actual = UriHelper.hasPath(input); Assert.assertEquals(true, actual); }
@Test public void hasPath_pathSlash() throws Exception { final URI input = URI.create("https: final boolean actual = UriHelper.hasPath(input); Assert.assertEquals(true, actual); } |
### Question:
TeamRestClient { public String ping() throws IOException { final URI requestUri; if (isTeamServices) { requestUri = UriHelper.join(collectionUri, "_apis", "connectiondata"); } else { requestUri = UriHelper.join(collectionUri, "_home", "About"); } return request(String.class, HttpMethod.GET, requestUri, null); } TeamRestClient(final URI collectionUri); TeamRestClient(final URI collectionUri, final StandardUsernamePasswordCredentials credentials); TeamRestClient(final String collectionUri, final StandardUsernamePasswordCredentials credentials); static TResponse deserialize(final Class<TResponse> responseClass, final String stringResponseBody); String ping(); ListOfGitRepositories getRepositories(); TeamGitStatus addCommitStatus(final GitCodePushedEventArgs args, final TeamGitStatus status); WorkItem getWorkItem(final int workItemId); void addHyperlinkToWorkItem(final int workItemId, final String hyperlink); TeamGitStatus addPullRequestStatus(final PullRequestMergeCommitCreatedEventArgs args, final TeamGitStatus status); TeamGitStatus addPullRequestIterationStatus(final PullRequestMergeCommitCreatedEventArgs args, final TeamGitStatus status); void sendJobCompletionEvent(final JobCompletionEventArgs args); }### Answer:
@Ignore("Only works on visualstudio.com due to the use of the Authorization header") @Category(IntegrationTests.class) @Test public void ping() throws Exception { final IntegrationTestHelper helper = new IntegrationTestHelper(); final URI collectionUri = new URI(helper.getServerUrl()); final StandardUsernamePasswordCredentials creds = new UsernamePasswordCredentialsImpl( CredentialsScope.SYSTEM, "buildAccount", null, helper.getUserName(), helper.getUserPassword()); final TeamRestClient cut = new TeamRestClient(collectionUri, creds); cut.ping(); } |
### Question:
DateUtil { public static String toString(final DateVersionSpec dateVersionSpec) { final Calendar calendar = dateVersionSpec.getDate(); return toString(calendar); } private DateUtil(); static String toString(final DateVersionSpec dateVersionSpec); static String toString(final Calendar calendar); static String toString(final Date dateTime); static Date parseDate(String dateString); @SuppressWarnings("deprecation") static Date parseDate(String dateString, Locale locale, TimeZone timezone); static final ThreadLocal<SimpleDateFormat> TFS_DATETIME_FORMATTER; }### Answer:
@Test public void toString_date() throws Exception { final String actual = DateUtil.toString(new Date(1372779650000L)); Assert.assertEquals("D2013-07-02T15:40:50Z", actual); }
@Test public void toString_calendar() throws Exception { final String actual = DateUtil.toString(fixedPointInTime); Assert.assertEquals("D2013-07-02T15:40:50Z", actual); }
@Test public void toString_dateVersionSpec() throws Exception { final String actual = DateUtil.toString(dateVersionSpec); Assert.assertEquals("D2013-07-02T15:40:50Z", actual); } |
### Question:
QueryString extends LinkedHashMap<String, String> { @Override public String toString() { return UriHelper.serializeParameters(this); } QueryString(); QueryString(final String... nameValuePairs); @Override String toString(); }### Answer:
@Test public void toString_typical() throws Exception { final QueryString cut = new QueryString(); cut.put("answer", "42"); final String actual = cut.toString(); Assert.assertEquals("answer=42", actual); }
@Test public void constructor_typical() throws Exception { final QueryString cut = new QueryString("answer", "42"); final String actual = cut.toString(); Assert.assertEquals("answer=42", actual); }
@Test public void constructor_twoPairs() throws Exception { final QueryString cut = new QueryString("answer", "42", "question", "whatdoyoug"); final String actual = cut.toString(); Assert.assertEquals("answer=42&question=whatdoyoug", actual); } |
### Question:
Server implements ServerConfigurationProvider, Closable { public Workspaces getWorkspaces() { if (workspaces == null) { workspaces = new Workspaces(this); } return workspaces; } Server(final Launcher launcher, final TaskListener taskListener, final String url, final String username, final String password); Server(final Launcher launcher, final TaskListener taskListener, final String url, final String username, final String password, final WebProxySettings webProxySettings, final ExtraSettings extraSettings); static Server create(final Launcher launcher, final TaskListener taskListener, final String url, final StandardUsernamePasswordCredentials credentials, final WebProxySettings webProxySettings, final ExtraSettings extraSettings); Project getProject(String projectPath); Workspaces getWorkspaces(); @SuppressFBWarnings(value = { "DC_DOUBLECHECK", "IS2_INCONSISTENT_SYNC"}, justification = "Only synchronize if not null") MockableVersionControlClient getVersionControlClient(); HttpClient getHttpClient(); T execute(final Callable<T, E> callable); String getUrl(); String getUserName(); String getUserPassword(); Launcher getLauncher(); WebProxySettings getWebProxySettings(); ExtraSettings getExtraSettings(); TaskListener getListener(); synchronized void close(); IIdentityManagementService createIdentityManagementService(); }### Answer:
@Test public void assertGetWorkspacesReturnSameObject() throws IOException { Server server = createServer(); assertNotNull("Workspaces object can not be null", server.getWorkspaces()); assertSame("getWorkspaces() returned different objects", server.getWorkspaces(), server.getWorkspaces()); } |
### Question:
Server implements ServerConfigurationProvider, Closable { public Project getProject(String projectPath) { if (! projects.containsKey(projectPath)) { projects.put(projectPath, new Project(this, projectPath)); } return projects.get(projectPath); } Server(final Launcher launcher, final TaskListener taskListener, final String url, final String username, final String password); Server(final Launcher launcher, final TaskListener taskListener, final String url, final String username, final String password, final WebProxySettings webProxySettings, final ExtraSettings extraSettings); static Server create(final Launcher launcher, final TaskListener taskListener, final String url, final StandardUsernamePasswordCredentials credentials, final WebProxySettings webProxySettings, final ExtraSettings extraSettings); Project getProject(String projectPath); Workspaces getWorkspaces(); @SuppressFBWarnings(value = { "DC_DOUBLECHECK", "IS2_INCONSISTENT_SYNC"}, justification = "Only synchronize if not null") MockableVersionControlClient getVersionControlClient(); HttpClient getHttpClient(); T execute(final Callable<T, E> callable); String getUrl(); String getUserName(); String getUserPassword(); Launcher getLauncher(); WebProxySettings getWebProxySettings(); ExtraSettings getExtraSettings(); TaskListener getListener(); synchronized void close(); IIdentityManagementService createIdentityManagementService(); }### Answer:
@Test public void assertGetProjectWithSameProjectPathReturnsSameInstance() throws IOException { Server server = createServer(); assertNotNull("Project object can not be null", server.getProject("$/projectPath")); assertSame("getProject() returned different objects", server.getProject("$/projectPath"), server.getProject("$/projectPath")); }
@Test public void assertGetProjectWithDifferentProjectPathReturnsNotSameInstance() throws IOException { Server server = createServer(); assertNotSame("getProject() did not return different objects", server.getProject("$/projectPath"), server.getProject("$/otherPath")); } |
### Question:
ChangeSet extends hudson.scm.ChangeLogSet.Entry { @Override public String getMsg() { return comment; } ChangeSet(); ChangeSet(String version, Date date, String userString, String comment); ChangeSet(String version, Date date, User author, String comment); @Override Collection<String> getAffectedPaths(); @Override Collection<? extends hudson.scm.ChangeLogSet.AffectedFile> getAffectedFiles(); @Override ChangeLogSet getParent(); @Override User getAuthor(); @Override String getMsg(); @Exported String getVersion(); void setVersion(String version); @Exported String getCommitId(); @Exported String getDomain(); @Exported String getUser(); void setUser(String user); @Exported Date getDate(); void setDateStr(String dateStr); @Exported String getComment(); void setComment(String comment); void setCheckedInBy(String checkedInByUserString); String getCheckedInBy(); User getCheckedInByUser(); void setCheckedInByUser(User checkedInBy); @Exported List<Item> getItems(); void add(ChangeSet.Item item); }### Answer:
@Test public void assertMsgReturnsComment() { ChangeSet changeset = new ChangeSet("0", null, "snd\\user", "comment"); assertSame("The getMsg() did not return the comment", "comment", changeset.getMsg()); } |
### Question:
ChangeSet extends hudson.scm.ChangeLogSet.Entry { @Exported public String getUser() { return userString; } ChangeSet(); ChangeSet(String version, Date date, String userString, String comment); ChangeSet(String version, Date date, User author, String comment); @Override Collection<String> getAffectedPaths(); @Override Collection<? extends hudson.scm.ChangeLogSet.AffectedFile> getAffectedFiles(); @Override ChangeLogSet getParent(); @Override User getAuthor(); @Override String getMsg(); @Exported String getVersion(); void setVersion(String version); @Exported String getCommitId(); @Exported String getDomain(); @Exported String getUser(); void setUser(String user); @Exported Date getDate(); void setDateStr(String dateStr); @Exported String getComment(); void setComment(String comment); void setCheckedInBy(String checkedInByUserString); String getCheckedInBy(); User getCheckedInByUser(); void setCheckedInByUser(User checkedInBy); @Exported List<Item> getItems(); void add(ChangeSet.Item item); }### Answer:
@Test public void assertUserNameIsSetCorrectly() { ChangeSet changeset = new ChangeSet("0", null, "RNO\\_MCLWEB", "comment"); assertEquals("The user name was incorrect", "_MCLWEB", changeset.getUser()); } |
### Question:
ChangeSet extends hudson.scm.ChangeLogSet.Entry { @Exported public String getDomain() { return domain; } ChangeSet(); ChangeSet(String version, Date date, String userString, String comment); ChangeSet(String version, Date date, User author, String comment); @Override Collection<String> getAffectedPaths(); @Override Collection<? extends hudson.scm.ChangeLogSet.AffectedFile> getAffectedFiles(); @Override ChangeLogSet getParent(); @Override User getAuthor(); @Override String getMsg(); @Exported String getVersion(); void setVersion(String version); @Exported String getCommitId(); @Exported String getDomain(); @Exported String getUser(); void setUser(String user); @Exported Date getDate(); void setDateStr(String dateStr); @Exported String getComment(); void setComment(String comment); void setCheckedInBy(String checkedInByUserString); String getCheckedInBy(); User getCheckedInByUser(); void setCheckedInByUser(User checkedInBy); @Exported List<Item> getItems(); void add(ChangeSet.Item item); }### Answer:
@Test public void assertDomainNameIsSetCorrectly() { ChangeSet changeset = new ChangeSet("0", null, "RNO\\_MCLWEB", "comment"); assertEquals("The domain name was incorrect", "RNO", changeset.getDomain()); } |
### Question:
ChangeLogSet extends hudson.scm.ChangeLogSet<ChangeSet> { public Iterator<ChangeSet> iterator() { return changesets.iterator(); } ChangeLogSet(final Run<?, ?> build, final RepositoryBrowser<?> browser, final List<ChangeSet> changesets); @Deprecated /* TODO: Used by TeamSystemWebAccessBrowserTest, should update to use non-deprecated method instead */ ChangeLogSet(final AbstractBuild build, final ChangeSet[] changesetArray); ChangeLogSet(final Run<?, ?> build, final RepositoryBrowser<?> browser, final ChangeSet[] changesetArray); @Override boolean isEmptySet(); Iterator<ChangeSet> iterator(); }### Answer:
@Test public void assertChangeSetsHaveLogSetParent() throws Exception { List<ChangeSet> changesets = new ArrayList<ChangeSet>(); changesets.add(new ChangeSet("version", null, "user", "comment")); ChangeLogSet logset = new ChangeLogSet(null, null, changesets); ChangeSet changeset = logset.iterator().next(); assertNotNull("Log set parent was null change set", changeset.getParent()); } |
### Question:
ChangeLogSet extends hudson.scm.ChangeLogSet<ChangeSet> { @Override public boolean isEmptySet() { return changesets.isEmpty(); } ChangeLogSet(final Run<?, ?> build, final RepositoryBrowser<?> browser, final List<ChangeSet> changesets); @Deprecated /* TODO: Used by TeamSystemWebAccessBrowserTest, should update to use non-deprecated method instead */ ChangeLogSet(final AbstractBuild build, final ChangeSet[] changesetArray); ChangeLogSet(final Run<?, ?> build, final RepositoryBrowser<?> browser, final ChangeSet[] changesetArray); @Override boolean isEmptySet(); Iterator<ChangeSet> iterator(); }### Answer:
@Test public void assertIsEmptyReturnsFalseWhenNoChangesets() throws Exception { List<ChangeSet> changesets = new ArrayList<ChangeSet>(); ChangeLogSet logset = new ChangeLogSet(null, null, changesets); assertTrue("The isEmpty did not return true with an empty log set", logset.isEmptySet()); }
@Test public void assertIsEmptyReturnsTrueWithChangesets() throws Exception { List<ChangeSet> changesets = new ArrayList<ChangeSet>(); changesets.add(new ChangeSet("version", null, "user", "comment")); ChangeLogSet logset = new ChangeLogSet(null, null, changesets); assertFalse("The isEmpty did not return false with a log set with change sets", logset.isEmptySet()); } |
### Question:
NativeLibraryManager implements NativeLibraryExtractor { static String buildPathToNativeFile(final String operatingSystem, final String architecture, final String fileName) { final StringBuilder sb = new StringBuilder(NATIVE.length() + 1 + operatingSystem.length() + 1 + 7 + 1 + fileName.length()); sb.append(NATIVE).append('/'); sb.append(operatingSystem).append('/'); if (architecture != null) { sb.append(architecture).append('/'); } sb.append(fileName); final String result = sb.toString(); return result; } NativeLibraryManager(final PersistenceStore store); void extractFiles(); void extractFile(final String operatingSystem, final String architecture, final String fileName); static synchronized void initialize(); }### Answer:
@Test public void buildPathToNativeFile_threeComponents() throws Exception { final String actual = NativeLibraryManager.buildPathToNativeFile("win32", "x86", "native_auth.dll"); Assert.assertEquals("native/win32/x86/native_auth.dll", actual); }
@Test public void buildPathToNativeFile_twoComponents() throws Exception { final String actual = NativeLibraryManager.buildPathToNativeFile("macosx", null, "libnative_auth.jnilib"); Assert.assertEquals("native/macosx/libnative_auth.jnilib", actual); } |
### Question:
NativeLibraryManager implements NativeLibraryExtractor { public void extractFile(final String operatingSystem, final String architecture, final String fileName) throws IOException { final String pathToNativeFile = buildPathToNativeFile(operatingSystem, architecture, fileName); if (!store.containsItem(pathToNativeFile)) { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = metaClass.getResourceAsStream(pathToNativeFile); outputStream = store.getItemOutputStream(pathToNativeFile); IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } NativeLibraryManager(final PersistenceStore store); void extractFiles(); void extractFile(final String operatingSystem, final String architecture, final String fileName); static synchronized void initialize(); }### Answer:
@Test public void extractFile() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PersistenceStore store = mock(PersistenceStore.class); when(store.containsItem(isA(String.class))).thenReturn(false); when(store.getItemOutputStream(isA(String.class))).thenReturn(baos); final NativeLibraryManager manager = new NativeLibraryManager(store); manager.extractFile("win32", "x86", "native_auth.dll"); Assert.assertEquals(67240, baos.size()); }
@Test public void extractFile_noArch() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PersistenceStore store = mock(PersistenceStore.class); when(store.containsItem(isA(String.class))).thenReturn(false); when(store.getItemOutputStream(isA(String.class))).thenReturn(baos); final NativeLibraryManager manager = new NativeLibraryManager(store); manager.extractFile("macosx", null, "libnative_auth.jnilib"); Assert.assertEquals(118960, baos.size()); } |
### Question:
NativeLibraryManager implements NativeLibraryExtractor { public void extractFiles() throws IOException { extractFiles(this); } NativeLibraryManager(final PersistenceStore store); void extractFiles(); void extractFile(final String operatingSystem, final String architecture, final String fileName); static synchronized void initialize(); }### Answer:
@Test public void extractFiles() throws Exception { final NativeLibraryExtractor extractor = mock(NativeLibraryExtractor.class); NativeLibraryManager.extractFiles(extractor); verify(extractor, times(82)).extractFile(isA(String.class), Matchers.<String>anyObject(), isA(String.class)); } |
### Question:
GitStatusContext { public static GitStatusContext fromJsonString(final String jsonString) { final JSONObject jsonObject = JSONObject.fromObject(jsonString); final GitStatusContext result; final JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(GitStatusContext.class); result = (GitStatusContext) JSONObject.toBean(jsonObject, jsonConfig); return result; } GitStatusContext(); GitStatusContext(final String name, final String genre); static GitStatusContext fromJsonString(final String jsonString); public String name; public String genre; }### Answer:
@Test public void fromJsonString_typical() throws Exception { final GitStatusContext actual = GitStatusContext.fromJsonString(FORMATTED_INPUT); Assert.assertEquals("Build123", actual.name); Assert.assertEquals("continuous-integration", actual.genre); } |
### Question:
Workspaces implements ListWorkspacesCommand.WorkspaceFactory { public Workspace getWorkspace(String workspaceName) { if (!workspaces.containsKey(workspaceName)) { populateMapFromServer(); } return workspaces.get(workspaceName); } Workspaces(Server server); Workspace getWorkspace(String workspaceName); boolean exists(String workspaceName); boolean exists(Workspace workspace); String getWorkspaceMapping(final String localPath); Workspace newWorkspace(final String workspaceName, final String serverPath, Collection<String> cloakedPaths, final String localPath); void deleteWorkspace(Workspace workspace); Workspace createWorkspace(String name, String computer, String owner, String comment); }### Answer:
@Test public void assertListFromServerIsParsedProperly() throws Exception { when(server.execute(isA(Callable.class))).thenReturn(parse( "--------- -------------- -------- ----------------------------------------------------------------------------------------------------------\n" + "\n" + "name1 SND\\redsolo_cp COMPUTER\n")); Workspaces workspaces = new Workspaces(server); Workspace workspace = workspaces.getWorkspace("name1"); assertNotNull("Workspace was null", workspace); }
@Test public void assertListFromServerIsRetrievedOnce() throws Exception { when(server.execute(isA(Callable.class))).thenReturn(parse( "--------- -------------- -------- ----------------------------------------------------------------------------------------------------------\n" + "\n" + "name1 SND\\redsolo_cp COMPUTER\n")); Workspaces workspaces = new Workspaces(server); Workspace workspace = workspaces.getWorkspace("name1"); assertNotNull("Workspace was null", workspace); workspace = workspaces.getWorkspace("name1"); assertNotNull("Workspace was null", workspace); verify(server, times(1)).execute(isA(Callable.class)); }
@Test public void assertGetUnknownWorkspaceReturnsNull() throws Exception { when(server.execute(isA(Callable.class))).thenReturn(parse("")); Workspaces workspaces = new Workspaces(server); assertNull("The unknown workspace was not null", workspaces.getWorkspace("name1")); } |
### Question:
Workspaces implements ListWorkspacesCommand.WorkspaceFactory { public boolean exists(String workspaceName) { if (!workspaces.containsKey(workspaceName)) { populateMapFromServer(); } return workspaces.containsKey(workspaceName); } Workspaces(Server server); Workspace getWorkspace(String workspaceName); boolean exists(String workspaceName); boolean exists(Workspace workspace); String getWorkspaceMapping(final String localPath); Workspace newWorkspace(final String workspaceName, final String serverPath, Collection<String> cloakedPaths, final String localPath); void deleteWorkspace(Workspace workspace); Workspace createWorkspace(String name, String computer, String owner, String comment); }### Answer:
@Test public void assertExistsWorkspace() throws Exception { when(server.execute(isA(Callable.class))).thenReturn(parse( "--------- -------------- -------- ----------------------------------------------------------------------------------------------------------\n" + "\n" + "name1 SND\\redsolo_cp COMPUTER\n")); Workspaces workspaces = new Workspaces(server); assertTrue("The workspace was reported as non existant", workspaces.exists(new Workspace("name1"))); }
@Test public void assertWorkspaceExistsWithOnlyName() throws Exception { when(server.execute(isA(Callable.class))).thenReturn(parse( "--------- -------------- -------- ----------------------------------------------------------------------------------------------------------\n" + "\n" + "name1 SND\\redsolo_cp COMPUTER\n")); Workspaces workspaces = new Workspaces(server); assertTrue("The workspace was reported as non existant", workspaces.exists("name1")); }
@Test public void assertUnknownWorkspaceDoesNotExists() throws Exception { when(server.execute(isA(Callable.class))).thenReturn(parse("")); Workspaces workspaces = new Workspaces(server); assertFalse("The unknown workspace was reported as existing", workspaces.exists(new Workspace("name1"))); } |
### Question:
Workspaces implements ListWorkspacesCommand.WorkspaceFactory { public Workspace createWorkspace(String name, String computer, String owner, String comment) { return new Workspace(name, computer, owner, comment); } Workspaces(Server server); Workspace getWorkspace(String workspaceName); boolean exists(String workspaceName); boolean exists(Workspace workspace); String getWorkspaceMapping(final String localPath); Workspace newWorkspace(final String workspaceName, final String serverPath, Collection<String> cloakedPaths, final String localPath); void deleteWorkspace(Workspace workspace); Workspace createWorkspace(String name, String computer, String owner, String comment); }### Answer:
@Test public void assertWorkspaceFactory() { ListWorkspacesCommand.WorkspaceFactory factory = new Workspaces(server); Workspace workspace = factory.createWorkspace("name", "computer", "owner", "comment"); assertEquals("Workspace name was incorrect", "name", workspace.getName()); assertEquals("Workspace comment was incorrect", "comment", workspace.getComment()); } |
### Question:
TeamGitStatus { public String toJson() { final JSONObject jsonObject = JSONObject.fromObject(this); final String result = jsonObject.toString(); return result; } static TeamGitStatus fromRun(@Nonnull final Run<?, ?> run); static TeamGitStatus fromJob(@Nonnull final Job job); String toJson(); public GitStatusState state; public String description; public String targetUrl; public GitStatusContext context; }### Answer:
@Test public void toJson_typical() { final TeamGitStatus cut = new TeamGitStatus(); cut.state = GitStatusState.Pending; cut.description = "The build is in progress"; cut.targetUrl = "https: cut.context = new GitStatusContext("Build124", "continuous-integration"); final String actual = cut.toJson(); final String expected = "{" + "\"state\":\"Pending\"," + "\"description\":\"The build is in progress\"," + "\"targetUrl\":\"https: "\"context\":" + "{" + "\"name\":\"Build124\"," + "\"genre\":\"continuous-integration\"" + "}" + "}"; Assert.assertEquals(expected, actual); } |
### Question:
GitPushEvent extends AbstractHookEvent { static URI determineCollectionUri(final URI repoApiUri) { final String path = repoApiUri.getPath(); final int i = path.indexOf("_apis/"); if (i == -1) { final String template = "Repository url '%s' did not contain '_apis/'."; throw new IllegalArgumentException(String.format(template, repoApiUri)); } final String pathBeforeApis = path.substring(0, i); final URI uri; try { uri = new URI(repoApiUri.getScheme(), repoApiUri.getAuthority(), pathBeforeApis, repoApiUri.getQuery(), repoApiUri.getFragment()); } catch (final URISyntaxException e) { throw new Error(e); } return uri; } @Override JSONObject perform(final ObjectMapper mapper, final Event serviceHookEvent, final String message, final String detailedMessage); }### Answer:
@Test public void determineCollectionUri_sample() throws Exception { final URI input = URI.create("https: final URI actual = GitPushEvent.determineCollectionUri(input); final URI expected = URI.create("https: Assert.assertEquals(expected, actual); } |
### Question:
RailsModelParser implements EventBasedTokenizer { public static Map<String, Map<String, ParameterDataType>> parse(@Nonnull File rootFile) { if (!rootFile.exists() || !rootFile.isDirectory()) { LOG.error("Root file not found or is not directory. Exiting."); return null; } File modelDir = new File(rootFile,"app/models"); if (!modelDir.exists() || !modelDir.isDirectory()) { LOG.error("{rootFile}/app/models/ not found or is not directory. Exiting."); return null; } String[] rubyExtension = new String[] { "rb" }; Collection<File> rubyFiles = FileUtils.listFiles(modelDir, rubyExtension, true); RailsModelParser parser = new RailsModelParser(); for (File rubyFile : rubyFiles) { parser.modelName = ""; parser.modelAttributes = map(); EventBasedTokenizerRunner.runRails(rubyFile, true, false, parser); if (!parser.modelName.isEmpty()) { parser.models.put(parser.modelName, parser.modelAttributes); } } return parser.models; } static Map<String, Map<String, ParameterDataType>> parse(@Nonnull File rootFile); @Override boolean shouldContinue(); @Override void processToken(int type, int lineNumber, String stringValue); }### Answer:
@Test public void testRailsGoatModelParser() { File f = new File(RAILSGOAT_SOURCE_LOCATION); assert(f.exists()); assert(f.isDirectory()); System.err.println("parsing "+f.getAbsolutePath() ); Map<String, Map<String, ParameterDataType>> modelMap = RailsModelParser.parse(f); System.err.println( "\n" + "Parse done." + "\n"); compareModels(RAILSGOAT_MODELS, modelMap); } |
### Question:
UrlAction { public String getAction() { return action; } UrlAction(); UrlAction(final String action); UrlAction(final String action, final PhaseId phaseId); PhaseId getPhaseId(); boolean onPostback(); void setOnPostback(final boolean onPostback); void setPhaseId(final String phaseId); String getAction(); void setAction(final String action); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testUrlActionStringSetsActionMethod() { String action = "#{this.is.my.action}"; UrlAction urlAction = new UrlAction(action); assertEquals(action, urlAction.getAction()); } |
### Question:
QueryParameter { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expression == null) ? 0 : expression.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } QueryParameter(); QueryParameter(final String name, final String expression); String getName(); void setName(final String name); String getExpression(); void setExpression(final String expression); boolean decode(); void setDecode(final boolean decode); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testHashCodeAndEquals() { QueryParameter param1 = new QueryParameter("foo", "bar"); QueryParameter param2 = new QueryParameter("foo", "bar"); QueryParameter param3 = new QueryParameter("foo", "bar2"); QueryParameter param4 = new QueryParameter("foo2", "bar"); assertNotSame(param1.hashCode(), param3.hashCode()); assertNotSame(param1.hashCode(), param4.hashCode()); assertNotSame(param3.hashCode(), param4.hashCode()); assertEquals(param1.hashCode(), param2.hashCode()); assertNotSame(param1, param3); assertNotSame(param1, param4); assertNotSame(param3, param4); assertEquals(param1, param2); } |
### Question:
URLPatternParser { public int getParameterCount() { return pathParameters.size(); } URLPatternParser(final String pattern); boolean matches(final URL target); @Deprecated boolean matches(final String target); List<PathParameter> getPathParameters(); List<PathParameter> parse(final URL url); URL getMappedURL(final Object... params); int getParameterCount(); Object getPattern(); boolean isElPattern(); }### Answer:
@Test public void testGetParameterCount() { URLPatternParser parser = new URLPatternParser( "/project/#{paramsBean.project}/#{paramsBean.iteration}/#{paramsBean.story}"); assertEquals(3, parser.getParameterCount()); } |
### Question:
URL { public String toURL() { return originalURL; } URL(String url); URL(final List<String> segments, final Metadata metadata); static URL build(final String url); static URL build(final List<String> segments, final Metadata metadata); List<String> getDecodedSegments(); List<String> getEncodedSegments(); URL decode(); URL encode(); int numSegments(); @Override String toString(); String toURL(); List<String> getSegments(); boolean hasLeadingSlash(); boolean hasTrailingSlash(); String getEncoding(); void setEncoding(final String encoding); Metadata getMetadata(); void setMetadata(final Metadata metadata); }### Answer:
@Test public void testURLPreservesOriginalURL() throws Exception { String value = "/com/ocpsoft/pretty/"; URL url = new URL(value); assertEquals(value, url.toURL()); } |
### Question:
URL { public URL decode() { return new URL(getDecodedSegments(), metadata); } URL(String url); URL(final List<String> segments, final Metadata metadata); static URL build(final String url); static URL build(final List<String> segments, final Metadata metadata); List<String> getDecodedSegments(); List<String> getEncodedSegments(); URL decode(); URL encode(); int numSegments(); @Override String toString(); String toURL(); List<String> getSegments(); boolean hasLeadingSlash(); boolean hasTrailingSlash(); String getEncoding(); void setEncoding(final String encoding); Metadata getMetadata(); void setMetadata(final Metadata metadata); }### Answer:
@Test public void testDecode() throws Exception { String value = "/\u010d"; URL url = new URL(value); URL encoded = url.encode(); assertEquals("/%C4%8D", encoded.toURL()); } |
### Question:
URL { public URL encode() { return new URL(getEncodedSegments(), metadata); } URL(String url); URL(final List<String> segments, final Metadata metadata); static URL build(final String url); static URL build(final List<String> segments, final Metadata metadata); List<String> getDecodedSegments(); List<String> getEncodedSegments(); URL decode(); URL encode(); int numSegments(); @Override String toString(); String toURL(); List<String> getSegments(); boolean hasLeadingSlash(); boolean hasTrailingSlash(); String getEncoding(); void setEncoding(final String encoding); Metadata getMetadata(); void setMetadata(final Metadata metadata); }### Answer:
@Test public void testEncode() throws Exception { String value = "/\u010d"; URL url = new URL(value); URL encoded = url.encode(); assertEquals("/%C4%8D", encoded.toURL()); URL original = encoded.decode(); assertEquals("/\u010d", original.toURL()); } |
### Question:
StringUtils { public static boolean hasLeadingSlash(final String s) { return s != null && isNotBlank(s) && SLASH == s.charAt(0); } static boolean isBlank(String s); static boolean isNotBlank(String s); static boolean hasLeadingSlash(final String s); static boolean hasTrailingSlash(final String s); static String[] splitBySlash(final String s); static int countSlashes(final String s); }### Answer:
@Test public void testHasLeadingSlash() { assertTrue(StringUtils.hasLeadingSlash("/")); assertTrue(StringUtils.hasLeadingSlash("/test")); assertTrue(StringUtils.hasLeadingSlash(" assertTrue(StringUtils.hasLeadingSlash(" assertTrue(StringUtils.hasLeadingSlash("/test/")); assertFalse(StringUtils.hasLeadingSlash(null)); assertFalse(StringUtils.hasLeadingSlash("")); assertFalse(StringUtils.hasLeadingSlash("test")); assertFalse(StringUtils.hasLeadingSlash("test/")); assertFalse(StringUtils.hasLeadingSlash("test } |
### Question:
StringUtils { public static boolean hasTrailingSlash(final String s) { return s != null && isNotBlank(s) && SLASH == s.charAt(s.length() - 1); } static boolean isBlank(String s); static boolean isNotBlank(String s); static boolean hasLeadingSlash(final String s); static boolean hasTrailingSlash(final String s); static String[] splitBySlash(final String s); static int countSlashes(final String s); }### Answer:
@Test public void testHasTrailingSlash() { assertTrue(StringUtils.hasTrailingSlash("/")); assertTrue(StringUtils.hasTrailingSlash("test/")); assertTrue(StringUtils.hasTrailingSlash(" assertTrue(StringUtils.hasTrailingSlash("test assertTrue(StringUtils.hasTrailingSlash("/test/")); assertFalse(StringUtils.hasTrailingSlash(null)); assertFalse(StringUtils.hasTrailingSlash("")); assertFalse(StringUtils.hasTrailingSlash("test")); assertFalse(StringUtils.hasTrailingSlash("/test")); assertFalse(StringUtils.hasTrailingSlash(" } |
### Question:
StringUtils { public static int countSlashes(final String s) { int result = 0; for (char ch : s.toCharArray()) { if (ch == '/') { ++result; } } return result; } static boolean isBlank(String s); static boolean isNotBlank(String s); static boolean hasLeadingSlash(final String s); static boolean hasTrailingSlash(final String s); static String[] splitBySlash(final String s); static int countSlashes(final String s); }### Answer:
@Test public void testCountSlashes() { assertEquals(0, StringUtils.countSlashes("")); assertEquals(0, StringUtils.countSlashes("abcde")); assertEquals(1, StringUtils.countSlashes("/")); assertEquals(1, StringUtils.countSlashes("/test")); assertEquals(1, StringUtils.countSlashes("test/")); assertEquals(1, StringUtils.countSlashes("test/test")); assertEquals(2, StringUtils.countSlashes(" assertEquals(2, StringUtils.countSlashes(" assertEquals(2, StringUtils.countSlashes("test assertEquals(2, StringUtils.countSlashes("/test/")); assertEquals(3, StringUtils.countSlashes("/test/test/")); } |
### Question:
PrettyURLBuilder { public List<UIParameter> extractParameters(final UIComponent component) { List<UIParameter> results = new ArrayList<UIParameter>(); for (UIComponent child : component.getChildren()) { if (child instanceof UIParameter) { results.add((UIParameter) child); } } return results; } List<UIParameter> extractParameters(final UIComponent component); @Deprecated String build(final UrlMapping mapping, final Map<String, String[]> parameters); String build(final UrlMapping mapping, final boolean encodeUrl, final Map<String, String[]> parameters); @Deprecated String build(final UrlMapping mapping, final Object... parameters); String build(final UrlMapping mapping, final boolean encodeUrl, final Object... parameters); @Deprecated String build(final UrlMapping mapping, final RequestParameter... parameters); String build(final UrlMapping mapping, final boolean encodeUrl, final RequestParameter... parameters); @Deprecated String build(final UrlMapping urlMapping, final List<UIParameter> parameters); String build(final UrlMapping urlMapping, final boolean encodeUrl, final List<UIParameter> parameters); }### Answer:
@Test public void testExtractParameters() { List<UIParameter> parameters = builder.extractParameters(link); assertEquals(5, parameters.size()); assertTrue(parameters.contains(param1)); assertTrue(parameters.contains(param2)); assertTrue(parameters.contains(param3)); assertTrue(parameters.contains(param4)); assertTrue(parameters.contains(param5)); } |
### Question:
FacesNavigationURLCanonicalizer { public static String normalizeRequestURI(final FacesContext context, final String viewId) { ExternalContext externalContext = context.getExternalContext(); return normalizeRequestURI(externalContext.getRequestServletPath(), externalContext.getRequestPathInfo(), viewId); } static String normalizeRequestURI(final FacesContext context, final String viewId); static String normalizeRequestURI(final String servletPath, final String requestPathInfo, final String viewId); }### Answer:
@Test public void testNormalizeRequestUriWithNullArguments() { assertEquals(null, FacesNavigationURLCanonicalizer.normalizeRequestURI(null, null, null)); }
@Test public void testNormalizeRequestUriWithExtensionMapping() { assertEquals("/page2.jsf", FacesNavigationURLCanonicalizer.normalizeRequestURI("/page1.jsf", null, "/page2.jsf")); }
@Test public void testNormalizeRequestUriWithPathMapping() { assertEquals("/page2.xhtml", FacesNavigationURLCanonicalizer.normalizeRequestURI("/faces", "/page1.xhtml", "/faces/page2.xhtml")); } |
### Question:
HTTPDecoder { public String decode(final String value) { String result = value; if (value != null) { try { result = URLDecoder.decode(value, "UTF-8"); } catch (Exception e) { throw new PrettyException("Could not URLDecode value <" + value + ">", e); } } return result; } String decode(final String value); String[] decode(final String[] values); }### Answer:
@Test public void testDecodeValidInputReturnsDecodedInput() { String value = "foo+bar"; assertEquals("foo bar", decoder.decode(value)); }
@Test(expected = PrettyException.class) public void testDecodeInvalidInputThrowsException() { String value = "foo+bar%"; assertEquals("foo+bar%", decoder.decode(value)); }
@Test public void testDecodeNullProducesNull() { String value = null; assertEquals(null, decoder.decode(value)); } |
### Question:
URLDuplicatePathCanonicalizer { public String canonicalize(final String url) { if (url != null && url.contains("/../")) { StringBuffer result = new StringBuffer(); Matcher m = pattern.matcher(url); while (m.find()) { if (m.group(1).equals(m.group(2))) { m.appendReplacement(result, m.group(1)); } m.appendTail(result); } return result.toString(); } return url; } String canonicalize(final String url); }### Answer:
@Test public void testRemovesDuplicatePaths() throws Exception { String url = "http: String expected = "http: assertEquals(expected, c.canonicalize(url)); }
@Test public void testIgnoresRelativePaths() throws Exception { String url = "http: String expected = "http: assertEquals(expected, c.canonicalize(url)); } |
### Question:
FacesMessagesUtils { @SuppressWarnings("unchecked") public int saveMessages(final FacesContext facesContext, final Map<String, Object> destination) { int savedCount = 0; if (facesContext != null) { Set<FacesMessageWrapper> messages = new LinkedHashSet<FacesMessageWrapper>(); for (Iterator<FacesMessage> iter = facesContext.getMessages(null); iter.hasNext();) { messages.add(new FacesMessageWrapper(iter.next())); } if (messages.size() > 0) { Set<FacesMessageWrapper> existingMessages = (LinkedHashSet<FacesMessageWrapper>) destination.get(token); if (existingMessages != null) { existingMessages.addAll(messages); } else { destination.put(token, messages); } savedCount = messages.size(); } } return savedCount; } @SuppressWarnings("unchecked") int saveMessages(final FacesContext facesContext, final Map<String, Object> destination); @SuppressWarnings("unchecked") int restoreMessages(final FacesContext facesContext, final Map<String, Object> source); }### Answer:
@Test public void testSaveMessages() { FacesContextMock facesContext = new FacesContextMock(); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Summary A", "Detail A")); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Summary B", "Detail B")); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Summary B", "Detail B")); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Summary B", "Detail B")); Map<String, Object> sessionMap = new HashMap<String, Object>(); int saved = new FacesMessagesUtils().saveMessages(facesContext, sessionMap); assertEquals(3, saved); assertNotNull(sessionMap.get(FacesMessagesUtils.token)); assertEquals(3, ((Collection<?>) sessionMap.get(FacesMessagesUtils.token)).size()); } |
### Question:
WebLibFinder extends AbstractClassFinder { public WebLibFinder(ServletContext servletContext, ClassLoader classLoader, PackageFilter packageFilter) { super(servletContext, classLoader, packageFilter); } WebLibFinder(ServletContext servletContext, ClassLoader classLoader, PackageFilter packageFilter); void findClasses(PrettyAnnotationHandler classHandler); }### Answer:
@Test @SuppressWarnings("unchecked") public void testWebLibFinder() throws Exception { URL libUrl = new URL("file:/somewhere/WEB-INF/lib/"); URL jarUrl = new URL("file", null, 0, "/somewhere/WEB-INF/lib/mylib.jar", new TestURLStreamHandler()); Set<String> libDirectory = new HashSet<String>(Arrays.asList("/WEB-INF/lib/mylib.jar")); PackageFilter filter = new PackageFilter(null); ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class); EasyMock.expect(servletContext.getResource("/WEB-INF/lib/")).andReturn(libUrl).anyTimes(); EasyMock.expect(servletContext.getResourcePaths("/WEB-INF/lib/")).andReturn(libDirectory).anyTimes(); EasyMock.expect(servletContext.getResource("/WEB-INF/lib/mylib.jar")).andReturn(jarUrl).anyTimes(); EasyMock.replay(servletContext); ClassLoader classLoader = EasyMock.createNiceMock(ClassLoader.class); EasyMock.expect(classLoader.loadClass("com.ocpsoft.pretty.faces.config.annotation.ClassFinderTestBean")) .andReturn((Class) ClassFinderTestBean.class).anyTimes(); EasyMock.replay(classLoader); PrettyAnnotationHandler handler = EasyMock.createMock(PrettyAnnotationHandler.class); handler.processClass(ClassFinderTestBean.class); EasyMock.expectLastCall().once(); EasyMock.replay(handler); WebLibFinder finder = new WebLibFinder(servletContext, classLoader, filter); finder.findClasses(handler); EasyMock.verify(handler); } |
### Question:
PrettyConfig { public UrlMapping getMappingById(String id) { if (id != null) { if (id.startsWith(PrettyContext.PRETTY_PREFIX)) { id = id.substring(PrettyContext.PRETTY_PREFIX.length()); } for (UrlMapping mapping : getMappings()) { if (mapping.getId().equals(id)) { return mapping; } } } return null; } PrettyConfig(); void setDynaviewId(final String facesDynaViewId); String getDynaviewId(); List<RewriteRule> getGlobalRewriteRules(); void setGlobalRewriteRules(final List<RewriteRule> rules); List<UrlMapping> getMappings(); void setMappings(final List<UrlMapping> mappings); UrlMapping getMappingForUrl(final URL url); boolean isMappingId(final String id); boolean isURLMapped(final URL url); boolean isViewMapped(String viewId); UrlMapping getMappingById(String id); boolean isUseEncodeUrlForRedirects(); void setUseEncodeUrlForRedirects(boolean useEncodeUrlForRedirects); @Override String toString(); static final String CONFIG_REQUEST_KEY; }### Answer:
@Test public void testGetMappingById() { UrlMapping mapping2 = config.getMappingById("testid"); assertEquals(mapping, mapping2); }
@Test public void testGetMappingByNullIdReturnsNull() { UrlMapping mapping2 = config.getMappingById(null); assertEquals(null, mapping2); } |
### Question:
PrettyConfig { public UrlMapping getMappingForUrl(final URL url) { final String mappingKey = url.toURL(); if (cachedMappings.containsKey(mappingKey)) { return cachedMappings.get(mappingKey); } for (UrlMapping mapping : getMappings()) { if (mapping.matches(url)) { if (!mapping.getPatternParser().isElPattern()) { cachedMappings.put(mappingKey, mapping); } return mapping; } } return null; } PrettyConfig(); void setDynaviewId(final String facesDynaViewId); String getDynaviewId(); List<RewriteRule> getGlobalRewriteRules(); void setGlobalRewriteRules(final List<RewriteRule> rules); List<UrlMapping> getMappings(); void setMappings(final List<UrlMapping> mappings); UrlMapping getMappingForUrl(final URL url); boolean isMappingId(final String id); boolean isURLMapped(final URL url); boolean isViewMapped(String viewId); UrlMapping getMappingById(String id); boolean isUseEncodeUrlForRedirects(); void setUseEncodeUrlForRedirects(boolean useEncodeUrlForRedirects); @Override String toString(); static final String CONFIG_REQUEST_KEY; }### Answer:
@Test public void testGetMappingForUrl() { UrlMapping mapping2 = config.getMappingForUrl(new URL("/home/en/test/")); assertEquals(mapping, mapping2); } |
### Question:
PrettyConfig { public boolean isViewMapped(String viewId) { if (viewId != null) { viewId = viewId.trim(); for (UrlMapping mapping : mappings) { if (viewId.equals(mapping.getViewId()) || (viewId.startsWith("/") && viewId.substring(1).equals(mapping.getViewId()))) { return true; } } } return false; } PrettyConfig(); void setDynaviewId(final String facesDynaViewId); String getDynaviewId(); List<RewriteRule> getGlobalRewriteRules(); void setGlobalRewriteRules(final List<RewriteRule> rules); List<UrlMapping> getMappings(); void setMappings(final List<UrlMapping> mappings); UrlMapping getMappingForUrl(final URL url); boolean isMappingId(final String id); boolean isURLMapped(final URL url); boolean isViewMapped(String viewId); UrlMapping getMappingById(String id); boolean isUseEncodeUrlForRedirects(); void setUseEncodeUrlForRedirects(boolean useEncodeUrlForRedirects); @Override String toString(); static final String CONFIG_REQUEST_KEY; }### Answer:
@Test public void isViewMapped() throws Exception { assertTrue(config.isViewMapped("/faces/view.jsf")); assertFalse(config.isViewMapped("/faces/view2.jsf")); }
@Test public void isNullViewMappedReturnsFalse() throws Exception { assertFalse(config.isViewMapped(null)); } |
### Question:
PrettyConfig { public boolean isURLMapped(final URL url) { UrlMapping mapping = getMappingForUrl(url); return mapping != null; } PrettyConfig(); void setDynaviewId(final String facesDynaViewId); String getDynaviewId(); List<RewriteRule> getGlobalRewriteRules(); void setGlobalRewriteRules(final List<RewriteRule> rules); List<UrlMapping> getMappings(); void setMappings(final List<UrlMapping> mappings); UrlMapping getMappingForUrl(final URL url); boolean isMappingId(final String id); boolean isURLMapped(final URL url); boolean isViewMapped(String viewId); UrlMapping getMappingById(String id); boolean isUseEncodeUrlForRedirects(); void setUseEncodeUrlForRedirects(boolean useEncodeUrlForRedirects); @Override String toString(); static final String CONFIG_REQUEST_KEY; }### Answer:
@Test public void testIsURLMapped() throws Exception { assertTrue(config.isURLMapped(new URL("/home/en/test/"))); assertFalse(config.isViewMapped("/home/en/notmapped/okthen")); } |
### Question:
PathParameter extends RequestParameter { public boolean isNamed() { return (null != super.getName()) && !"".equals(super.getName().trim()); } PathParameter(); PathParameter(final String name, final String value, final PrettyExpression expression); PathParameter(final String name, final String value); PathParameter copy(); int getPosition(); void setPosition(final int param); boolean isNamed(); @Override String getName(); String getRegex(); void setRegex(final String regex); void setExpressionIsPlainText(final boolean value); boolean expressionIsPlainText(); @Override String toString(); }### Answer:
@Test public void testIsNamedFalseWhenNameNull() { PathParameter parameter = new PathParameter(); assertFalse(parameter.isNamed()); }
@Test public void testIsNamedFalseWhenNameEmpty() { PathParameter parameter = new PathParameter(); parameter.setName(""); assertFalse(parameter.isNamed()); }
@Test public void testIsNamedTrueWhenNameSet() { PathParameter parameter = new PathParameter(); parameter.setName("name"); assertTrue(parameter.isNamed()); } |
### Question:
UrlAction { public PrettyExpression getAction() { return action; } UrlAction(); UrlAction(final String action); UrlAction(final PrettyExpression action); UrlAction(final String action, final PhaseId phaseId); PhaseId getPhaseId(); boolean onPostback(); void setOnPostback(final boolean onPostback); void setPhaseId(final PhaseId phaseId); PrettyExpression getAction(); void setAction(final PrettyExpression action); void setAction(final String action); boolean isInheritable(); void setInheritable(boolean inheritable); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); }### Answer:
@Test public void testUrlActionStringSetsActionMethod() { String action = "#{this.is.my.action}"; UrlAction urlAction = new UrlAction(action); assertEquals(action, urlAction.getAction().getELExpression()); } |
### Question:
RewriteEngine { public String processInbound(final HttpServletRequest request, final HttpServletResponse response, final RewriteRule rule, final String url) { String result = url; if ((rule != null) && rule.isInbound() && rule.matches(url)) { for (Processor p : processors) { result = p.processInbound(request, response, rule, result); } } return result; } String processInbound(final HttpServletRequest request, final HttpServletResponse response,
final RewriteRule rule, final String url); String processOutbound(final HttpServletRequest request, final HttpServletResponse response,
final RewriteRule rule, final String url); }### Answer:
@Test public void testRegex() throws Exception { RewriteRule c = new RewriteRule(); c.setMatch("foo"); c.setSubstitute("bar"); assertEquals("/my/bar/is/COOL", rewriteEngine.processInbound(null, null, c, url)); }
@Test public void testTrailingSlash() throws Exception { RewriteRule c = new RewriteRule(); c.setTrailingSlash(TrailingSlash.APPEND); assertEquals("/my/foo/is/COOL/", rewriteEngine.processInbound(null, null, c, url)); }
@Test public void testRemoveSingleTrailingSlash() throws Exception { RewriteRule c = new RewriteRule(); c.setTrailingSlash(TrailingSlash.APPEND); assertEquals("/", rewriteEngine.processInbound(null, null, c, "/")); }
@Test public void testToLowerCase() throws Exception { RewriteRule c = new RewriteRule(); c.setToCase(Case.LOWERCASE); assertEquals("/my/foo/is/cool", rewriteEngine.processInbound(null, null, c, url)); }
@Test public void testCustomClassProcessor() throws Exception { RewriteRule c = new RewriteRule(); c.setProcessor(MockCustomClassProcessor.class.getName()); assertEquals(MockCustomClassProcessor.RESULT, rewriteEngine.processInbound(null, null, c, url)); } |
### Question:
SpringBeanNameResolver implements ELBeanNameResolver { public boolean init(ServletContext servletContext, ClassLoader classLoader) { webAppContext = servletContext.getAttribute("org.springframework.web.context.WebApplicationContext.ROOT"); if (webAppContext == null) { if (log.isDebugEnabled()) { log.debug("WebApplicationContext not found in ServletContext. Resolver has been disabled."); } return false; } try { Class<?> webAppContextClass = classLoader.loadClass(WEB_APP_CONTEXT_CLASS); getBeanNamesMethod = webAppContextClass.getMethod(GET_BEAN_NAMES_METHOD, Class.class); if (log.isDebugEnabled()) { log.debug("Spring detected. Enabling Spring bean name resolving."); } getTargetBeanNameMethod = getProxyTargetBeanNameMethod(classLoader); return true; } catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug("WebApplicationContext class could not be found. Resolver has been disabled."); } } catch (NoSuchMethodException e) { log.warn("Cannot find getBeanNamesByType() method.", e); } catch (SecurityException e) { log.warn("Unable to init resolver due to security restrictions", e); } return false; } boolean init(ServletContext servletContext, ClassLoader classLoader); String getBeanName(Class<?> clazz); }### Answer:
@Test public void testNoSpringEnvironment() throws Exception { ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class); ClassLoader classLoader = EasyMock.createNiceMock(ClassLoader.class); EasyMock.expect(classLoader.loadClass((String) EasyMock.anyObject())).andThrow(new ClassNotFoundException()) .anyTimes(); EasyMock.replay(classLoader); SpringBeanNameResolver resolver = new SpringBeanNameResolver(); boolean initCompleted = resolver.init(servletContext, classLoader); assertFalse(initCompleted); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.