This question already has answers here:
Error using one package from another "class interface or enum expected"
(3 answers)
Java error: class, interface, or enum expected,
(3 answers)
Class, interface, or enum expected when compiling
(1 answer)
Closed 5 years ago.
So, the problem is: I cannot load the imports. Help...
I got this code from online just to experiment with how it works. The problem is that the error that a "class, interface, or enum expected." It just won't compile and keeps asking for a JAR due to the dependencies at the top. I don't even know what dependencies were until I saw this program. Can someone please tell me why it's not working, and attempt to fix it? I tried all the .JAR Intellij suggested, then I tried searching up the issue but most of the answers were irrelevant or too complicated involving Maven or something. Please help...
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpDocumentExistsWithHttpClient {
/**
* check if a document exists in a sharepoint library
*/
public static void main(String[] args) throws Exception{
CloseableHttpClient httpclient = HttpClients.custom()
.setRetryHandler(new DefaultHttpRequestRetryHandler(0,false))
.build();
String user = "myusername";
String pwd = "mypassword";
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials(user, pwd, "", ""));
// You may get 401 if you go through a load-balancer.
// To fix this, go directly to one of the sharepoint web server or
// change the config. See this article :
// http://blog.crsw.com/2008/10/14/unauthorized-401-1-exception-calling-web-services-in-sharepoint/
HttpHost target = new HttpHost("web01.mysharepoint.local", 80, "http");
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
// The authentication is NTLM.
// To trigger it, we send a minimal http request
HttpHead request1 = new HttpHead("/");
CloseableHttpResponse response1 = null;
try {
response1 = httpclient.execute(target, request1, context);
EntityUtils.consume(response1.getEntity());
System.out.println("1 : " + response1.getStatusLine().getStatusCode());
}
finally {
if (response1 != null ) response1.close();
}
// The real request, reuse authentication
String file = "/30500C/PubDoc/TEST/jira.log"; // source
HttpGet request2 = new HttpGet("/_api/web/GetFileByServerRelativeUrl('" + file + "')/Etag");
CloseableHttpResponse response2 = null;
try {
response2 = httpclient.execute(target, request2, context);
EntityUtils.consume(response2.getEntity());
int rc = response2.getStatusLine().getStatusCode();
String reason = response2.getStatusLine().getReasonPhrase();
if (rc != HttpStatus.SC_OK) {
System.out.println(file + " is missing. Reason : "
+ reason + " rc : " + rc + "(500 is the equivalent of NOT FOUND)");
}
else {
System.out.println(file + " exists.");
}
}
finally {
if (response2 != null) response2.close();
}
return;
}
}
I'm literally just trying to compile this in JGrasp and IntelliJ. Not that experienced with Java.
First of all, Maven is a dependency management and build tool, which can download dependencies automatically for you, if it is set-up.
The first piece of code (<dependency>...) are instructions to maven to fetch the dependencies. it belongs into a pom.xml file not in your class.
If you are not set-up for this and don't want to get into it you can download the needed JARs at https://hc.apache.org/downloads.cgi. And make sure to add this to the classpath.
I do recommend that you get familiar with a tool like Maven as you will encounter dependencies all along when working with Java and it does simplify a lot of things in the long run.
Related
I am trying to pull discussions for a given defect. I understand from a prior question I asked that it is not possible to pull the discussion data as a property of the defect itself rather I must run a separate fetch request.
The problem is that I can not identify any query filter to use when pulling conversation posts. This leads me to believe I would have to loop through every single conversation post and try to find the matching defect number in the actual data returned which would be highly inefficient.
Rather I would prefer to simply run a query fetch for each defect that uses a query filter for the formatted ID that will only return the conversation posts that apply for that defect.
import com.google.gson.JsonElement;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class ExtractFull {
#SuppressWarnings("unchecked")
public static void main(String args[]) throws URISyntaxException, IOException {
RallyRestApi restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"), "_myapikey");
restApi.setApplicationName("DANA Example");
restApi.setProxy(new URI("http://myproxy:8080"), "username", "pass");
System.out.println("Querying Rally for defects, this may take some time");
try {
QueryRequest defectRequest = new QueryRequest("ConversationPost");
defectRequest.setPageSize(2000);
defectRequest.setLimit(5000);
QueryFilter filter = new QueryFilter("FormattedID","=","DE10101");
defectRequest.setQueryFilter(filter);
defectRequest.setFetch(new Fetch());
QueryResponse queryResponse = restApi.query(defectRequest);
for(JsonElement result: queryResponse.getResults()){
System.out.println(result);
}
} finally {
restApi.close();
}
}
}
This code doesn't work. I assume because "FormattedId" isn't a valid object of the "ConversationPost" type. I don't know if it's possible to filter for parent defect ID when querying a conversation post but that is what I need to do.
Specifically the code I am referring to is here:
QueryRequest defectRequest = new QueryRequest("ConversationPost");
defectRequest.setPageSize(2000);
defectRequest.setLimit(5000);
QueryFilter filter = new QueryFilter("FormattedID","=","DE10101");
defectRequest.setQueryFilter(filter);
Use the standard WSAPI, I can query like this:
(Artifact.FormattedID = "US123")
Was able to solve this issue on my own. The problem was that I was attempting to use "QueryRequest" without having a valid "type" to pass to the constructor.
The correct solution was to use "GetRequest" with the path to the defect discussion page being passed as the url (without requiring me to set an object type in the constructor). This returned a GetRequest object which contained a result set with all of the conversation posts.
GetRequest getRequest = new GetRequest(discussionURL);
GetResponse getResponse = restApi.get(getRequest);
The "discussion url" did not contain the "https://rally1.rallydev.com" which was declared when creating the rallyApi - the discussionURL variable contains the entire defect discussion page URL but without the above rally api url so for example "/slm/webservice/v2.0/Defect/106032660792/Discussion"
I have 2 questions
I am trying to run a axis 2 sample. In the last part of the instruction file, there is this line which it says, should be run in the terminal(ubuntu), is not working
java -Djava.ext.dirs=%AXIS2_HOME%\lib;%JAVA_HOME%\jre\lib\ext -cp target/classes org.apache.axis2.jaxws.addressbook.AddressBookClient.class
I am not an expert in this field, and I am not familiar with ubuntu commands. I feel that this is not an ubuntu command
The error I get is, "Invalid Job"
Can someone convert this into an ubuntu command?
Since it was not working, I built the jar using,
mvn clean install
Then I copied the jar file to the servicejars directory under repository, in axis2
Then the axis server says that the jar does not contain the WebServices annotation
"No #WebService annotated service implementations found in the jar: file:/home/dodan/Programs/axis2-1.6.0/repository/servicejars/jaxws-addressbook-1.6.0-client.jar. Service deployment failed."
So I added it to the original java file which did not have that annotation(and the import too)
Yet the axis2 server still sys that there is not webservices annotation
2. Can somebody say whether I have missed anything?
here is the java file I changed
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.jws.WebService;
import java.util.Map;
/**
* Simple JAX-WS Dispatch client for the address book service implementation.
*/
#WebService
public class AddressBookClient {
private static String NAMESPACE = "http://addressbook.jaxws.axis2.apache.org";
private static QName QNAME_SERVICE = new QName(NAMESPACE, "service");
private static QName QNAME_PORT = new QName(NAMESPACE, "port");
private static String ENDPOINT_URL = "http://localhost:8080/axis2/services/AddressBookImplService.AddressBookImplPort";
private static String ADD_ENTRY_BODY_CONTENTS =
"<ns1:addEntry xmlns:ns1=\"http://addressbook.jaxws.axis2.apache.org\">" +
"<ns1:firstName xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myFirstName</ns1:firstName>" +
"<ns1:lastName xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myLastName</ns1:lastName>" +
"<ns1:phone xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myPhone</ns1:phone>" +
"<ns1:street xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myStreet</ns1:street>" +
"<ns1:city xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myCity</ns1:city>" +
"<ns1:state xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myState</ns1:state>" +
"</ns1:addEntry>";
private static String FIND_BODY_CONTENTS =
"<ns1:findByLastName xmlns:ns1=\"http://addressbook.jaxws.axis2.apache.org\">" +
"<ns1:lastName xmlns=\"http://addressbook.jaxws.axis2.apache.org\">myLastName</ns1:lastName>" +
"</ns1:findByLastName>";
public static void main(String[] args) {
try {
System.out.println("AddressBookClient ...");
Service svc = Service.create(QNAME_SERVICE);
svc.addPort(QNAME_PORT, null, ENDPOINT_URL);
// A Dispatch<String> client sends the request and receives the response as
// Strings. Since it is PAYLOAD mode, the client will provide the SOAP body to be
// sent; the SOAP envelope and any required SOAP headers will be added by JAX-WS.
Dispatch<String> dispatch = svc.createDispatch(QNAME_PORT,
String.class, Service.Mode.PAYLOAD);
// Invoke the Dispatch
System.out.println(">> Invoking sync Dispatch for AddEntry");
String response = dispatch.invoke(ADD_ENTRY_BODY_CONTENTS);
System.out.println("Add Entry response: " + response);
System.out.println(">> Invoking Dispatch for findByLastName");
String response2 = dispatch.invoke(FIND_BODY_CONTENTS);
System.out.println("Find response: " + response2);
} catch (Exception e) {
System.out.println("Caught exception: " + e);
e.printStackTrace();
}
}
}
You're using Windows syntax for environment variables.
Instead of %AXIS_HOME%, you would use $AXIS_HOME.
That said, you do not need any version of Axis to learn about web services these days. JAX-WS implementations exist in the JDK for Java 6 and newer.
There's a lot of tutorials around for it.
Here is a code to create a new bug in Bugzilla using Java. But I am getting following error.
BugCreator2.java:20: error: cannot find symbol
factory.setHttpClient(httpClient);
^
symbol: method setHttpClient(HttpClient)
location: variable factory of type XmlRpcCommonsTransportFactor
Note: BugCreator2.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
Following Jar Files I have used:
commons-httpclient-3.0.1
java-rt-jar-stubs-1.5.0
ws-commons-util-1.0.1
ws-commons-util-1.0.1-sources
xmlrpc-3.0
xmlrpc-3.0-common
I don't knnow if all of them are required.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
public class BugCreator2 {
public static void main(String s[])
throws MalformedURLException, XmlRpcException {
HttpClient httpClient = new HttpClient();
XmlRpcClient rpcClient = new XmlRpcClient();
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(rpcClient);
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
factory.setHttpClient(httpClient);
rpcClient.setTransportFactory(factory);
config.setServerURL(new URL("http://URL/bugzilla/xmlrpc.cgi"));
rpcClient.setConfig(config);
// map of the login data
Map loginMap = new HashMap();
loginMap.put("login", "username#abc.com");
loginMap.put("password", "*********");
loginMap.put("rememberlogin", "Bugzilla_remember");
// login to bugzilla
Object loginResult = rpcClient.execute("User.login", new Object[]{loginMap});
System.err.println ("loginResult=" + loginResult);
// map of the bug data
Map bugMap = new HashMap();
bugMap.put("product", "Demo");
bugMap.put("component", "Demo_project");
bugMap.put("summary", "Bug created for test");
bugMap.put("description", "This is text ");
bugMap.put("version", "unspecified");
bugMap.put("op_sys", "Windows");
bugMap.put("platform", "PC");
bugMap.put("priority", "P2");
bugMap.put("severity", "Normal");
bugMap.put("status", "NEW");
// create bug
Object createResult = rpcClient.execute("Bug.create", new Object[]{bugMap});
System.err.println("createResult = " + createResult);
}
}
After much efforts i came to know there is problem with versions of JARs. You need to use exact JARS as come other versions are not supporting some methods.
Jars Used:
commons-httpclient-3.0.1
commons-logging-1.1.3
java-rt-jar-stubs-1.5.0
org.apache.commons.codec_1.3.0.v201101211617
ws-commons-util-1.0.2
xmlrpc-client-3.1.3
xmlrpc-common-3.1.3
I want to use Windows NTLM authentication in my Java application to authenticate intranet users transparently. The users should not notice any authentication if using their browsers (single sign-on).
I've found a few libs with NTLM support, but don't know which one to use:
http://spnego.sourceforge.net/
http://sourceforge.net/projects/ntlmv2auth/
http://jcifs.samba.org/
http://www.ioplex.com/jespa.html
http://www.luigidragone.com/software/ntlm-authentication-in-java/
Any suggestions where to start?
Out of the above list, only ntlmv2-auth and Jespa support NTLMv2. Jespa is workable but commercial. ntlmv2-auth I haven't tried but it's based on the code from Liferay, which I've seen working before.
'ntlm-authentication-in-java' is only NTLMv1, which is old, insecure, and works in a dwindling number of environments as people upgrade to newer Windows versions. JCIFS used to have an NTLMv1 HTTP auth filter, but it was removed in later versions, as the way it was implemented amounts to a man-in-the-middle attack on the insecure protocol. (The same appears to be true of 'ntlm-authentication-in-java'.)
The 'spnego' project is Kerberos not NTLM. If you want to replicate full IWA as IIS does it, you'd need to support both NTLMv2 and Kerberos ('NTLM' auth, 'Negotiate' auth, NTLMSSP-in-SPNego auth and NTLM-masquerading-as-Negotiate auth).
Luigi Dragone's script is really old and seems to always fail.
HttpURLConnection can work with NTLM if you add library jcifs, this example works with latest jcifs-1.3.18 :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.impl.auth.NTLMEngineException;
public class TestNTLMConnection {
public static void main(String[] args) throws UnknownHostException, IOException, NTLMEngineException {
// Method 1 : authentication in URL
jcifs.Config.registerSmbURLHandler();
URL urlRequest = new URL("http://domain%5Cuser:pass#127.0.0.1/");
// or Method 2 : authentication via System.setProperty()
// System.setProperty("http.auth.ntlm.domain", "domain");
// System.setProperty("jcifs.smb.client.domain", "domain");
// System.setProperty("jcifs.smb.client.username", "user");
// System.setProperty("jcifs.smb.client.password", "pass");
// Not verified // System.setProperty("jcifs.netbios.hostname", "host");
// System.setProperty("java.protocol.handler.pkgs", "jcifs");
// URL urlRequest = new URL("http://127.0.0.1:8180/simulate_get.php");
HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
StringBuilder response = new StringBuilder();
try {
InputStream stream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str = "";
while ((str = in.readLine()) != null) {
response.append(str);
}
in.close();
System.out.println(response);
} catch(IOException err) {
System.out.println(err);
} finally {
Map<String, String> msgResponse = new HashMap<String, String>();
for (int i = 0;; i++) {
String headerName = conn.getHeaderFieldKey(i);
String headerValue = conn.getHeaderField(i);
if (headerName == null && headerValue == null) {
break;
}
msgResponse.put(headerName == null ? "Method" : headerName, headerValue);
}
System.out.println(msgResponse);
}
}
}
And if you are curious about the content of each handshake, you can find another example using jcifs and Socket on this thread.
Had to recently implement this at work hence here is updated solution with Spring's RestTemplate:
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
public class Runner {
public static void main(String[] args) {
var credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials("username", "password", "", "someDomain"));
try (var client = HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.build();) {
var requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(client);
RestTemplate restTemplate = new RestTemplate(requestFactory);
ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("url", new HttpEntity<>("yourDtoObject"), String.class);
} catch (IOException e) {
e.printStackTrace();
}
}
}
dependencies needed are: spring-web and org.apache.httpcomponents
ps: it is important to enter username without domain otherwise it doesn't work. As in if your domain is companyName/username often people just enter that whole thing as username and what you should do is enter them separately where domain="companyName" and username="username"
Ref: https://jcifs.samba.org/src/docs/faq.html#ntlmv2
Q: Does jCIFS support NTLMv2?
A: Yes. As of 1.3.0, JCIFS fully supports NTLMv2 and uses it by default.
Note: The NTLM HTTP SSO Filter that used to be included with JCIFS cannot support NTLMv2.
Relatively from the list you gave,I would go with JCIFS.
The library is mature , and their documentation is good.
To top it off they had fairly regular releases , and the last one being Nov 2011.
Personal Experience : it was fairly easy to get started when compared to others i have tried (spnego and ntmv2auth)
Hi I am new to flickrj library.
Have foundational java knowledge though.
The project that I am working on requires me to authenticate into flickr and then download geo-tagged images into a folder in local hard drive. The program will be Desktop application program.
I am approaching the program by breaking down into 3 steps.
1.Proper authentication to be completed.(which i have succeeded)
2.Try to download all the photos that user has when authenticated.
3.Try to alter the code a little so that it will only download geo-tagged images.
My problems is on step 2. I cant download logged-in user images let alone geo-tagged ones.
I am trying the code provided by Daniel Cukier here
But I am running into problem.
My netbeans simply strike off at the line 77 on .getOriginalAsStream() part, with the error "java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.io.ByteArrayOutputStream.write"
From my understanding netbeans striking off a line means , it is depreciated but shouldnt it still work? What is holding this whole problem back?
I have tried researching and basically I have to admit , it is beyond my capability to trouble shoot. If anyone has any idea on what i am doing wrong , I would be so grateful.
Ps: I am not looking to be spoon fed but please answer me in idiot-friendly way as I am still a student and my java isn't the greatest.
This code is what I have so far.
import com.aetrion.flickr.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.util.IOUtilities;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class authenticate {
Flickr f;
RequestContext requestContext;
String frob = "";
String token = "";
Properties properties = null;
public authenticate() throws ParserConfigurationException, IOException, SAXException {
InputStream in = null;
try {
in = getClass().getResourceAsStream("/setup.properties");
properties = new Properties();
properties.load(in);
} finally {
IOUtilities.close(in);
}
f = new Flickr(
properties.getProperty("apiKey"),
properties.getProperty("secret"),
new REST()
);
Flickr.debugStream = false;
requestContext = RequestContext.getRequestContext();
AuthInterface authInterface = f.getAuthInterface();
try {
frob = authInterface.getFrob();
} catch (FlickrException e) {
e.printStackTrace();
}
System.out.println("frob: " + frob);
URL url = authInterface.buildAuthenticationUrl(Permission.DELETE, frob);
System.out.println("Press return after you granted access at this URL:");
System.out.println(url.toExternalForm());
BufferedReader infile =
new BufferedReader ( new InputStreamReader (System.in) );
String line = infile.readLine();
try {
Auth auth = authInterface.getToken(frob);
System.out.println("Authentication success");
// This token can be used until the user revokes it.
System.out.println("Token: " + auth.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission().getType());
PhotoList list = f.getPhotosetsInterface().getPhotos("72157629794698308", 100, 1);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Photo photo = (Photo) iterator.next();
File file = new File("/tmp/" + photo.getId() + ".jpg");
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(photo.getOriginalAsStream());
FileUtils.writeByteArrayToFile(file, b.toByteArray());
}
} catch (FlickrException e) {
System.out.println("Authentication failed");
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
authenticate t = new authenticate();
} catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
You are correct in your interpretation of the strikeout that getOriginalAsStream() is deprecated. It looks like you might want to rework your code to use PhotosInterface.getImageAsStream(), passing the ORIGINAL size as one of the arguments.
To adjust NetBeans' behavior with respect to deprecated methods, you can follow the link recommended by #AljoshaBre as well as this one.
If you want download all your photos from Flickr, this is possible if you have a mac computer.
Download Aperture program on Apple Store and install it.
After to install, open the Aperture.
Go on preferences.
Click on 'Accounts' tab.
Click on plus sign (+) on bottom left to add a photo service.
Add the Flicker option.
Follow the login and authorization instructions.
Done! All your photos will be synchronized in you aperture library locate on ~/images/
I hope I have helped.