Input from text file into linked list and displays in output file, also searched through index for date - linked-list

Trying to get a linked list to read input from a file, put it into a linked list, search for same date, and write back into a file, UserLoginTest cannot be changed
public class User {``
String name;
int id;
String login;
double duration;
public User() {
name="";
id=0;
login="";
duration=0.0;
}
public User(String n,int i, String l, double d) {
n=name;
i=id;
l=login;
d=duration;
}
public void setName(String n) {
name=n;
}
public void setId(int i) {
id=i;
}
public void setLogin(String l) {
login=l;
}
public void setDuration(double d) {
duration =d;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public String getLogin() {
return login;
}
public double getDuration() {
return duration;
}
}
public class Node{
public User data;
Node next;
public Node(User u) {
data=u;
}
public Node(User u, Node n) {
data = u;
next = n;
}
public String toString() {
return data+"";
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class UserLoginTest {
public static void main(String[] args) throws FileNotFoundException {
String searchDate = "Oct 02";
String tempData;
String inputFileName = "Input.txt";
String outputFileName = "Output.txt";
UserLoginLinkedList loginList = generateLoginList(inputFileName);
tempData = "List of users who logged into the system";
//writeData(outputFileName, tempData);
writeData(outputFileName, loginList);
tempData = "List of users who logged into the system on "+searchDate;
//writeData(outputFileName, tempData);
//writeData(outputFileName, loginList.searchDate(searchDate, 0));
}
public static UserLoginLinkedList generateLoginList(String inputFileName) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
String loginList="";
File file = new File(inputFileName);
Scanner sc = new Scanner(file);
UserLoginLinkedList list = new UserLoginLinkedList();
while(sc.hasNextLine()) {
String temp = input.nextLine();
User u = new User(temp, 0, temp, 0);
list.add(u);
}
return list;
}
static void writeData(String inputFileName, UserLoginLinkedList loginList) {
try {
FileWriter f = new FileWriter(inputFileName, true);
PrintWriter p = new PrintWriter(f);
p.print(loginList.toString());
p.close();
}catch(Exception ex) {
}
}
}
public class UserLoginLinkedList{
Node head= null;
Node tail = null;
public void add(User u) {
Node newNode = new Node(u);
newNode.next = head;
head = newNode;
if(tail == null)tail = head;
}
public boolean searchDate(String searchDate,int id) {
Node current = head;
while (current != null) {//
if(current(searchDate) == searchDate)
return true;
current = current.next;
}
return false;
}
public String toString() {
String temp="";
Node current = head;
while (current != null) {
temp+=current.toString();
current = current.next;
}
return temp;
}
}
Input
aaa-123-Thu Oct 28 09:15:44 EDT 2021-22
abc-112-Thu Oct 28 09:20:45 EDT 2021-10
bbb-125-Fri Oct 29 09:15:44 EDT 2021-18
ccc-789-Sat Oct 02 09:15:44 EDT 2021-88
aaa-123-Sat Oct 02 19:15:44 EDT 2021-50
ddd-666-Wed Oct 13 09:15:44 EDT 2021-78
What is expected:
List of users who logged into the system
aaa 123 Thu Oct 28 09:15:44 EDT 2021 22
abc 112 Thu Oct 28 09:20:45 EDT 2021 10
bbb 125 Fri Oct 29 09:15:44 EDT 2021 18
ccc 789 Sat Oct 02 09:15:44 EDT 2021 88
aaa 123 Sat Oct 02 19:15:44 EDT 2021 50
ddd 666 Wed Oct 13 09:15:44 EDT 2021 78
List of users who logged into the system on Oct 02
ccc 789 Sat Oct 02 09:15:44 EDT 2021 88
aaa 123 Sat Oct 02 19:15:44 EDT 2021 50

Related

How to get or sync date & time from the Server IP in c# (back end code)

I won't get or sync date & time from the Server IP in c# (back-end code)
currently, I am getting time and date from the NTP server but I want server time and date form the public Ip.
Here is my code for the getting NTP server time but How to convert this code for getting time & date form server IP.
private static void Main(string[] args)
{
foreach (string server in ListOfNTPServer())
{
DateTime dateTime = GetNetworkTime(server);
Console.WriteLine(dateTime + "----" + server);
}
Console.ReadLine();
}
public static string[] ListOfNTPServer()
{
string[] serverList = {
"time-a-g.nist.gov",
"time-b-g.nist.gov",
"time-c-g.nist.gov",
"time-d-g.nist.gov",
"time-d-g.nist.gov",
"time-a-wwv.nist.gov",
"time-b-wwv.nist.gov",
"time-c-wwv.nist.gov",
"time-d-wwv.nist.gov",
"time-d-wwv.nist.gov",
"time-a-b.nist.gov",
"time-b-b.nist.gov",
"time-c-b.nist.gov",
"time-d-b.nist.gov",
"time-d-b.nist.gov",
"time.nist.gov",
"utcnist.colorado.edu",
"utcnist2.colorado.edu",
"ntp-b.nist.gov",
"ntp-wwv.nist.gov",
"ntp-c.colorado.edu",
"ntp-d.nist.gov",
"ut1-time.colorado.edu"
};
return serverList;
}
public static DateTime GetNetworkTime(string ntpServer)
{
try
{
// const string ntpServer = "time-a-wwv.nist.gov";
byte[] ntpData = new byte[48];
ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
IPAddress[] addresses = Dns.GetHostEntry(ntpServer).AddressList;
IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | ntpData[43];
ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | ntpData[47];
ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
DateTime networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
catch (Exception)
{
return DateTime.Now;
}
}
Thanks in advance.
Also maintain Time Zone of server in server list
class server
{
public string hostname { get; set; }
public double hourdiff { get; set; }
}
List<server> serverList = new List<server>();
serverList.Add(new server { hostname = "time-a-g.nist.gov", hourdiff = 5.5 });// for india time
public static DateTime GetNetworkTime(string ntpServer)
{
.......
server serv = serverList.Where(x => x.hostname == ntpServer).FirstOrDefault();
DateTime servertime = DateTime.UtcNow.AddHours(serv.hourdiff);
........
}

why parse exception Exception in thread "main" java.text.ParseException: Unparseable date: "Thu Jan 24 00:00:00 EET 2018

this programe should subtract 2 days tare3 and tare4. tare3 valued from current day (from system) tare4 value from text file (element[3]), when I parsed string (element[3]) to date (tare4) its give`me parseexception
date saved in file looked like (Thu Jan 24 00:00:00 EET 2018)
package javaapplication3;
import java.io.*; ` `
import java.util.*;
import java.text.*;
public static void main(String[] args) throws ParseException, FileNotFoundException {
private static String tare5 = new String();
static String tare2 = new String ();
DateFormat dateFormat = new SimpleDateFormat(" dd MMM yyyy ",Locale.ENGLISH );
Calendar cal = Calendar.getInstance();
Date tare4 = new Date ();
tare5 = dateFormat.format(cal.getTime());
Date tare3 = dateFormat.parse(tare5);
Scanner scanner;
File Myfile = new File("C:\\Users\\mido\\Documents\\NetBeansProjects\\JavaApplication3\\src\\javaapplication3\\products.txt");
scanner = new Scanner (Myfile);
while (scanner.hasNext()){
String line = scanner.nextLine();
StringTokenizer x = new StringTokenizer(line,"~");
String [] element= new String [7];
int counter = 0 ;
while (x.hasMoreElements())
{
element[counter]=(String)x.nextElement();
counter ++;
}
tare4 = dateFormat.parse(element[3]);
if (tare4.getTime()>= tare3.getTime() )
{
System.out.println(element[1]+"is expired");
}
else {
long def = tare3.getTime()- tare4.getTime();
System.out.println(element[1]+"has"+def+"to expire");}
}
}

Query repo committed files order by commit date

I'd like to be able to have a collection of the files in the repo ordered by their commit date.
File Committed
abc.bat Dec 1 2013
bar.txt Jan 1 2010
baz.cmd Nov 8 2010
cru.zip Feb 9 2012
How can I do this with LibGit2Sharp so that I can order by Commit Date?
The reason I need to do this is that LibGit2Sharp doesn't allow you to .Pull(), thereby merging changes. If that were the case, I'd go about with a System.IO.DirectoryInfo and query by modified date in Windows. It seems we only have .Clone(), which doesn't maintain those dates in the file system.
Hmm. There's nothing out of the box that would fit this need.
However, by walking the revision history backwards and identifying additions and modifications, one could gather the date of the latest change of each file that exist in the commit being examined.
How about this?
public void LetUsTryThis()
{
using (var repo = new Repository(StandardTestRepoPath))
{
var referenceCommit = repo.Head.Tip;
IEnumerable<KeyValuePair<string, DateTimeOffset>> res = LatestChanges(repo, referenceCommit);
foreach (KeyValuePair<string, DateTimeOffset> kvp in res)
{
Console.WriteLine(string.Format("{0} - {1}", kvp.Key, kvp.Value));
}
}
}
private IEnumerable<KeyValuePair<string, DateTimeOffset>> LatestChanges(Repository repo, Commit referenceCommit)
{
IDictionary<string, DateTimeOffset> dic = new Dictionary<string, DateTimeOffset>();
var commitLog = repo.Commits.QueryBy(new CommitFilter { Since = referenceCommit })
.Concat(new[] { default(Commit) })
.Skip(1);
var mostRecent = referenceCommit;
foreach (Commit current in commitLog)
{
IEnumerable<KeyValuePair<string, DateTimeOffset>> res = ExtractAdditionsAndModifications(repo, mostRecent, current);
AddLatest(dic, res);
mostRecent = current;
}
return dic.OrderByDescending(kvp => kvp.Value);
}
private IEnumerable<KeyValuePair<string, DateTimeOffset>> ExtractAdditionsAndModifications(Repository repo, Commit next, Commit current)
{
IDictionary<string, DateTimeOffset> dic = new Dictionary<string, DateTimeOffset>();
var tc = repo.Diff.Compare(current == null ? null : current.Tree, next.Tree);
foreach (TreeEntryChanges treeEntryChanges in tc.Added)
{
dic.Add(treeEntryChanges.Path, next.Committer.When);
}
foreach (TreeEntryChanges treeEntryChanges in tc.Modified)
{
dic.Add(treeEntryChanges.Path, next.Committer.When);
}
return dic;
}
private void AddLatest(IDictionary<string, DateTimeOffset> main, IEnumerable<KeyValuePair<string, DateTimeOffset>> latest)
{
foreach (var kvp in latest)
{
if (main.ContainsKey(kvp.Key))
{
continue;
}
main.Add(kvp);
}
}

AMF ActionResult for asp.net mvc

I'm building a mvc application which will communicate with flash via AMF,
anybody knows if there is any AMF ActionResult available on the web ?
EDIT:
using #mizi_sk answer (but without using IExternalizable) I did this ActionResult:
public class AmfResult : ActionResult
{
private readonly object _o;
public AmfResult(object o)
{
_o = o;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "application/x-amf";
using (var ms = new MemoryStream())
{
// write object
var writer = new AMFWriter(ms);
writer.WriteData(FluorineFx.ObjectEncoding.AMF3, _o);
context.HttpContext.Response.BinaryWrite(ms.ToArray());
}
}
}
but the response handler on the flash side doesn't get hit.
in Charles at the Response->Amf tab I see this error:
Failed to parse data (com.xk72.amf.AMFException: Unsupported AMF3 packet type 17 at 1)
this is the raw tab:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 14 May 2012 15:22:58 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private
Content-Type:application/x-amf
Content-Length: 52
Connection: Close
3/bingo.model.TestRequest param1coins name
and the Hex tab:
00000000 11 0a 33 2f 62 69 6e 67 6f 2e 6d 6f 64 65 6c 2e 3/bingo.model.
00000010 54 65 73 74 52 65 71 75 65 73 74 0d 70 61 72 61 TestRequest para
00000020 6d 31 0b 63 6f 69 6e 73 09 6e 61 6d 65 01 04 00 m1 coins name
00000030 06 05 6a 6f jo
The trick is to use FluorineFx.IO.AMFMessage with AMFBody as a result object and set a Content property.
You can see this in Charles proxy with other working examples (I've used great WebORB examples, specifically Flash remoting Basic Invocation AS3)
I've updated AMFFilter to support Response parameter that AMFBody needs. Maybe it could be solved more elegantly by some current context cache, don't know.
Code follows:
public class AmfResult : ActionResult
{
private readonly object _o;
private readonly string _response;
public AmfResult(string response, object o)
{
_response = response;
_o = o;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "application/x-amf";
var serializer = new AMFSerializer(context.HttpContext.Response.OutputStream);
var amfMessage = new AMFMessage();
var amfBody = new AMFBody();
amfBody.Target = _response + "/onResult";
amfBody.Content = _o;
amfBody.Response = "";
amfMessage.AddBody(amfBody);
serializer.WriteMessage(amfMessage);
}
}
For this to work, you need to decorate method on the controller with AMFFilter
public class AMFFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.ContentType == "application/x-amf")
{
var stream = filterContext.HttpContext.Request.InputStream;
var deserializer = new AMFDeserializer(stream);
var message = deserializer.ReadAMFMessage();
var body = message.Bodies.First();
filterContext.ActionParameters["target"] = body.Target;
filterContext.ActionParameters["args"] = body.Content;
filterContext.ActionParameters["response"] = body.Response;
base.OnActionExecuting(filterContext);
}
}
}
which would look something like this
[AMFFilter]
[HttpPost]
public ActionResult Index(string target, string response, object[] args)
{
// assume target == "TestMethod" and args[0] is a String
var message = Convert.ToString(args[0]);
return new AmfResult(response, "Echo " + message);
}
Client side code for reference
//Connect the NetConnection object
var netConnection: NetConnection = new NetConnection();
netConnection.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
netConnection.connect("http://localhost:27165/Home/Index");
//Invoke a call
var responder : Responder = new Responder( handleRemoteCallResult, handleRemoteCallFault);
netConnection.call('TestMethod', responder, "Test");
private function onNetStatus(event:NetStatusEvent):void {
log(ObjectUtil.toString(event.info));
}
private function handleRemoteCallFault(...args):void {
log(ObjectUtil.toString(args));
}
private function handleRemoteCallResult(message:String):void {
log(message);
}
private static function log(s:String):void {
trace(s);
}
If you would like to return fault, just change this line in AMFResult
amfBody.Target = _response + "/onFault";
I like ObjectUtil.toString() formatting, but just remove it if you don't have Flex linked.
BTW, do you really need this in ASP.NET MVC? Maybe simple ASHX handler would suffice and performance would be better, I don't know. The MVC architecture is a plus I presume.
I haven't seen an ActionResult implemented on the web but there's FluorineFX.NET which supports AMF.
AFAIK there is not any implementation of AMF ActionResult, but you can create your own using class FluorineFx.IO.AMFWriter from FluorineFx.NET sources
Consider creating an opensource project somewhere (for example on github)
EDIT 1 - Sample
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluorineFx.IO;
using System.IO;
using FluorineFx.AMF3;
using System.Diagnostics;
namespace AMF_SerializationTest
{
class Program
{
static void Main(string[] args)
{
var ms = new MemoryStream();
// write object
var writer = new AMFWriter(ms);
writer.WriteData(FluorineFx.ObjectEncoding.AMF3, new CustomObject());
Debug.Assert(ms.Length > 0);
// rewind
ms.Position = 0;
// read object
var reader = new AMFReader(ms);
var o = (CustomObject)reader.ReadData();
// test
Debug.Assert(o.I == 3);
Debug.Assert(o.S == "Hello");
}
}
public class CustomObject : IExternalizable
{
private int i = 3;
public int I
{
get { return i; }
}
private string s = "Hello";
public string S
{
get { return s; }
}
public void ReadExternal(IDataInput input)
{
i = input.ReadInt();
s = input.ReadUTF();
}
public void WriteExternal(IDataOutput output)
{
output.WriteInt(i);
output.WriteUTF(s);
}
}
}

how to convert date from yyyy-MM-dd to dd-MMM-yyyy without using Date function

I have "2011-12-05" and I want to convert this to "Monday 05-Dec-2011".
My date conversion code depends on the device timezone. If my timezone is India, then I get date Monday 05-Dec-2011 and if my timezone is Kingston, Jamaica, I get Sunday 04-Dec-2011.
For this reason my application does not display the correct date for different timezones.
Is there any solution to convert date without Blackberry Date class or using current Date and Time Zone?
I want to only convert this date to String
I am converting this date using below function
public static String reformatMonthDate(String source)
{
SimpleDateFormat write = new SimpleDateFormat("dd MMM yyyy"); //YYYY-MMM-dd
Date date = new Date(HttpDateParser.parse(source));
return write.format(date);
}
You can specify a specific locale, instead of relying on the system's default.
Locale locale = Locale.get(Locale.LOCALE_fr);
// Parse with HttpDateParser
Date date = new Date(HttpDateParser.parse("2002-01-29"));
// Format with a custom format and locale
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
StringBuffer buf = new StringBuffer(30);
String s = formatter.format(date, buf, null).toString(); // mar., 29 janv. 2002
DateTimePicker gives the current date according to the location or device configuration settings.
Try this code:
You should get your requirement.
public class LoadingScreen extends MainScreen implements FieldChangeListener
{
private String select_Date[]={"Select Date"};
private String month_ar[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
private ObjectChoiceField choiceField;
private ButtonField show;
public LoadingScreen()
{
createGUI();
}
private void createGUI()
{
choiceField=new ObjectChoiceField("Select Date: ", select_Date, 0)
{
protected boolean navigationClick(int status, int time)
{
DateTimePicker datePicker = DateTimePicker.createInstance( Calendar.getInstance(), "dd/MM/yyyy",null);
datePicker.doModal();
Calendar cal1=datePicker.getDateTime();
String day="";
String mon="";
if(String.valueOf(cal1.get(Calendar.DAY_OF_MONTH)).length()==1)
{
day="0"+String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
else
{
day=String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
mon=String.valueOf(cal1.get(Calendar.MONTH));
String month=""+month_ar[cal1.get(Calendar.MONTH)];
select_Date[0]=day+"-"+month+"-"+cal1.get(Calendar.YEAR);
choiceField.setChoices(select_Date);
return true;
}
};
add(choiceField);
show=new ButtonField("Show",FIELD_HCENTER);
show.setChangeListener(this);
add(show);
}
public void fieldChanged(Field field, int context)
{
if(field==show)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(select_Date[choiceField.getSelectedIndex()]);
}
});
}
}
public boolean onMenu(int instance)
{
return true;
}
protected boolean onSavePrompt()
{
return true;
}
}

Resources