List of usage examples for java.text DateFormat getDateInstance
public static final DateFormat getDateInstance()
From source file:FormatTest.java
public FormatTestFrame() { setTitle("FormatTest"); setSize(WIDTH, HEIGHT);/* w ww .j a v a2 s. c om*/ JPanel buttonPanel = new JPanel(); okButton = new JButton("Ok"); buttonPanel.add(okButton); add(buttonPanel, BorderLayout.SOUTH); mainPanel = new JPanel(); mainPanel.setLayout(new GridLayout(0, 3)); add(mainPanel, BorderLayout.CENTER); JFormattedTextField intField = new JFormattedTextField(NumberFormat.getIntegerInstance()); intField.setValue(new Integer(100)); addRow("Number:", intField); JFormattedTextField intField2 = new JFormattedTextField(NumberFormat.getIntegerInstance()); intField2.setValue(new Integer(100)); intField2.setFocusLostBehavior(JFormattedTextField.COMMIT); addRow("Number (Commit behavior):", intField2); JFormattedTextField intField3 = new JFormattedTextField( new InternationalFormatter(NumberFormat.getIntegerInstance()) { protected DocumentFilter getDocumentFilter() { return filter; } private DocumentFilter filter = new IntFilter(); }); intField3.setValue(new Integer(100)); addRow("Filtered Number", intField3); JFormattedTextField intField4 = new JFormattedTextField(NumberFormat.getIntegerInstance()); intField4.setValue(new Integer(100)); intField4.setInputVerifier(new FormattedTextFieldVerifier()); addRow("Verified Number:", intField4); JFormattedTextField currencyField = new JFormattedTextField(NumberFormat.getCurrencyInstance()); currencyField.setValue(new Double(10)); addRow("Currency:", currencyField); JFormattedTextField dateField = new JFormattedTextField(DateFormat.getDateInstance()); dateField.setValue(new Date()); addRow("Date (default):", dateField); DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT); format.setLenient(false); JFormattedTextField dateField2 = new JFormattedTextField(format); dateField2.setValue(new Date()); addRow("Date (short, not lenient):", dateField2); try { DefaultFormatter formatter = new DefaultFormatter(); formatter.setOverwriteMode(false); JFormattedTextField urlField = new JFormattedTextField(formatter); urlField.setValue(new URL("http://java.sun.com")); addRow("URL:", urlField); } catch (MalformedURLException e) { e.printStackTrace(); } try { MaskFormatter formatter = new MaskFormatter("###-##-####"); formatter.setPlaceholderCharacter('0'); JFormattedTextField ssnField = new JFormattedTextField(formatter); ssnField.setValue("078-05-1120"); addRow("SSN Mask:", ssnField); } catch (ParseException exception) { exception.printStackTrace(); } JFormattedTextField ipField = new JFormattedTextField(new IPAddressFormatter()); ipField.setValue(new byte[] { (byte) 130, 65, 86, 66 }); addRow("IP Address:", ipField); }
From source file:net.alexjf.tmm.fragments.ImmedTransactionEditorFragment.java
public ImmedTransactionEditorFragment() { dateFormat = DateFormat.getDateInstance(); timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); }
From source file:com.nextgis.maplibui.formcontrol.DateTime.java
@Override public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor, SharedPreferences preferences) throws JSONException { JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY); mFieldName = attributes.getString(JSON_FIELD_NAME_KEY); mIsShowLast = ControlHelper.isSaveLastValue(attributes); if (!ControlHelper.isEnabled(fields, mFieldName)) { setEnabled(false);/* w w w . j a v a 2s.c om*/ getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP); } if (attributes.has(JSON_DATE_TYPE_KEY)) { mPickerType = attributes.getInt(JSON_DATE_TYPE_KEY); } switch (mPickerType) { case 0: mDateFormat = (SimpleDateFormat) DateFormat.getDateInstance(); mPickerType = GeoConstants.FTDate; break; case 1: mDateFormat = (SimpleDateFormat) DateFormat.getTimeInstance(); mPickerType = GeoConstants.FTTime; break; default: mPickerType = FTDateTime; case 2: mDateFormat = (SimpleDateFormat) DateFormat.getDateTimeInstance(); mPickerType = GeoConstants.FTDateTime; break; } long timestamp = System.currentTimeMillis(); if (ControlHelper.hasKey(savedState, mFieldName)) { timestamp = savedState.getLong(ControlHelper.getSavedStateKey(mFieldName)); } else if (null != featureCursor) { // feature exists int column = featureCursor.getColumnIndex(mFieldName); if (column >= 0) { timestamp = featureCursor.getLong(column); } } else { // new feature if (attributes.has(JSON_TEXT_KEY) && !TextUtils.isEmpty(attributes.getString(JSON_TEXT_KEY).trim())) { String defaultValue = attributes.getString(JSON_TEXT_KEY); timestamp = parseDateTime(defaultValue, mPickerType); } if (mIsShowLast) { timestamp = preferences.getLong(mFieldName, timestamp); } } mCalendar.setTimeInMillis(timestamp); setText(mDateFormat.format(mCalendar.getTime())); setSingleLine(true); setFocusable(false); setOnClickListener(getDateUpdateWatcher(mPickerType)); String pattern = mDateFormat.toLocalizedPattern(); setHint(pattern); }
From source file:edu.ucla.stat.SOCR.chart.demo.EventFrequencyDemo1.java
/** * Creates a sample chart./* w w w . ja v a 2 s. co m*/ * * @param dataset a dataset. * * @return A sample chart. */ protected JFreeChart createChart(CategoryDataset dataset) { JFreeChart chart = ChartFactory.createBarChart(chartTitle, // title domainLabel, // domain axis label rangeLabel, // range axis label dataset, // dataset PlotOrientation.HORIZONTAL, // orientation !legendPanelOn, // include legend true, // tooltips false // URLs ); chart.setBackgroundPaint(new Color(0xFF, 0xFF, 0xCC)); // get a reference to the plot for further customisation... CategoryPlot plot = chart.getCategoryPlot(); plot.getDomainAxis().setMaximumCategoryLabelWidthRatio(10.0f); plot.setRangeAxis(new DateAxis("Date")); CategoryToolTipGenerator toolTipGenerator = new StandardCategoryToolTipGenerator("", DateFormat.getDateInstance()); LineAndShapeRenderer renderer = new LineAndShapeRenderer(false, true); renderer.setBaseToolTipGenerator(toolTipGenerator); plot.setRenderer(renderer); // setCategorySummary(dataset); time return chart; }
From source file:com.mobileman.projecth.business.patient.PatientQuestionAnswerServiceTest.java
/** * @throws Exception//from w w w . j a va2 s . com */ @Test public void saveFileEntryAnswer() throws Exception { DateFormat dirNameDateFormat = new SimpleDateFormat("yyyy_MM"); DateFormat fileNameDateFormat = new SimpleDateFormat("hh_mm_ss"); Disease psoriasis = diseaseService.findByCode(DiseaseCodes.PSORIASIS_CODE); List<Haq> haqs = haqService.findByDisease(psoriasis.getId()); Haq haq1 = haqs.get(0); assertEquals(1, haq1.getQuestions().size()); Question question = haq1.getQuestions().get(0); Answer noAnswer = question.getQuestionType().getAnswers().get(0); assertFalse(noAnswer.isActive()); Answer fileAnswer = question.getQuestionType().getAnswers().get(1); assertTrue(fileAnswer.isActive()); User patient = userService.findUserByLogin("sysuser1"); assertNotNull(patient); DateFormat dateFormat = DateFormat.getDateInstance(); Date logDate = dateFormat.parse("1.1.2011"); File tmpFile = File.createTempFile("projecth", ".test"); configurationService.setImagesRootDirectoryPath(tmpFile.getParent()); int count = patientQuestionAnswerService.findAll().size(); patientQuestionAnswerService.saveAnswer(patient.getId(), question.getId(), noAnswer.getId(), tmpFile.getPath(), logDate); List<PatientQuestionAnswer> answers = patientQuestionAnswerService.findAll(); assertEquals(count + 1, answers.size()); assertEquals(null, answers.get(answers.size() - 1).getCustomAnswer()); /////////////// POSITIVE patientQuestionAnswerService.saveAnswer(patient.getId(), question.getId(), fileAnswer.getId(), tmpFile.getPath(), logDate); answers = patientQuestionAnswerService.findAll(); assertEquals(count + 2, answers.size()); assertEquals( patient.getId() + File.separator + psoriasis.getId() + File.separator + dirNameDateFormat.format(new Date()) + File.separator + fileNameDateFormat.format(new Date()) + ".test", answers.get(answers.size() - 1).getCustomAnswer()); }
From source file:com.jgoodies.validation.tutorial.formatted.DateExample.java
/** * Builds and returns a panel with a header row and the sample rows. * /*ww w . j a v a 2 s . c o m*/ * @return the example panel with a header and the sample rows */ public JComponent buildPanel() { FormLayout layout = new FormLayout("r:max(80dlu;pref), 4dlu, 45dlu, 1dlu, pref, 4dlu, pref, 0:grow"); DefaultFormBuilder builder = new DefaultFormBuilder(layout); builder.setDefaultDialogBorder(); builder.getPanel().setFocusTraversalPolicy(MyFocusTraversalPolicy.INSTANCE); Utils.appendTitleRow(builder, "Description"); List fields = appendDemoRows(builder); String validText = DateFormat.getDateInstance().format(new Date(67, 11, 5)); String invalidText = "aa" + validText; Utils.appendButtonBar(builder, fields, validText, invalidText); return builder.getPanel(); }
From source file:com.gaba.alex.trafficincidents.Adapter.IncidentsAdapter.java
@Override public void bindView(View view, final Context context, Cursor cursor) { super.bindView(view, context, cursor); final int type = cursor.getInt(cursor.getColumnIndexOrThrow(IncidentsColumns.TYPE)); final int severity = cursor.getInt(cursor.getColumnIndexOrThrow(IncidentsColumns.SEVERITY)); final double lat = cursor.getDouble(cursor.getColumnIndexOrThrow(IncidentsColumns.LAT)); final double lng = cursor.getDouble(cursor.getColumnIndexOrThrow(IncidentsColumns.LNG)); final double toLat = cursor.getDouble(cursor.getColumnIndexOrThrow(IncidentsColumns.TO_LAT)); final double toLng = cursor.getDouble(cursor.getColumnIndexOrThrow(IncidentsColumns.TO_LNG)); final long dateInMillis = Long .parseLong(cursor.getString(cursor.getColumnIndexOrThrow(IncidentsColumns.END_DATE))); final boolean roadClosed = Boolean .valueOf(cursor.getString(cursor.getColumnIndexOrThrow(IncidentsColumns.ROAD_CLOSED))); final String description = cursor.getString(cursor.getColumnIndexOrThrow(IncidentsColumns.DESCRIPTION)); TextView typeTextView = (TextView) view.findViewById(R.id.incident_type); if (typeTextView != null) { typeTextView.setText(Utility.getIncidentType(mContext, type)); }/* w w w .ja v a 2 s . co m*/ TextView severityTextView = (TextView) view.findViewById(R.id.incident_severity); if (severityTextView != null) { severityTextView.setText(Utility.getIncidentSeverity(mContext, severity)); severityTextView.setTextColor(ContextCompat.getColor(mContext, Utility.getIncidentColor(severity))); } TextView roadClosedTextView = (TextView) view.findViewById(R.id.incident_road_closed); if (roadClosedTextView != null) { roadClosedTextView.setText(String.format("%s: ", mContext.getString(R.string.road_closed))); } TextView roadClosedContentTextView = (TextView) view.findViewById(R.id.incident_road_closed_content); if (roadClosedContentTextView != null) { roadClosedContentTextView .setText(roadClosed ? mContext.getString(R.string.yes) : mContext.getString(R.string.no)); roadClosedContentTextView.setTextColor(ContextCompat.getColor(mContext, roadClosed ? android.R.color.holo_red_light : android.R.color.holo_green_dark)); } TextView dateTextView = (TextView) view.findViewById(R.id.incident_end_date); if (dateTextView != null) { dateTextView.setText(String.format("%s: ", mContext.getString(R.string.estimated_end_date))); } TextView dateContentTextView = (TextView) view.findViewById(R.id.incident_end_date_content); if (dateContentTextView != null) { dateContentTextView.setText(DateFormat.getDateInstance().format(new Date(dateInMillis))); } TextView descriptionTextView = (TextView) view.findViewById(R.id.incident_description); if (descriptionTextView != null) { descriptionTextView.setText(String.format("%s: ", mContext.getString(R.string.local_description))); } TextView descriptionContentTextView = (TextView) view.findViewById(R.id.incident_description_content); if (descriptionContentTextView != null) { descriptionContentTextView.setText(description); } ImageView showOnMapImageView = (ImageView) view.findViewById(R.id.show_on_map_button); showOnMapImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = Utility.buildShowOnMapIntent(mContext, lat, lng, toLat, toLng, severity, description); if (intent.resolveActivity(mContext.getPackageManager()) != null) { mContext.startActivity(intent); } } }); ImageView shareImageView = (ImageView) view.findViewById(R.id.share_button); shareImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); String shareText = Utility.getIncidentType(mContext, type) + "\n\n" + mContext.getString(R.string.local_description) + ": " + description + "\n\n" + mContext.getString(R.string.severity) + ": " + Utility.getIncidentSeverity(mContext, severity) + "\n\n" + mContext.getString(R.string.road_closed) + ": " + (roadClosed ? mContext.getString(R.string.yes) : mContext.getString(R.string.no)) + "\n\n" + mContext.getString(R.string.provided_by) + ": " + mContext.getString(R.string.app_name); intent.putExtra(Intent.EXTRA_TEXT, shareText); if (intent.resolveActivity(mContext.getPackageManager()) != null) { mContext.startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } } }); }
From source file:org.jfree.chart.demo.EventFrequencyDemo.java
/** * Creates a new demo./*from w w w. j a v a2 s . co m*/ * * @param title the frame title. */ public EventFrequencyDemo(final String title) { super(title); // create a dataset... final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // initialise the data... final Day d1 = new Day(12, SerialDate.JUNE, 2002); final Day d2 = new Day(14, SerialDate.JUNE, 2002); final Day d3 = new Day(15, SerialDate.JUNE, 2002); final Day d4 = new Day(10, SerialDate.JULY, 2002); final Day d5 = new Day(20, SerialDate.JULY, 2002); final Day d6 = new Day(22, SerialDate.AUGUST, 2002); dataset.setValue(new Long(d1.getMiddleMillisecond()), "Series 1", "Requirement 1"); dataset.setValue(new Long(d1.getMiddleMillisecond()), "Series 1", "Requirement 2"); dataset.setValue(new Long(d2.getMiddleMillisecond()), "Series 1", "Requirement 3"); dataset.setValue(new Long(d3.getMiddleMillisecond()), "Series 2", "Requirement 1"); dataset.setValue(new Long(d4.getMiddleMillisecond()), "Series 2", "Requirement 3"); dataset.setValue(new Long(d5.getMiddleMillisecond()), "Series 3", "Requirement 2"); dataset.setValue(new Long(d6.getMiddleMillisecond()), "Series 1", "Requirement 4"); // create the chart... final JFreeChart chart = ChartFactory.createBarChart("Event Frequency Demo", // title "Category", // domain axis label "Value", // range axis label dataset, // dataset PlotOrientation.HORIZONTAL, // orientation true, // include legend true, // tooltips false // URLs ); // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART... // set the background color for the chart... chart.setBackgroundPaint(new Color(0xFF, 0xFF, 0xCC)); // final StandardLegend legend = (StandardLegend) chart.getLegend(); // legend.setDisplaySeriesShapes(true); // get a reference to the plot for further customisation... final CategoryPlot plot = chart.getCategoryPlot(); // plot.getDomainAxis().setMaxCategoryLabelWidthRatio(10.0f); plot.setRangeAxis(new DateAxis("Date")); final CategoryToolTipGenerator toolTipGenerator = new StandardCategoryToolTipGenerator("", DateFormat.getDateInstance()); // final CategoryItemRenderer renderer = new LineAndShapeRenderer(LineAndShapeRenderer.SHAPES); // renderer.setToolTipGenerator(toolTipGenerator); // plot.setRenderer(renderer); // **************************************************************************** // * JFREECHART DEVELOPER GUIDE * // * The JFreeChart Developer Guide, written by David Gilbert, is available * // * to purchase from Object Refinery Limited: * // * * // * http://www.object-refinery.com/jfreechart/guide.html * // * * // * Sales are used to provide funding for the JFreeChart project - please * // * support us so that we can continue developing free software. * // **************************************************************************** // OPTIONAL CUSTOMISATION COMPLETED. // add the chart to a panel... final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(chartPanel); }
From source file:com.jgoodies.validation.tutorial.formatted.DateExample.java
/** * Appends the demo rows to the given builder and returns the List of * formatted text fields./*from www. j ava2s. co m*/ * * @param builder the builder used to add components to * @return the List of formatted text fields */ private List appendDemoRows(DefaultFormBuilder builder) { // The Formatter is choosen by the initial value. JFormattedTextField defaultDateField = new JFormattedTextField(new Date()); // The Formatter is choosen by the given Format. JFormattedTextField noInitialValueField = new JFormattedTextField(DateFormat.getDateInstance()); // Uses a custom DateFormat. DateFormat customFormat = DateFormat.getDateInstance(DateFormat.SHORT); JFormattedTextField customFormatField = new JFormattedTextField(new DateFormatter(customFormat)); // Uses a RelativeDateFormat. DateFormat relativeFormat = new RelativeDateFormat(); JFormattedTextField relativeFormatField = new JFormattedTextField(new DateFormatter(relativeFormat)); // Uses a custom DateFormatter that allows relative input and // prints natural language strings. JFormattedTextField relativeFormatterField = new JFormattedTextField(new RelativeDateFormatter()); // Uses a custom FormatterFactory that used different formatters // for the display and while editing. DefaultFormatterFactory formatterFactory = new DefaultFormatterFactory( new RelativeDateFormatter(false, true), new RelativeDateFormatter(true, true)); JFormattedTextField relativeFactoryField = new JFormattedTextField(formatterFactory); // Wraps a DateFormatter to map empty strings to null and vice versa. JFormattedTextField numberOrNullField = new JFormattedTextField(new EmptyDateFormatter()); // Wraps a DateFormatter to map empty strings to -1 and vice versa. Date epoch = new Date(0); // January 1, 1970 JFormattedTextField numberOrEmptyValueField = new JFormattedTextField(new EmptyDateFormatter(epoch)); numberOrEmptyValueField.setValue(epoch); // Commits value on valid edit text DefaultFormatter formatter = new RelativeDateFormatter(); formatter.setCommitsOnValidEdit(true); JFormattedTextField commitOnValidEditField = new JFormattedTextField(formatter); // A date field as created by the BasicComponentFactory: // Uses relative date input, and maps empty strings to null. ValueModel dateHolder = new ValueHolder(); JFormattedTextField componentFactoryField = ExampleComponentFactory.createDateField(dateHolder); Format displayFormat = new DisplayFormat(DateFormat.getDateInstance()); List fields = new LinkedList(); fields.add(Utils.appendRow(builder, "Default", defaultDateField, displayFormat)); fields.add(Utils.appendRow(builder, "No initial value", noInitialValueField, displayFormat)); fields.add(Utils.appendRow(builder, "Empty <-> null", numberOrNullField, displayFormat)); fields.add(Utils.appendRow(builder, "Empty <-> epoch", numberOrEmptyValueField, displayFormat)); fields.add(Utils.appendRow(builder, "Short format", customFormatField, displayFormat)); fields.add(Utils.appendRow(builder, "Relative format", relativeFormatField, displayFormat)); fields.add(Utils.appendRow(builder, "Relative formatter", relativeFormatterField, displayFormat)); fields.add(Utils.appendRow(builder, "Relative factory", relativeFactoryField, displayFormat)); fields.add(Utils.appendRow(builder, "Commits on valid edit", commitOnValidEditField, displayFormat)); fields.add(Utils.appendRow(builder, "Relative, maps null", componentFactoryField, displayFormat)); return fields; }
From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabaseTester.java
License:asdf
@SuppressWarnings("unchecked") @Test//www. j av a 2 s . co m // FIXME: Split test up. public void testAll() throws Exception { LogbackRecorder lr = LogbackRecorder.startRecorder(); Date beforeTest = new Date(Calendar.getInstance().getTimeInMillis()); assertTrue("The database should be empty to begin with.", cache.isEmpty()); // try handling output from ChecksumJob. File csFile = makeTemporaryChecksumFile1(); cache.addChecksumInformation(csFile, Replica.getReplicaFromId("ONE")); // try handling output from FilelistJob. File flFile = makeTemporaryFilelistFile(); cache.addFileListInformation(flFile, Replica.getReplicaFromId("TWO")); Date dbDate = cache.getDateOfLastMissingFilesUpdate(Replica.getReplicaFromId("TWO")); Date afterInsert = new Date(Calendar.getInstance().getTimeInMillis()); // Assert that the time of insert is between the start of this test // and now. String stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be after the test was begun. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be after '" + DateFormat.getDateInstance().format(beforeTest) + "'."; assertTrue(stepMessage, dbDate.after(beforeTest)); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be before " + "the current time. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be before '" + DateFormat.getDateInstance().format(afterInsert) + "'."; assertTrue(stepMessage, dbDate.before(afterInsert)); // Check that getDateOfLastWrongFilesUpdate gives a date between // the start of this test and now. dbDate = cache.getDateOfLastWrongFilesUpdate(Replica.getReplicaFromId("ONE")); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be after " + "the test was begun. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be after '" + DateFormat.getDateInstance().format(beforeTest) + "'."; assertTrue(stepMessage, dbDate.after(beforeTest)); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be before " + "the current time. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be before '" + DateFormat.getDateInstance().format(afterInsert) + "'."; assertTrue(stepMessage, dbDate.before(afterInsert)); // retrieve empty file and set all files in replica 'THREE' to missing File fl2File = makeTemporaryEmptyFilelistFile(); cache.addFileListInformation(fl2File, Replica.getReplicaFromId("THREE")); // check that all files are unknown for the uninitialised replica. long files = FileUtils.countLines(csFile); assertEquals("All the files for replica 'THREE' should be missing.", files, cache.getNumberOfMissingFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); // check that the getMissingFilesInLastUpdate works appropriately. //List<String> misFiles = toArrayList(cache.getMissingFilesInLastUpdate( List<String> misFiles = IteratorUtils .toList(cache.getMissingFilesInLastUpdate(Replica.getReplicaFromId("THREE")).iterator()); List<String> allFilenames = new ArrayList<String>(); for (String entry : FileUtils.readListFromFile(csFile)) { String[] e = entry.split("##"); allFilenames.add(e[0]); } assertEquals("All the files should be missing for replica 'THREE': " + misFiles + " == " + allFilenames, misFiles, allFilenames); // adding the checksum for the other replicas. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("TWO")); // check that when a replica is given wrong checksums it will be // found by the update method. assertEquals("Replica 'THREE' has not been assigned checksums yet." + " Therefore not corrupt files yet!", 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("No files has been assigned to replica 'THREE' yet.", 0, cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); File csFile2 = makeTemporaryChecksumFile2(); cache.addChecksumInformation(csFile2, Replica.getReplicaFromId("THREE")); stepMessage = "All the files in Replica 'THREE' has been assigned checksums, but not checksum update has been run yet. " + "Therefore no corrupt files yet!"; assertEquals(stepMessage, 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("Entries for replica 'THREE' has should be assigned.", FileUtils.countLines(csFile2), cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); cache.updateChecksumStatus(); assertEquals("After update all the entries for replica 'THREE', " + "they should all be set to 'CORRUPT'!", FileUtils.countLines(csFile2), cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("All the entries for replica 'THREE' is all corrupt, " + "but they should still be counted.", FileUtils.countLines(csFile2), cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); // Check that all files are wrong for replica 'THREE' //List<String> wrongFiles = toArrayList(cache.getWrongFilesInLastUpdate( List<String> wrongFiles = IteratorUtils .toList(cache.getWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE")).iterator()); assertEquals("All the files should be wrong for replica 'THREE': " + wrongFiles + " == " + allFilenames, wrongFiles, allFilenames); // check that a file can become missing, after it was ok, but still be ok! cache.addFileListInformation(flFile, Replica.getReplicaFromId("ONE")); stepMessage = "Replica 'ONE' had the files '" + allFilenames + "' before updating the filelist with '" + FileUtils.readListFromFile(flFile) + "'. Therefore one " + "file should now be missing."; assertEquals(stepMessage, 1, cache.getNumberOfMissingFilesInLastUpdate(Replica.getReplicaFromId("ONE"))); stepMessage = "Replica 'ONE' is missing 1 file, but since the checksum already is set to 'OK', then it is not CORRUPT"; assertEquals(stepMessage, 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("ONE"))); // set replica THREE to having the same checksum as the other two, // and update. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("THREE")); cache.updateChecksumStatus(); // reset the checksums of replica ONE, thus setting the // 'checksum_status' to UNKNOWN. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("ONE")); // Check that replica 'TWO' is found with good file. stepMessage = "Now only replica 'TWO' and 'THREE' both have checksum_status set to OK, and since replica 'TWO' is the only bitarchive, it should found when searching for replica with good file for the file 'TEST1'."; assertEquals(stepMessage, cache.getBitarchiveWithGoodFile("TEST1"), Replica.getReplicaFromId("TWO")); assertEquals("No bitarchive replica should be returned.", null, cache.getBitarchiveWithGoodFile("TEST1", Replica.getReplicaFromId("TWO"))); cache.changeStateOfReplicafileinfo("TEST1", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_STARTED); cache.changeStateOfReplicafileinfo("TEST2", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_STARTED); cache.changeStateOfReplicafileinfo("TEST1", Replica.getReplicaFromId("ONE"), ReplicaStoreState.UPLOAD_FAILED); Collection<String> names = cache.retrieveFilenamesForReplicaEntries("TWO", ReplicaStoreState.UPLOAD_STARTED); assertTrue("The list of names should contain TEST1", names.contains("TEST1")); assertTrue("The list of names should contain TEST2", names.contains("TEST2")); cache.insertNewFileForUpload("TEST5", "asdfasdf0123"); try { cache.insertNewFileForUpload("TEST5", "01234567890"); fail("It should not be allowed to reupload a file with another checksum."); } catch (IllegalState e) { // expected assertTrue("It should say, the checksum is wrong, but said: " + e.getMessage(), e.getMessage().contains("The file 'TEST5' with checksum 'asdfasdf0123'" + " has attempted being uploaded with the checksum '" + "01234567890" + "'")); } cache.changeStateOfReplicafileinfo("TEST5", "asdffdas0123", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_COMPLETED); cache.changeStateOfReplicafileinfo("TEST5", "fdsafdas0123", Replica.getReplicaFromId("THREE"), ReplicaStoreState.UPLOAD_COMPLETED); try { cache.insertNewFileForUpload("TEST5", "asdfasdf0123"); fail("It should not be allowed to reupload a file when it has been completed."); } catch (IllegalState e) { // expected assertTrue("It should say, that it has already been completely uploaded, but said: " + e.getMessage(), e.getMessage().contains("The file has already been " + "completely uploaded to the replica: ")); } assertNull("No common checksum should be found for file TEST5", cache.getChecksum("TEST5")); cache.changeStateOfReplicafileinfo("TEST5", "fdsafdas0123", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_COMPLETED); assertEquals("The checksum for file 'TEST5' should be fdsafdas0123", "fdsafdas0123", cache.getChecksum("TEST5")); // check content String content = cache.retrieveAsText(); for (String filename : cache.retrieveAllFilenames()) { assertTrue("The filename '" + filename + "' should be in the content", content.contains(filename)); } for (Replica rep : Replica.getKnown()) { assertEquals("Unexpected filelist status", FileListStatus.NO_FILELIST_STATUS, cache.retrieveFileListStatus("TEST5", rep)); } // check for duplicates cache.addFileListInformation(makeTemporaryDuplicateFilelistFile(), Replica.getReplicaFromId("ONE")); boolean stop = true; if (stop) { return; } lr.assertLogContains("Warning about duplicates should be generated", "There have been found multiple files with the name 'TEST1'"); // cleanup afterwards. cache.cleanup(); lr.stopRecorder(); }