IPathVariableManager.validateValue(URI) returns null - eclipse-plugin

in the Eclipse plugin I'm working on I have a piece of code which basically looks like this:
public static void checkProblemV1() {
try {
String path = "C:\\temp";
org.eclipse.core.runtime.IPath value =
new org.eclipse.core.runtime.Path(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV1(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV1(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setValue(name, value); // setValue is deprecated
System.out.println("checkProblemV1(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV1(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV1(): statusValue is not OK.");
}
}
}
catch (CoreException e) {
System.err.println("checkProblemV1(): CoreException: " + e.getMessage());
}
}
When the above method is executed, there are no problems, but I get a deprecation warning for setValue() when compiling. It's when I wanted to fix that deprecation warning by replacing the call to setValue() with a call to setURIValue() that I got into trouble. First I had to tweak how that Windows-style path was written to avoid an URISyntaxException but after doing that, setURIValue() returns null and after having a look in the documentation I can't see that it should do that? I guess the URI is invalid after all but don't know how to fix it. Below is a test method in the same style as the one above demonstrating the problem.
public static void checkProblemV2() {
try {
String path = "C:\\temp";
// Have to replace \ with /, or we get URISyntaxExeption:
// checkProblemV2(): URISyntaxException: Illegal character in opaque part at index 2: C:\temp
path = path.replace('\\', '/');
java.net.URI value = new java.net.URI(path);
IPathVariableManager pathManager =
ResourcesPlugin.getWorkspace().getPathVariableManager();
String name = "somename";
IStatus statusName = pathManager.validateName(name);
IStatus statusValue = pathManager.validateValue(value);
if (statusName == null || statusValue == null) {
System.err.println("checkProblemV2(): statusName is " +
(statusName == null ? "null" : ("not null: '" + statusName + "'.")));
System.err.println("checkProblemV2(): statusValue is " +
(statusValue == null ? "null" : ("not null: '" + statusValue + "'.")));
}
else if (statusName.isOK() && statusValue.isOK()) {
pathManager.setURIValue(name, value);
System.out.println("checkProblemV2(): Everything fine");
}
else {
if (!statusName.isOK()) {
System.err.println("checkProblemV2(): statusName is not OK.");
}
if (!statusValue.isOK()) {
System.err.println("checkProblemV2(): statusValue is not OK.");
}
}
}
catch (URISyntaxException e) {
System.err.println("checkProblemV2(): URISyntaxException: " + e.getMessage());
}
catch (CoreException e) {
System.err.println("checkProblemV2(): CoreException: " + e.getMessage());
}
}
When I run the above two methods, I get the following output.
checkProblemV1(): Everything fine
checkProblemV2(): statusName is not null: 'Status OK: unknown code=0 OK null'.
checkProblemV2(): statusValue is null
Thanks for reading and for any help, it's seriously appreciated!

There's a bug in org.eclipse.core.internal.resources.PathVariableManager.validateValue(URI) where it is using other internal methods but returning null no matter what else is going on. Please open a bug with Eclipse Platform/Resources.
And I agree with your comment, you should use:
URI uri = new File("C:\\temp").toURI();
pathManager.setURIValue(theName, uri);

Related

How to fix '0 level missing for abstractListDefinition 0' error when using Emulator.getNumber()

I used docx4j to read the docx file. And I need to read the paragraph number format characters. I use Emulator.getNumber() to process, but I got this error. How should I deal with it?
try {
PPr pPr = ((P) p).getPPr();
if (pPr != null && pPr.getNumPr() != null) {
Emulator.ResultTriple triple = Emulator.getNumber(wordprocessingMLPackage, pPr);
if (triple != null) {
order = triple.getNumString();
}
}
} catch (Exception e) {
// throw error '0 level missing for abstractListDefinition 0'
e.printStackTrace();
}
Any help would be appreciated.Thanks.
docx4j version: 6.1.2
docx4j's html output uses it like so:
// Numbering
String numberText=null;
String numId=null;
String levelId=null;
if (pPrDirect.getNumPr()!=null) {
numId = pPrDirect.getNumPr().getNumId()==null ? null : pPrDirect.getNumPr().getNumId().getVal().toString();
levelId = pPrDirect.getNumPr().getIlvl()==null ? null : pPrDirect.getNumPr().getIlvl().getVal().toString();
}
ResultTriple triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal, numId, levelId);
if (triple==null) {
getLog().debug("computed number ResultTriple was null");
} else {
if (triple.getBullet() != null) {
//numberText = (triple.getBullet() + " ");
numberText = "\u2022 ";
} else if (triple.getNumString() == null) {
getLog().error("computed NumString was null!");
numberText = ("?");
} else {
numberText = (triple.getNumString() + " ");
}
}
if (numberText!=null) {
currentParent.appendChild(document.createTextNode(
numberText + " "));
}
XSL-FO output:
if (pPrDirect!=null && pPrDirect.getNumPr()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPrDirect.getNumPr().getNumId().getVal().toString(),
pPrDirect.getNumPr().getIlvl().getVal().toString() );
} else {
// Get the effective values; since we already know this,
// save the effort of doing this again in Emulator
Ilvl ilvl = pPr.getNumPr().getIlvl();
String ilvlString = ilvl == null ? "0" : ilvl.getVal().toString();
triple = null;
if (pPr.getNumPr().getNumId()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPr.getNumPr().getNumId().getVal().toString(),
ilvlString );
}
}

How to validate a link showing 500 error in Selenium?

I am trying to validate the links of a website using server response code and page title, the server response found through the code shown below is 200 and page title is also same for all the pages.
the code is as follows:
if(url == null || url.isEmpty())
{
System.out.println("URL is either not configured for anchor tag or it is
empty");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else if(!url.startsWith(homePage)){
System.out.println("URL belongs to another domain, skipping it.");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else{
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode != 200){
System.out.println(url+" is a broken link");
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"broken_links",url);
}
else{
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
if (Actualtitle.contentEquals(unexpectedTitle)){
System.out.println(url+ " is a broken link");
objExcelFile.writeExcel(filePath,"broken_links",url);
} else {
System.out.println(url+ " is a valid link");
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"valid_links",url);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
The header is intact but the link is showing 500 error below the header. The issue is that even though page is showing 500 error, I am getting the server response code as 200, hence I am not able to make out whether this link is broken or not
This is the screenshot of the issue for the page I am validating :
enter image description here
Once you induce connect() as in :
huc.connect();
You can write as many for() loops to check any condition of the Response Code invoking getResponseCode() method as below :
if (huc.getResponseCode() == 200)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 500)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 404)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 402)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND)
{
System.out.println(
linkURL + " - " + huc.getResponseMessage() + " - " + huc.HTTP_NOT_FOUND);
}
} catch (IOException e)
{
System.out.println(e.getMessage());
}

How to avoid to fetch a list of followers of the same Twitter user that was displayed before

I'm very new at coding and I'm having some issues. I'd like to display the followers of followers of ..... of followers of some specific users in Twitter. I have coded this and I can set a limit for the depth. But, while running the code with a small sample, I saw that I run into the same users again and my code re-display the followers of these users. How can I avoid this and skip to the next user? You can find my code below:
By the way, while running my code, I encounter with a 401 error. In the list I'm working on, there's a private user, and when my code catches that user, it stops. Additionally, how can I deal with this issue? I'd like to skip such users and prevent my code to stop.
Thank you for your help in advance!
PS: I know that I'll encounter with a 429 error working with a large sample. After fixing these issues, I'm planning to review relevant discussions to deal with.
public class mainJava {
public static Twitter twitter = buildConfiguration.getTwitter();
public static void main(String[] args) throws Exception {
ArrayList<String> rootUserIDs = new ArrayList<String>();
Scanner s = new Scanner(new File("C:\\Users\\ecemb\\Desktop\\rootusers1.txt"));
while (s.hasNextLine()) {
rootUserIDs.add(s.nextLine());
}
s.close();
for (String rootUserID : rootUserIDs) {
User rootUser = twitter.showUser(rootUserID);
List<User> userList = getFollowers(rootUser, 0);
}
}
public static List<User> getFollowers(User parent, int depth) throws Exception {
List<User> userList = new ArrayList<User>();
if (depth == 2) {
return userList;
}
IDs followerIDs = twitter.getFollowersIDs(parent.getScreenName(), -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User child = twitter.showUser(id);
userList.add(child);
getFollowers(child, depth + 1);
System.out.println(depth + "th user: " + parent.getScreenName() + " Follower: " + child.getScreenName());
}
return userList;
}
}
I guess graph search algorithms can be implemented for this particular issue. I chose Breadth First Search algorithm because visiting root user's followers at first would be better. You can check this link to additional information about algorithm.
Here is my implementation for your problem:
public List<User> getFollowers(User parent, int startDepth, int finalDepth) {
List<User> userList = new ArrayList<User>();
Queue<Long> queue = new LinkedList<Long>();
HashMap<Long, Integer> discoveredUserId = new HashMap<Long, Integer>();
try {
queue.add(parent.getId());
discoveredUserId.put(parent.getId(), 0);
while (!queue.isEmpty()) {
long userId = queue.remove();
int discoveredDepth = discoveredUserId.get(userId);
if (discoveredDepth == finalDepth) {
continue;
}
User user = twitter.showUser(userId);
handleRateLimit(user.getRateLimitStatus());
if (user.isProtected()) {
System.out.println(user.getScreenName() + "'s account is protected. Can't access followers.");
continue;
}
IDs followerIDs = null;
followerIDs = twitter.getFollowersIDs(user.getScreenName(), -1);
handleRateLimit(followerIDs.getRateLimitStatus());
long[] ids = followerIDs.getIDs();
for (int i = 0; i < ids.length; i++) {
if (!discoveredUserId.containsKey(ids[i])) {
discoveredUserId.put(ids[i], discoveredDepth + 1);
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
userList.add(child);
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
queue.add(ids[i]);
} else {//prints to console but does not check followers. Just for data consistency
User child = twitter.showUser(ids[i]);
handleRateLimit(child.getRateLimitStatus());
if (discoveredDepth >= startDepth && discoveredDepth < finalDepth) {
System.out.println(discoveredDepth + ". user: " + user.getScreenName() + " has " + user.getFollowersCount() + " follower(s) " + (i + 1) + ". Follower: " + child.getScreenName());
}
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return userList;
}
//There definitely are more methods for handling rate limits but this worked for me well
private void handleRateLimit(RateLimitStatus rateLimitStatus) {
//throws NPE here sometimes so I guess it is because rateLimitStatus can be null and add this conditional expression
if (rateLimitStatus != null) {
int remaining = rateLimitStatus.getRemaining();
int resetTime = rateLimitStatus.getSecondsUntilReset();
int sleep = 0;
if (remaining == 0) {
sleep = resetTime + 1; //adding 1 more second
} else {
sleep = (resetTime / remaining) + 1; //adding 1 more second
}
try {
Thread.sleep(sleep * 1000 > 0 ? sleep * 1000 : 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in this code HashMap<Long, Integer> discoveredUserId is used to prevent program checking same users repeatedly and storing in which depth we faced with this user.
and for private users, there is isProtected() method in twitter4j library.
Hope this implementation helps.

Getting "object reference not set to an instance" in HttpContext.Current.Application

I'm hardly to figure out how to solve this.. I want to catch the error when the server is turn off and redirect the page to Maintenance.aspx. But it's getting error at HttpContext.Current.Application["ErrorCode"].ToString();.Please help me how to solve this...
Many thanks.
try{
// method here
}
catch (Exception ex)
{
Panel1.Visible = true;
string statuscode = HttpContext.Current.Application["ErrorCode"].ToString(); //Getting error here!
if (statuscode != null || statuscode != string.Empty)
{
if (statuscode == "500")
{
lblDetailMsg.Text = "<b>Error Page- <b> " + HttpContext.Current.Application["ErrorPage"].ToString() + " <br /> <b>Error Message-</b> The Requested Page was not found.";
Response.Redirect("Maintenance.aspx");
}
}
}
If I understand your code right, then the error must be due to .toString() method.
Try this
string statuscode = Convert.ToString(HttpContext.Current.Application["ErrorCode"]); // added Convert.Tostring()
if (statuscode != null || statuscode != string.Empty)
{
if (statuscode == "500")
{
lblDetailMsg.Text = "<b>Error Page- <b> " + Convert.ToString(HttpContext.Current.Application["ErrorPage"]) + " <br /> <b>Error Message-</b> The Requested Page was not found.";
Response.Redirect("Maintenance.aspx");
}
}
Convert.ToString() handles null, while ToString() doesn't.
Here it seems that HttpContext.Current.Application["ErrorCode"] does not contain value for "Error Code", so it giving null value.

How to disable/deactivate a SalesForce User through SOAP API?

I want to disable a User programmetically by using SOAP API. How can I do that? I am using Partner API and I have Developer edition. I have manage users persmissions set. I have gone through this link. I am looking for code which can help me disable/deactivate a User.
This is my code:
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class DeactivateUser {
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername("waprau#waprau.com");
config.setPassword("sjjhggrhgfhgffjdgj");
PartnerConnection connection = null;
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Username, IsActive from User");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
if(s.getField("Username").equals("abcd#pqrs.com")){
System.out.println("Username: " + s.getField("Username"));
s.setField("IsActive", false);
}
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}
}
This is output:
Username: waprau#waprau.com IsActive: true
Username: jsmith#ymail.net IsActive: false
Username: abcd#pqrs.com
Username: abcd#pqrs.com IsActive: false
However in UI when I go to My Name > Setup > Manage Users > Users, it always show 'Active' check box for user abcd#pqrs.com selected :-(
It doesn't look like you're actually sending the update back to Salesforce - you're just setting IsActive to false locally. You will need to use a call to PartnerConnection.update(SObject[] sObjects) in order for Salesforce to reflect your changes, like so:
try {
connection = Connector.newConnection(config);
QueryResult queryResults = connection.query("SELECT Id, Username, IsActive from User");
if ( queryResults.getSize() > 0 ) {
// keep track of which records you want to update with an ArrayList
ArrayList<SObject> updateObjects = new ArrayList<SObject>();
for (SObject s : queryResults.getRecords()) {
if ( s.getField("Username").equals("abcd#pqrs.com") ){
System.out.println("Username: " + s.getField("Username"));
s.setField("Id", null);
s.setField("IsActive", false);
}
updateObjects.add(s); // if you want to update all records...if not, put this in a conditional statement
System.out.println("Username: " + s.getField("Username") + " IsActive: " + s.getField("IsActive"));
}
// make the update call to Salesforce and then process the SaveResults returned
SaveResult[] saveResults = connection.update(updateObjects.toArray(new SObject[updateObjects.size()]));
for ( int i = 0; i < saveResults.length; i++ ) {
if ( saveResults[i].isSuccess() )
System.out.println("record " + saveResults[i].getId() + " was updated successfully");
else {
// There were errors during the update call, so loop through and print them out
System.out.println("record " + saveResults[i].getId() + " failed to save");
for ( int j = 0; j < saveResults[i].getErrors().length; j++ ) {
Error err = saveResults[i].getErrors()[j];
System.out.println("error code: " + err.getStatusCode().toString());
System.out.println("error message: " + err.getMessage());
}
}
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
It is possible to directly work with the user record without the SOQL query if you already know the Id.
SalesforceSession session = ...;
sObject userSObject = new sObject();
userSObject.Id = "00570000001V9NA";
userSObject.type = "User";
userSObject.Any = new System.Xml.XmlElement[1];
XmlDocument xmlDocument = new XmlDocument();
XmlElement fieldXmlElement = xmlDocument.CreateElement("IsActive");
fieldXmlElement.InnerText = bool.FalseString;
userSObject.Any[0] = fieldXmlElement;
SaveResult[] result = session.Binding.update(new sObject[] { userSObject });
foreach(SaveResult sr in result)
{
System.Diagnostics.Debug.WriteLine(sr.success + " " + sr.id);
if(!sr.success)
{
foreach(Error error in sr.errors)
{
System.Diagnostics.Debug.WriteLine(error.statusCode + " " + error.message);
}
}
}