I hope somebody could please help me out in identifying to where I am going wrong with the codes below.
public class CCFileImpl implements CCFileAbs {
private LogMe logMe = null;
private ExecutorService ccfileimpl_exsc = null;
private CCProcessorImpl cProc = null;
private DataUtil dUtil = null;
public CCFileImpl() {
this.logMe = LogMe.getLogger();
if (dUtil == null) {
dUtil = new DataUtil();
}
}
#Override
public void getFilesForProcess() {
CCHeader cHead = null;
Future future = null;
String sPath = PropReader.getPropValue(PropReader.FILEDIR); //D:\samples\
int iCtr = 0;
ccfileimpl_exsc = Executors.newFixedThreadPool(Integer.parseInt(PropReader.getPropValue(PropReader.TPool_File)));
Date dToday = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Iterator iter = dUtil.getFilesForProcess(sdf.format(dToday)).iterator();
String sFileGroupName = "", sFileName = "";
String sId = null; //"testFiles";
while (iter.hasNext()) {
cHead = (CCHeader) iter.next();
sFileName = cHead.getsFileName(); //(String) iter.next();
sId = cHead.getsId();
sFileGroupName = sFileName + "_" + iCtr++;
dUtil.updTPDHDRStatusById(sId); //Interface utility class // <=== And also here, when trying to update the db
// nothing happened.
cProc = new CCProcessorImpl(sId, sFileGroupName, sPath, sFileName); // <=== Problem is here?
future = ccfileimpl_exsc.submit(cProc);
}
ccfileimpl_exsc.shutdown();
}
}
The above code retrieves the files for processing then assigning it to a runnable class (below) then submitting it to an executorService class.
Now i can't understand to why the passed values of the constructor (below) is set to null/space and only the sPath variable has a definite value.
public class CCProcessorImpl implements Runnable{
private CCFileParser rpsCCParser;
private ExecutorService ccprocimpl_exsc;
private static LogMe logMe;
private final String sGroupName;
private final String sId;
private final String sFileName;
#Override
public void run() {
this.parseFiles(sId, sFileName);
}
public CCProcessorImpl(String sId, String sGroupName, String sPath, String sFileName) {
this.logMe = LogMe.getLogger();
this.sId = sId;
this.sGroupName = sGroupName;
this.sFileName = sPath + sFileName;
}
public void parseFiles(String sId, String sFileName) {
try {
Future future = null;
rpsCCParser = new CCFileParser(sId, sFileName);
ArrayList aList = rpsCCParser.getFileContent();
String sGroupName = sId + "_";
ccprocimpl_exsc = Executors.newFixedThreadPool(Integer.parseInt(PropReader.getPropValue(PropReader.TPool_Content)));
int iStart = 0, iSize = 9, iEnd = iSize;
for (int iCtr = 0; iCtr <= ((aList.size() / 10) - 1); iCtr++, iStart += iSize, iEnd += iSize) {
future = ccprocimpl_exsc.submit(new CCUpdater(aList.subList(iStart, iEnd), sGroupName + iCtr));
}
future.get();
ccprocimpl_exsc.shutdown();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
}
Also as a supplementary question, why is it when i tried to update the db table no updates were performed? Would this be related to being in a thread environment?
Why don't you use the futures returned by ccfileimpl_exsc.submit()?
Instead, you call ccfileimpl_exsc.shutdown() right after submitting the jobs, killing them before they finish.
Related
In my jFrame,I created a table that contains the patients' list and a button that allows to refresh the table on action. When I click the refresh button for the firt time, the list is displayed in the table. Howerver, when I press it for a second time it doesn't work any more and the table isn't able to be refreshed.
Any idea about the problem please?
this is the code of the refresh button:
public class Interface extends javax.swing.JFrame{
private void RefreshActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)worklisttable.getModel();
int rowCount = model.getRowCount();
for (int i = rowCount - 1; i >= 0; i--) {
model.removeRow(i);
}
model.fireTableDataChanged();
GetMwl_3.main(args);
}
public static void main(String args[]) {
......
}
}
GetMwl_3.java : allows to retrieve the patient list from the server
public class GetMwl_3 {
private String[] args;
/**
* #param args
*/
public static void main(String[] args/*,String aet, String host, Integer port*/) {
new GetMwl_3(/*aet,host,port*/);
}
private static final int[] RETURN_KEYS = {
Tag.AccessionNumber,
Tag.ReferringPhysicianName,
Tag.PatientName,
Tag.PatientID,
Tag.PatientBirthDate,
Tag.PatientSex,
Tag.PatientWeight,
Tag.MedicalAlerts,
Tag.Allergies,
Tag.PregnancyStatus,
Tag.StudyInstanceUID,
Tag.RequestingPhysician,
Tag.RequestingService,
Tag.RequestedProcedureDescription,
Tag.AdmissionID,
Tag.SpecialNeeds,
Tag.CurrentPatientLocation,
Tag.PatientState,
Tag.RequestedProcedureID,
Tag.RequestedProcedurePriority,
Tag.PatientTransportArrangements,
Tag.PlacerOrderNumberImagingServiceRequest,
Tag.FillerOrderNumberImagingServiceRequest,
Tag.ConfidentialityConstraintOnPatientDataDescription,
};
private static final int[] SPS_RETURN_KEYS = {
Tag.Modality,
Tag.RequestedContrastAgent,
Tag.ScheduledStationAETitle,
Tag.ScheduledProcedureStepStartDate,
Tag.ScheduledProcedureStepStartTime,
Tag.ScheduledPerformingPhysicianName,
Tag.ScheduledProcedureStepDescription,
Tag.ScheduledProcedureStepID,
Tag.ScheduledStationName,
Tag.ScheduledProcedureStepLocation,
Tag.PreMedication,
Tag.ScheduledProcedureStepStatus
};
private static final String[] LE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian };
private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };
private Device device;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private final NetworkConnection remoteConn = new NetworkConnection();
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private final DicomObject keys = new BasicDicomObject();
private final DicomObject spsKeys = new BasicDicomObject();
private Association assoc;
private int priority = 0;
private int cancelAfter = Integer.MAX_VALUE;//ÐœÐ°ÐºÑ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑтво Ñтрок
private boolean fuzzySemanticPersonNameMatching;
private Component emptyLabel;
public GetMwl_3(/*String aet, String host, Integer port*/) {
String name = "DCMMWL";
device = new Device(name);
NewThreadExecutor executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAETitle(name);
for (int i = 0; i < RETURN_KEYS.length; i++) {
keys.putNull(RETURN_KEYS[i], null);
}
keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
new BasicDicomObject());
keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
spsKeys.putNull(SPS_RETURN_KEYS[i], null);
}
spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
new BasicDicomObject());
/////////
Properties pacs = new Properties();
InputStream file = null;
File thefile = new File("C:\\properties\\save.properties");
if (thefile.exists()){
try {
file = new FileInputStream("C:\\properties\\save.properties");
// load a properties file
pacs.load(file);
// get the property value and print it out
remoteAE.setAETitle( pacs.getProperty("aethl7"));
remoteConn.setHostname(pacs.getProperty("hosthl7"));
remoteConn.setPort(Integer.parseInt(pacs.getProperty("porthl7")));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,"20131030");
setTransferSyntax(LE_TS);
long t1 = System.currentTimeMillis();
try {
assoc = ae.connect(remoteAE, executor);
} catch (Exception e) {
// System.err.println("ERROR: Failed to establish association:");
//e.printStackTrace(System.err);
//jLabel7.setText("ERROR: Failed to establish association");
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients ne peut pas être retirée");
//System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
//jLabel6.setText("Connected to " + remoteAE + " in "
// + ((t2 - t1) / 1000F) + "s");
try {
List<DicomObject> result = query();
long t3 = System.currentTimeMillis();
System.out.println("Received " + result.size()
+ " matching entries in " + ((t3 - t2) / 1000F) + "s");
for(DicomObject dcm : result) {
worklist.main(args,
dcm.getString(Tag.PatientID),
dcm.getString(Tag.AccessionNumber),
dcm.getString(Tag.PatientName),
dcm.getString(Tag.PatientBirthDate),
dcm.getString(Tag.PatientSex),
dcm.getString(Tag.ReferringPhysicianName)
);
}
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients retirée avec succée");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assoc.release(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Released connection to " + remoteAE);
}
}
public void setTransferSyntax(String[] ts) {
TransferCapability tc = new TransferCapability(
UID.ModalityWorklistInformationModelFIND, ts,
TransferCapability.SCU);
if (fuzzySemanticPersonNameMatching)
tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
ae.setTransferCapability(new TransferCapability[]{tc});
}
public void addSpsMatchingKey(int tag, String value) {
spsKeys.putString(tag, null, value);
}
public List<DicomObject> query() throws IOException, InterruptedException {
TransferCapability tc = assoc.getTransferCapabilityAsSCU(
UID.ModalityWorklistInformationModelFIND);
if (tc == null) {
throw new NoPresentationContextException(
"Modality Worklist not supported by "
+ remoteAE.getAETitle());
}
DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
priority, keys, tc.getTransferSyntax()[0], cancelAfter);
List<DicomObject> result = new ArrayList<DicomObject>();
while (rsp.next()) {
DicomObject cmd = rsp.getCommand();
if (CommandUtils.isPending(cmd)) {
DicomObject data = rsp.getDataset();
result.add(data);
}
}
return result;
}
}
worklist.java :
public class worklist extends Interface{
public worklist(){
}
public static void main(String[] args,
String PatientID,
String accessingNumber,
String PatientName,
String BirthDate,
String sex,
String referringPhysician
) {
DefaultTableModel modelw=(DefaultTableModel)worklisttable.getModel();
modelw.setColumnIdentifiers(new String[]{"ID Patient"," Nom Patient","Date de Naissance","Sexe"});
DefaultTableCellRenderer centerRenderer= new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
worklisttable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int j = 0 ; j< worklisttable.getColumnCount(); j++)
{
worklisttable.getColumnModel().getColumn(j).setCellRenderer(centerRenderer);
}
row=new Object[4];
row[0]=PatientID;
row[1]=PatientName;
row[2]=BirthDate;
row[3]=sex;
modelw.addRow(row);
}
}
Hi i am struggling to get my database to receive a username and ip address from a client instance connecting to a server.
It is a bidding system that initially just lets multiple individual instances of the client bid on 2 items, now I need to add the name (user prompted to enter upon loading client instance) and their ip address to my database.
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null; //null pointer exception fix
Statement statement = null;
String inserSql = null;
Connection sqlLink = null;
final int PORT = 1239;
Socket client = null;
ClientHandler handler = null;
Scanner getTime;
try {
/**
* This piece of code has errors or you maybe did the error
* when copy/paste your code.
* Fixed the DriverManager connection code
*/
sqlLink = DriverManager.getConnection(
"correct info already here);
} catch (SQLException e) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ioEx) {
System.out.println("Unable to set up port!");
System.exit(1);
}
System.out.println("\nUp and running\n");
String currentTime = null;
getTime = new Scanner(System.in);
System.out.println("\nSet time for Ball");
currentTime = getTime.nextLine();
Items BallItem = new Items("Ball", currentTime, "Ball");
System.out.println("\nSet time for Plate");
currentTime = getTime.nextLine();
Items PlateItem = new Items("Plate", currentTime, "Plate");
Bidder bidder = new Bidder(null);
BallItem.start();
PlateItem.start();
Users user = new Users(BallItem, PlateItem);
ArrayList<ClientHandler> userList =
new ArrayList<ClientHandler>();
//add new array for the clients details as stated
ArrayList<String> bidders = new ArrayList<String>();
do {
client = serverSocket.accept();//
System.out.println("Enter username ");//
//takes in bidders name (1.1 and 2.1)
bidders.add(getTime.nextLine());
bidders.add(client.getInetAddress().toString());
//takes in next bidder's ip address to string like in tips (2.2)
Bidder userBidding = new Bidder(bidders);
System.out.println("\nUser" + (user.getUsers() + 1));
user.addUsers(userList, client, handler);
System.out.println(userBidding.returnUsers());
bidder.insert(statement, statement);
}
while (true);
}
}
class Items extends Thread {
private String name, description, timeUp, userBidding = "";
private boolean newBid = true;
private double topBid = 0;
private Calendar start = Calendar.getInstance();
private int date = start.get(Calendar.DATE); //gets the dates
private int month = start.get(Calendar.MONTH);
private int year = start.get(Calendar.YEAR);
private Calendar deadline = Calendar.getInstance();
//time file supplied to help etc
private Calendar now = Calendar.getInstance();
public Items(String newName, String newTimeString,
String newDescription) throws IOException {
String timeString, hourString, minString;
name = newName;
description = newDescription;
timeUp = newTimeString;
timeString = newTimeString;
hourString = timeString.substring(0, 2);
int hour = Integer.parseInt(hourString);
minString = timeString.substring(3, 5);
int minute = Integer.parseInt(minString);
deadline.set(year, month, date, hour, minute, 0); //setting time
}
public void run() {
while (now.before(deadline)) {
System.out.println(name + " " + getDateTime(now));
try {
Thread.sleep(5000); //increased to check server notifications easier
} catch (InterruptedException intEx) {
}
now = Calendar.getInstance();
}
System.out.println("\nDeadline! Times up!");
newBid = false;
}
class Bidder {
private static ArrayList<String> users;
private static Users user = new Users(null, null);
public Bidder(ArrayList<String> newUserList) {
users = newUserList;
}
public ArrayList<String> returnUsers()//return users as in question
{
return users;
}
public static String returnIP()//return ip as in question
{
return users.get(user.getUsers() + 1);
}
static void insert(Statement insert, Statement statement) {
Users user = new Users(null, null);
try {
String insertSql = "INSERT INTO Usernames(id, Name, ipAddress) VALUES (1"
+ users.get(user.getUsers()) + "," + returnIP() + ")";
System.out.println(users.get(user.getUsers()));
statement.executeUpdate(insertSql);
} catch (SQLException sqlEx) {
System.out.println("* Cannot execute insert! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
//remove user as stated in question
public synchronized void RemoveUser(Socket client, int clientUser) {
int index = 0;
for (final String newString : users) {
if (users.indexOf(user.getUsers()) == clientUser) {
try {
client.close();
Thread.currentThread().isInterrupted();
users.remove(index);
} catch (final IOException e) {
System.out.println("Try to leave again!");
System.exit(1);
}
}
index++;
}
}
}
class Users {
private ArrayList<ClientHandler> userList;
private Items Ball;
private Items Plate;
public Users(Items newItem1, Items newItem2) {
Ball = newItem1;
Plate = newItem2;
userList = null;
}
public synchronized int getUsers() {
int totalUsers = 0;
if (userList != null)
for (ClientHandler handler : userList)
totalUsers++;
return totalUsers;
}
}// <-- miss this close brace
I am trying to implement paging in an already running application, it works like mongodb where you get a query with bunch of parameters like
searchConditions ,limit( how many docs you want), skip ( skip these many docs)
and so on
and the response is back in json my task is to generate the previous and next link to the query that means previous page and the next page as per query
I came up with a method below
public Paging generateLink(RequestFilter filter) {
int prev_skip;
int prev_limit;
String pagePrev = "";
String pageNext = "";
int next_skip;
int next_limit;
String searchCondition = JsonUtils.toSimpleJsonString(filter.getSearch());
String url = "http://isgswmdi1n1.nam.nsroot.net:7014/account-search/rest/api/v1/pmm";
//properties.getProperty("paging.link");
System.out.println(url);
Paging pagingOption = new Paging();
Result result = new Result();
int count = luceneSearchService.searchCount(filter);
try {
if (count > 1) {
if (filter.getSkip() > 0) {
prev_skip = Math.max((filter.getSkip() - 1), 0);
prev_limit = filter.getLimit();
pagePrev = url + "?search=" + searchCondition + "&skip=" + prev_skip + "$limit=" + prev_limit;
} else{
result.setPaging(null);
return null;
}
if (count > (filter.getLimit() + filter.getSkip())) {
next_skip = (filter.getSkip() + filter.getLimit());
next_limit = filter.getLimit();
pageNext = url + "?search=" + searchCondition + "&skip=" + next_skip + "$limit=" + next_limit;
} else{
result.setPaging(null);
return null;
}
pagingOption.setPagePrev(pagePrev);
pagingOption.setPageNext(pageNext);
result.setPaging(pagingOption);
}
return pagingOption;
} catch (NullPointerException n)
{
n.printStackTrace();
return pagingOption;
}
}
call to generateLink method
return Result.ok(resultRow, generateLink(filter));
the ok response method in the Result class
public static Result ok(List<ResultRow> resultRows, Paging paging) {
if (paging != null) {
return new Result(resultRows, 200, "Completed", paging);
} else
return new Result(resultRows, 200, "Completed");
}
Underlying paging class
public class Paging implements Serializable {
public String getPagePrev() {
return pagePrev;
}
public void setPagePrev(String pagePrev) {
this.pagePrev = pagePrev;
}
#JsonProperty("pagePrev")
private String pagePrev;
public String getPageNext() {
return pageNext;
}
public void setPageNext(String pageNext) {
this.pageNext = pageNext;
}
#JsonProperty("pageNext")
private String pageNext;
}
but my test method is failing
#Test
public void search_allFilterParamsAreDefined_hp() throws Exception {
// given
Map<String, Serializable> searchConditions = singletonMap("shortName", "GO");
List<String> returnFields = asList("shortname", "gfcid");
String returnFieldsStr = returnFields.stream().collect(joining(","));
RequestFilter filter = RequestFilter.create(searchConditions, returnFieldsStr, 5, 10, true);
int resultSize = 20;
List<ResultRow> searchResult = getSearchResult(resultSize);
when(luceneSearchService.search(filter)).thenReturn(searchResult);
when(luceneSearchService.searchCount(filter)).thenReturn(resultSize);
// do
Result result = searchCoordinator.search(filter);
// verify
assertEquals(searchResult, result.getRows());
assertReturnFields(returnFields, result.getRows());
assertNotNull(result.getPaging());
Map<String, String> nextParams = getQueryParams(result.getPaging().getPageNext());
assertParam(nextParams, "search", toSimpleJsonString(searchConditions));
assertParam(nextParams, "skip", "15");
assertParam(nextParams, "limit", "10");
}
Okay so I get an access token for Twitter each time I run my program...(It's tedious at the moment but I will find out how to make it a persistent store)... How do I go about using this access token so that when I search, I won't get a
"Rate limit exceeded. Clients may not make more than 150 requests per hour."
error?
It happens when I'm searching for the following: "https://api.twitter.com/1/users/show.json?screen_name=[screenName]"
Which is coded as :
BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));
In my code below:
public class UDC {
private static String term1;
private static String term2;
public static String PIN;
private static final String twitterSearch = "http://search.twitter.com/search.json?q=%23";
private static String rppPage = "&rpp=500&page=1";
private static final String ffGet = "https://api.twitter.com/1/users/show.json?screen_name=";
private static final String CONSUMER_KEY = "K7el7Fqu7UtcJv3A3ssOQ";
private static final String CONSUMER_SECRET = "w7ZX27ys58mafLYeivuA2POVe0gjhTIIUH26f2IM";
private static String entities = "&include_entities=true";
static Object[][] tableData = new Object[500][6];
static SearchResultC s = new SearchResultC();
static StringBuffer buff = new StringBuffer();
static StringBuffer buff1 = new StringBuffer();
public static void main (String args[]) throws Exception{
verifyURL v = new verifyURL();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null; // = loadAccessToken(Integer.parseInt(args[0]));
//Twitter twitter = factory.getInstance);
//twitter.setOAuthConsumerKey(COMSUMER_KEY, COMSUMER_SECRET);
//twitter.setOAuthAccessToken(accessToken);
v.valURLText.setText(requestToken.getAuthorizationURL());
v.vFrame.setVisible(true);
int p = 0;
do {
//nothing
} while (v.vFrame.isVisible());
try {
if (PIN.length() > 0) {
accessToken = twitter.getOAuthAccessToken(requestToken, PIN);
} else {
accessToken = twitter.getOAuthAccessToken();
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()) {
showErrorPane("Unable to get access code", "Error");
p = 1;
} else {
te.printStackTrace();
}
}
//storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
if (p == 0) {
initComponents();
UDTFrame.setVisible(true);
} else {
System.exit(0);
}
}
#SuppressWarnings({ "static-access"})
private static void searchButtonMouseClicked(String t1, String t2) throws IOException {
if(t1.equals("") || t2.equals("") || t1.equals(t2))
{
showErrorPane("Invalid Search Terms", "Search Error");
}
else
{
s.getInitComponents();
clicked(t1, 0);
clicked(t2, 3);
s.SRTFrame.setVisible(true);
s.sTerm1Field.setText(t1);
s.sTerm2Field.setText(t2);
}
}
#SuppressWarnings("static-access")
public static void clicked(String term, int t){
UDTFrame.setVisible(false);
float follower;
float friends;
float ffRatio;
float DUA;
int statuses;
int day;
int year;
String month;
try {
URL searchURL1 = new URL (twitterSearch + term + rppPage);
//String searchURL = new String (twitterSearch + term + rppPage);
BufferedReader br = new BufferedReader( new InputStreamReader(searchURL1.openConnection().getInputStream()));
//OAuthRequest request = new OAuthRequest(Verb.POST, searchURL);
int c;
while ((c=br.read()) != -1) {
buff.append((char)c);
}
br.close();
/*******************************************************************************************/
/*******************************************************************************************/
/******************************** follower/friend ratio ************************************/
/*******************************************************************************************/
/*******************************************************************************************/
JSONObject js = new JSONObject(buff.toString());
JSONArray tweets = js.getJSONArray("results");
JSONObject tweet = new JSONObject();
for(int i=0; i < tweets.length(); i++) {
tweet = tweets.getJSONObject(i);
//System.out.println(tweet);
//user[i] = tweet.getString("from_user_name");
//System.out.println(tweet.getString("from_user_name"));
//System.out.println(user[i]);
String userName = tweet.getString("from_user");
//URL ffUser = new URL(ffGet + user[i] + entities);
URL ffUser = new URL(ffGet + userName + entities);
String ffUser1 = new String(ffGet + userName + entities);
BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));
OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);
int d, e = 0;
while((d = ff.read()) != -1) {
buff1.append((char)d);
e++;
}
ff.close();
JSONObject js1 = new JSONObject(buff1.toString());
//System.out.println(js1);
//JSONArray userData = new JSONArray(buff1.toString());
//JSONObject userData1;
//for(int j = 0; j < js1.length(); i++){
//userData1 = userData.getJSONObject(j);
follower = js1.getInt("followers_count");
friends = js1.getInt("friends_count");
ffRatio = friends/follower;
String createdDate = js1.getString("created_at");
statuses = js1.getInt("statuses_count");
String nameData = js1.getString("name");
String gen = gender(nameData);
//}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm completely new to this OAuth and Access Tokens and all so any help will be much appreciated.
With
OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);
you are doing an unauthenticated request using the Scribe library (you never instantiated an OAuthService object which would have to be used to sign this request). So when you do this too often Twitter denies these requests.
So your problem here does indeed come from mixing Twitter4J and Scribe.
I wrote a simple java application, I have a problem please help me;
I have a file (JUST EXAMPLE):
1.TXT
-------
SET MRED:NAME=MRED:0,MREDID=60;
SET BCT:NAME=BCT:0,NEPE=DCS,T2=5,DK0=KOR;
CREATE LCD:NAME=LCD:0;
-------
and this is my source code
import java.io.IOException;
import java.io.*;
import java.util.StringTokenizer;
class test1 {
private final int FLUSH_LIMIT = 1024 * 1024;
private StringBuilder outputBuffer = new StringBuilder(
FLUSH_LIMIT + 1024);
public static void main(String[] args) throws IOException {
test1 p=new test1();
String fileName = "i:\\1\\1.txt";
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ";|,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
p.processToken(token);
}
}
p.flushOutputBuffer();
}
private void processToken(String token) {
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("MREDID:").append(value).append("\n");
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("DK0=:").append(value).append("\n");
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("NEPE:").append(value).append("\n");
}
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}
private String getTokenValue(String token,String find) {
int start = token.indexOf(find) + 1;
int end = token.length();
String value = token.substring(start, end);
return value;
}
private void flushOutputBuffer() {
System.out.print(outputBuffer);
outputBuffer = new StringBuilder(FLUSH_LIMIT + 1024);
}
}
I want this output :
MREDID:60
DK0=:KOR
NEPE:DCS
But this application show me this :
MREDID:60
NEPE:DCS
DK0=:KOR
please tell me how can i handle this , because of that DK0 must be at first and this is just a sample ; my real application has 14000 lines
Thanks ...
Instead of outputting the value when you read it, put it in a hashmap. Once you've read your entire file, output in the order you want by getting the values from the hashmap.
Use a HashTable to store the values and print from it in the desired order after parsing all tokens.
//initialize hash table
HashTable ht = new HashTable();
//instead of outputBuffer.append, put the values in to the table like
ht.put("NEPE", value);
ht.put("DK0", value); //etc
//print the values after the while loop
System.out.println("MREDID:" + ht.get("MREDID"));
System.out.println("DK0:" + ht.get("DK0"));
System.out.println("NEPE:" + ht.get("NEPE"));
Create a class, something like
class data {
private int mredid;
private String nepe;
private String dk0;
public void setMredid(int mredid) {
this.mredid = mredid;
}
public void setNepe(String nepe) {
this.nepe = nepe;
}
public void setDk0(String dk0) {
this.dk0 = dk0;
}
public String toString() {
String ret = "MREDID:" + mredid + "\n";
ret = ret + "DK0=:" + dk0 + "\n";
ret = ret + "NEPE:" + nepe + "\n";
}
Then change processToken to
private void processToken(String token) {
Data data = new Data();
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
data.setMredid(Integer.parseInt(value));
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
data.setDk0(value);
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
data.setNepe(value);
}
outputBuffer.append(data.toString());
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}