I am working on a web dev project right now using netbeans 8.2 + glassfish 4.1
My code seems to be good since it is not showing any type of errors. However, when I try to run it and I paste the code in google postman my response look like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<clubss></clubss>
Just to make sure, my project is on football teams. I currently have a table with 3 team only, just to keep it short. A weird thing that I noticed is the last line - "clubss". I searched through my code and could not find the word "clubss" anywhere - I do have loats of "club" + "clubs" but nowhere a "clubss".
However, most important thing to me at the moment is to get the whole thing running and to display the 3 teams in postman.
If you require any code just let me know. I did not paste them in in the first place because
a) it might turned out it is not needed
b) they are fairly long and it would make the post look bad.
However if you do need it I will update it immediately.
Thanks in advance, any help appreciated. UPDATE
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name="clubs")
// define the field order
#XmlType(propOrder={"id", "name", "year", "country", "league",
"picture", "description"})
public class Clubs {
private int id;
private String name, year, country, league, picture, description;
// JAXB requires a default ctor
public Clubs(){
}
public Clubs(int id, String name, String year, String country, String league, String picture, String description) {
this.id = id;
this.name = name;
this.country = country;
this.year = year;
this.league = league;
this.picture = picture;
this.description = description;
}
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
#XmlElement
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#XmlElement
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
#XmlElement
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
#XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Clubs{" + "id=" + id + ", name=" + name + ", country=" + country + ", league=" + league + ", year=" + year + ", picture=" + picture + ", description=" + description + '}';
}
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClubsDAO {
private Connection con = null;
public static void main(String[] args) {
ClubsDAO dao = new ClubsDAO();
int nextId = dao.getNextClubId();
System.out.println(nextId);
}
public ClubsDAO() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/CD_WD3_DB",
"sean", "sean");
System.out.println("OK");
} catch (ClassNotFoundException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("ClassNotFoundException");
ex.printStackTrace();
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
}
public int updateClubs(Clubs clubs){
int rowsUpdated=0;
try{
PreparedStatement ps = con.prepareStatement(
"UPDATE APP.CLUB SET NAME=?, YR=?, COUNTRY=?,"
+ "LEAGUE=?, DESCRIPTION=?, PICTURE=? WHERE "
+ "ID = ?");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
rowsUpdated = ps.executeUpdate();
}catch (Exception e){
System.err.println("Exception in executeUpdate()");
e.printStackTrace();
return -1;
}
return rowsUpdated;// 1
}
public int addClubs(Clubs clubs){
int numRowsInserted=0;
try{
PreparedStatement ps = con.prepareStatement(
"INSERT INTO APP.CLUB " // CLUBS??
+ "(ID, NAME, YR, COUNTRY, "
+ "LEAGUE, DESCRIPTION, PICTURE) "
+ "VALUES (?,?,?,?,?,?,?)");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
numRowsInserted = ps.executeUpdate();
}catch (Exception e){
e.printStackTrace();
return -1;
}
return numRowsInserted;
}
public int getNextClubId(){
int nextClubId = -1;
try{
PreparedStatement ps =
con.prepareStatement(
"SELECT MAX(ID) AS MAX_ID FROM APP.CLUB");
ResultSet rs = ps.executeQuery();
if(!rs.next()){ // set the db cursor
return -1;
}
nextClubId = rs.getInt("MAX_ID") + 1;
}catch(Exception e){
e.printStackTrace();
return -1;
}
return nextClubId;
}
public List<Clubs> findAll() {
List<Clubs> list
= new ArrayList<>();
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB ORDER BY ID");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return list;
}
public Clubs processRow(ResultSet rs) throws SQLException {
Clubs clubs = new Clubs();
clubs.setId(rs.getInt("id"));
clubs.setName(rs.getString("name"));
clubs.setCountry(rs.getString("country"));
clubs.setLeague(rs.getString("league"));
clubs.setYear(rs.getString("yr"));
clubs.setPicture(rs.getString("picture"));
clubs.setDescription(rs.getString("description"));
return clubs;
}
public Clubs findById(int clubId) {
Clubs club = null;
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) { // !F => T
return null;
}
// we have a record
club = processRow(rs);
} catch (SQLException ex) {
//Logger.getLogger(ClubDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return club;
}
public List<Clubs> findByName(String name) {
List<Clubs> list
= new ArrayList<Clubs>();
try {
PreparedStatement pstmt
= con.prepareStatement(
"SELECT * FROM APP.CLUB "
+ "WHERE UPPER(NAME) "
+ "LIKE ? ORDER BY NAME");
pstmt.setString(1, "%" + name.toUpperCase() + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
public int deleteById(int clubId){
int numRowsDeleted=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
numRowsDeleted = pstmt.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
return numRowsDeleted; // 0 == failure; 1 == success
}
public int deleteAllClubs(){
int result=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB");
result = pstmt.executeUpdate(); // 0 == failure; >=1 == success
}catch (Exception e){
e.printStackTrace();
}
return result; // 0 == failure; >=1 == success
}
}
package rest.clubs;
// link into JAX-RS
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/rest")
public class RestConfig extends Application{
#Override
public Set<Class<?>> getClasses(){
final Set<Class<?>> classes =
new HashSet<Class<?>>();
classes.add(ClubsResource.class);
return classes;
}
}
package rest.clubs;
import dao.Clubs;
import dao.ClubsDAO;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
#Path("/clubs")
public class ClubsResource {
// this class responds to ".../rest/clubs"
private static ClubsDAO dao = new ClubsDAO();
#Context
private UriInfo context;
public ClubsResource() {
}
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getAllClubs() {
System.out.println("get all");
List<Clubs> clubList
= dao.findAll();
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
#POST
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response addClubs(Clubs newClubs) {
System.out.println("POST - " + newClubs);
// the 'id' field in the request entity body is ignored!
int nextClubId = dao.getNextClubId();
newClubs.setId(nextClubId);
System.out.println("POST: nextClubId == " + nextClubId);
// now, our Clubobject is set up; insert into db
dao.addClubs(newClubs);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",
String.format("%s%s",
context.getAbsolutePath().toString(),
newClubs.getId()))
.header("Access-Control-Allow-Origin", "*")
.entity(newClubs)
.build();
}
#OPTIONS
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForAllClubs() {
System.out.println("OPTIONS for all");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get all
api.add("POST");// add
api.add("DELETE");// delete all
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
#OPTIONS
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForOneClub() {
System.out.println("OPTIONS for one");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get one
api.add("PUT");// update (or add)
api.add("DELETE");// delete one
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "DELETE, PUT, GET")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
#PUT
#Path("{clubId}")
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response updateOneClub(Clubs updateClub, #PathParam("clubId") int clubId) {
System.out.println("PUT - " + updateClub);
if (clubId == updateClub.getId()) {
// entity body id == id in URI
if (dao.findById(clubId) == null) {
// id not in db, create
dao.addClubs(updateClub);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",context.getAbsolutePath().toString())
.header("Access-Control-Allow-Origin", "*")
.entity(updateClub)
.build();
} else {
// id in db, update
dao.updateClubs(updateClub);
return Response
.status(Response.Status.OK)
.entity(updateClub)
.build();
}
} else {
// id in xml <> id in URI
return Response
.status(Response.Status.CONFLICT)
.entity("<conflict idInURI='"+clubId+"' idInEntityBody='"+updateClub.getId()+"' />")
.build();
}
}
#HEAD
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForAllClubs() {
System.out.println("HEAD");
return Response
.noContent()
.build();
}
#HEAD
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForOneClub(#PathParam("clubId") String clubId) {
return Response
.noContent()
.build();
}
#DELETE
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteAllClubs() {
System.out.println("delete all");
int rowsDeleted = dao.deleteAllClubs();
if (rowsDeleted > 0) { // success
// now set up the HTTP response message
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {
// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<error rowsDeleted='" + rowsDeleted + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
#GET
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getOneClub(#PathParam("clubId") String clubId) {
System.out.println("getOneClub::" + clubId);
Clubs club
= dao.findById(Integer.parseInt(clubId));
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(club)
.build();
}
#GET
#Path("search/{name}") // /clubs/search/Real
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getByName(#PathParam("name") String name) {
System.out.println("getByName: " + name);
List<Clubs> clubList
= dao.findByName(name);
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
#DELETE
#Path("{clubId}") // Path Param i.e. /clubs/1
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteOneClub(#PathParam("clubId") String clubId) {
System.out.println("deleteOneClub(): " + clubId);
// delete the row from the db where the id={clubId}
int numRowsDeleted = dao.deleteById(Integer.parseInt(clubId));
if (numRowsDeleted == 1) { // success
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<idNotInDB id='" + clubId + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
}
Related
GET products/_search
{
"query": {
"multi_match" : {
"query": "novel",
"fields": [ "description", "name","id" ,"price"]
}
}
}
This query i want to fire on my spring boot application to search keyword searching
This is my conreoller class which function i will use
package com.pixelTrice.elastic.search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
#RestController
public class ElasticSearchController {
#Autowired
private ElasticSearchQuery elasticSearchQuery;
#PostMapping("/createOrUpdateDocument")
public ResponseEntity<Object> createOrUpdateDocument(#RequestBody Product product) throws IOException {
String response = elasticSearchQuery.createOrUpdateDocument(product);
return new ResponseEntity<>(response, HttpStatus.OK);
}
#GetMapping("/getDocument")
public ResponseEntity<Object> getDocumentById(#RequestParam String productId) throws IOException {
Product product = elasticSearchQuery.getDocumentById(productId);
return new ResponseEntity<>(product, HttpStatus.OK);
}
#DeleteMapping("/deleteDocument")
public ResponseEntity<Object> deleteDocumentById(#RequestParam String productId) throws IOException {
String response = elasticSearchQuery.deleteDocumentById(productId);
return new ResponseEntity<>(response, HttpStatus.OK);
}
#GetMapping("/searchDocument")
public ResponseEntity<Object> searchAllDocument() throws IOException {
List<Product> products = elasticSearchQuery.searchAllDocuments();
return new ResponseEntity<>(products, HttpStatus.OK);
}
#GetMapping("/searching")
public ResponseEntity<Object> searching() throws IOException{
List<Product> products = elasticSearchQuery.searching();
return new ResponseEntity<>(products,HttpStatus.OK);
}
}
This is my query class as I want to to write java query:
package com.pixelTrice.elastic.search;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Repository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
#Repository
public class ElasticSearchQuery {
#Autowired
private ElasticsearchClient elasticsearchClient;
private final String indexName = "products";
public String createOrUpdateDocument(Product product) throws IOException {
IndexResponse response = elasticsearchClient.index(i -> i
.index(indexName)
.id(product.getId())
.document(product)
);
if (response.result().name().equals("Created")) {
return new StringBuilder("Document has been successfully created.").toString();
} else if (response.result().name().equals("Updated")) {
return new StringBuilder("Document has been successfully updated.").toString();
}
return new StringBuilder("Error while performing the operation.").toString();
}
public Product getDocumentById(String productId) throws IOException {
Product product = null;
GetResponse<Product> response = elasticsearchClient.get(g -> g
.index(indexName)
.id(productId),
Product.class
);
if (response.found()) {
product = response.source();
System.out.println("Product name " + product.getName());
} else {
System.out.println("Product not found");
}
return product;
}
public String deleteDocumentById(String productId) throws IOException {
DeleteRequest request = DeleteRequest.of(d -> d.index(indexName).id(productId));
DeleteResponse deleteResponse = elasticsearchClient.delete(request);
if (Objects.nonNull(deleteResponse.result()) && !deleteResponse.result().name().equals("NotFound")) {
return new StringBuilder("Product with id " + deleteResponse.id() + " has been deleted.").toString();
}
System.out.println("Product not found");
return new StringBuilder("Product with id " + deleteResponse.id() + " does not exist.").toString();
}
public List<Product> searchAllDocuments() throws IOException {
SearchRequest searchRequest = SearchRequest.of(s -> s.index(indexName));
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Product.class);
List<Hit> hits = searchResponse.hits().hits();
List<Product> products = new ArrayList<>();
for (Hit object : hits) {
System.out.print(((Product) object.source()));
products.add((Product) object.source());
}
return products;
}
public List<Product> searching() throws IOException{
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(indexName);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
QueryBuilder cluase0 = QueryBuilders.multiMatchQuery(queryString,
"name",
"id",
"description",
"price");
MultiMatchQueryBuilder multiMatchQueryBuilder1 = new MultiMatchQueryBuilder(queryString, "firstName", "lastName",
"password", "emailId", "userId", "mobileNumber");
multiMatchQueryBuilder1.operator(Operator.AND);
searchSourceBuilder.query(multiMatchQueryBuilder1);
}
GET products/_search
{
"query": {
"multi_match" : {
"query": "novel",
"fields": [ "description", "name","id" ,"price"]
}
}
}
i tried this on kibana and get my desired keyword search on "novel" it showed me my desired result now i want to convert this into java api but couldnot think how can i write its sysntax on java
SearchRequest searchRequest = SearchRequest.of(s -> s.index("products").from(from).size(size).query(q -> q.multiMatch(
t -> t .fields("description","name").query(text)))
);
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Product.class);
List<Hit> hits = searchResponse.hits().hits();
List<Product> products = new ArrayList<>();
for(Hit object : hits){
products.add(p);
}
How to get OAuth2.0 access token using refresh token in scala .
Sample code using the HttpsURLConnection, without any libraries
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Sample_OAuth {
public static void main(String[] args) throws Exception {
Sample_OAuth outhDriver = new Sample_OAuth();
outhDriver.sendRefreshTokenRequestWithOnlyHeader(null);
}
/**
* Send refresh token request to 3rd party with client cred either in body or
* request header.
*
* #param conn
* #param mapListTagToMetaDataName
* #return
* #throws Exception
*/
private Map<String, Object> sendRefreshTokenRequestWithOnlyHeader(Map<String, String> mapListTagToMetaDataName)
throws Exception {
String tokenUrl = "https://xyz.snowflakecomputing.com/oauth/token-request";
URL url = new URL(tokenUrl);
StringBuilder stringBuilder = new StringBuilder();
appendURLParam(stringBuilder, "grant_type", "refresh_token", true);
appendURLParam(stringBuilder, "refresh_token", "ver:2-hint:2065896170862-did:1003-ETMsDgAAAYWAOC1cABRBRVMvQ0JDL1BLQ1M1UGFkZGluZwEAABAAEDu3hgX2UvrDbaMif7uC+ygAAADwoZhxL+aOCvvsmNh0wy0FdNGuDRLCtOq7iQTsZPPmfkRZJnkj3nXgKDxTFeFOmty4ej/O6Fsf17HfNvKdLrqfN3V29FkFQ5S+FktFIznTSjtd7+xaMS+sPEAyey2SFfbSyMvrknjq9F+CQZ50H181OO8Ak4v1uW4ON9Q1UBRd9ywM2Yg5g59hPgy90jtAW0DPQ8gvfAwRJCgg2wzV7tXrQ1H2TQhFEkQH418s5pSNB5V6BSW0fFqOUW3O8X4MmHcWcpTbghZ5aga8+dSKSR8jd2KMmfawyXMdkIYdWEsrpcJozuYDAjFwIT1lkqLxqBnuABQIbwjao0KeWXYU3sYanTb0WoR4Ng==",
false);
String clientRequestType = "Basic Auth Header";
return sendOAuthRequestWithHeader(mapListTagToMetaDataName, url, stringBuilder.toString());
}
private static void appendURLParam(StringBuilder stringBuilder, String name, String value, boolean appendAmpersand)
throws UnsupportedEncodingException {
/*
* if (StringUtil.isNullOrEmptyTrim(name) ||
* StringUtil.isNullOrEmptyTrim(value)) { //log.error(String.
* format("Either Auth attr name : %s or value : %s is Null or empty", name,
* value)); return; }
*/
stringBuilder.append(name);
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(value, "UTF-8"));
//stringBuilder.append(value);
if (appendAmpersand) {
stringBuilder.append("&");
}
}
private Map<String, Object> sendOAuthRequestWithHeader(Map<String, String> mapListTagToMetaDataName, URL url,
String postBody) throws Exception {
String clientId = "S0RpOorCRUQOqVncoxc8fXUO22A=";
String client_secret = "MHTOaEmQeLB359K+kEAs/+2ow4AcmqD5/ABckC4E2fQ=";
clientId = clientId + ":" + client_secret;
// Should not be MIME-encode since value is used as a HTTP header and MIME adds
// new lines if over 76 characters
String value = java.util.Base64.getEncoder().encodeToString(clientId.getBytes());
return sendOAuthRequest(url, postBody, value);
}
private Map<String, Object> sendOAuthRequest(URL url, String postBody, String authorizationHeader) throws Exception {
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.addRequestProperty("Accept", "application/json");
if (notNullOrEmptyTrim(authorizationHeader)) {
urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.addRequestProperty("Authorization", "Basic " + authorizationHeader);
}
return sendAccessTokenRequest(urlConn, postBody);
}
public Map<String, Object> getToken(String tokenUrl, String requestBody, String authorizationHeader)
throws Exception {
// LOG.info("Request : getToken "+ tokenUrl);
URL url = new URL(tokenUrl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Accept", "application/json");
if (null != authorizationHeader && !authorizationHeader.isEmpty()) {
urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.addRequestProperty("Authorization", "Basic " + authorizationHeader);
}
return sendAccessTokenRequest(urlConnection, requestBody);
}
private Map<String, Object> sendAccessTokenRequest(HttpsURLConnection urlConn, String postBody) throws Exception {
// Write to input stream
try {
//optional
enableAllSSLCert(urlConn);
urlConn.setDoOutput(true);
//optional
urlConn.setHostnameVerifier((name, session) -> true);
DataOutputStream outputStream = new DataOutputStream(urlConn.getOutputStream());
outputStream.writeBytes(postBody);
outputStream.flush();
outputStream.close();
int responseCode = urlConn.getResponseCode();
InputStream is = null;
// LOG.info(" response code is:" + responseCode);
if (responseCode >= 200 && responseCode < 400) {
is = urlConn.getInputStream();
} else {
// LOG.error("Error, sendOAuthRequest response code is:" + responseCode);
is = urlConn.getErrorStream();
}
// Read response
String response = null;
if (null != is) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder();
while (true) {
String line = bufferedReader.readLine();
if (line == null) {
break;
} else {
stringBuilder.append(line);
}
}
response = stringBuilder.toString();
bufferedReader.close();
}
// Logging in case of error
if (responseCode != 200) {
// LOG.error("Get Token error response : " + response);
}
System.out.println(response);
Map<String, Object> retValue = new HashMap<>();
retValue.put("errorCode", responseCode);
retValue.put("token", response);
return retValue;
} catch (Exception exp) {
// LOG.info(" Exception while getting Access Token:", exp);
throw exp;
}
}
public static boolean notNullOrEmptyTrim(String str) {
return !isNullOrEmptyTrim(str);
}
public static boolean isNullOrEmptyTrim(String s) {
return s == null || s.trim().isEmpty();
}
/**
* Enable https client for all SSL cert
*
* #param urlConn
* #throws NoSuchAlgorithmException
* #throws KeyManagementException
*/
private void enableAllSSLCert(HttpsURLConnection urlConn) throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAllTrustManager() }, new java.security.SecureRandom());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = (hostname, session) -> true;
urlConn.setHostnameVerifier(allHostsValid);
}
/**
* Override Trust All trust manager
*/
private class TrustAllTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
I am trying to post data in Jersey but all I get is a 500 error. My GET requests are all working fine.
Below is my client code.
package main;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
public class MainClass {
public static void main(String[] args) {
try {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("admin", "admin"));
WebResource webResource = client
.resource("http://localhost:7307/mysite/rest_service/postdataclass/postData");
String input = "{\"name\":\"Violent Soho\",\"last\":\"Jesus Stole My Girlfriend\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
And Here is my other class
package service.utils;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import beans.AASample;
#Path("postdataclass")
public class PostSample {
#GET
#Path("/sayHell")
public Response sayHell() {
return Response.status(Response.Status.OK).entity("Hell").build();
}
#POST
#Path("/postData")
#Consumes(MediaType.APPLICATION_JSON)
public Response postData(AASample sample) {
return Response.status(Response.Status.OK).entity("Profile " + sample.toString()).build();
}
}
And my AAClass
package beans;
public class AASample {
private String name;
private String last;
public AASample(String name, String last) {
super();
this.name = name;
this.last = last;
}
public AASample() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
#Override
public String toString() {
return "AASample [name=" + name + ", last=" + last + "]";
}
}
Below is the Server Log when I Make the Post Request.
Jul 08, 2016 8:35:22 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 3 * Server has received a request on thread http-nio-8090-exec-4
3 > POST http://localhost:8090/mysite/rest_service/postdataclass/postData
3 > accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
3 > authorization: Basic YWRtaW46YWRtaW4=
3 > connection: keep-alive
3 > content-length: 43
3 > content-type: application/json
3 > host: localhost:8090
3 > user-agent: Java/1.8.0_20
Jul 08, 2016 8:35:23 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Spot Buddy Service] in context with path [/mysite] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.AbstractMethodError: com.fasterxml.jackson.jaxrs.base.ProviderBase._configForReading(Lcom/fasterxml/jackson/databind/ObjectMapper;[Ljava/lang/annotation/Annotation;)Lcom/fasterxml/jackson/jaxrs/cfg/EndpointConfigBase;] with root cause
java.lang.AbstractMethodError: com.fasterxml.jackson.jaxrs.base.ProviderBase._configForReading(Lcom/fasterxml/jackson/databind/ObjectMapper;[Ljava/lang/annotation/Annotation;)Lcom/fasterxml/jackson/jaxrs/cfg/EndpointConfigBase;
at com.fasterxml.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:644)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:260)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
I converted my data to a json object manually. changed post method to
#POST
#Path("/postData")
#Consumes(MediaType.APPLICATION_JSON)
public Response postData(String sample) {
AASample object = StringToObjectConverter.getObject(sample);
if(object != null){
return Response.status(Response.Status.OK).entity("Object " + object.toString()).build();
}else{
return Response.status(Response.Status.OK).entity("We Failed Decoding :" + sample +":").build();
}
}
StringToObjectConverter class
package main
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import beans.AASample;
public class StringToObjectConverter {
public static AASample getObject(String postedData) {
AASample aaSample = null;
ObjectMapper mapper = new ObjectMapper();
try {
aaSample = mapper.readValue(postedData, AASample.class);
} catch (JsonGenerationException e) {
aaSample = null;
} catch (JsonMappingException e) {
aaSample = null;
} catch (IOException e) {
aaSample = null;
}
return aaSample;
}
}
Is it possible to retrieve and log the request XML to a file at OutFaultInterceptor when I hit an error such as fail schema validation?
I have tried search the web but don't seems to be able to find much related to this.
Yest it is possible. I have wrote CxfOutInterceptor for getting XML of the message. Here is the code:
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CacheAndWriteOutputStream;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.io.CachedOutputStreamCallback;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CxfOutInterceptor extends AbstractPhaseInterceptor<Message> {
private static final Logger LOGGER = LoggerFactory.getLogger(CxfInInterceptor.class);
public CxfOutInterceptor() {
super(Phase.PRE_STREAM);
}
public static final String SINGLE_KEY = CxfOutInterceptor.class.getName() + ".Processed";
private static final int LIMIT = 10 * 1024 * 1024;
#Override
public void handleFault(Message message) {
LOGGER.trace("handleFault");
try {
internalHandleMessage(message);
} catch (Throwable ex) {
LOGGER.error("Exception thrown by internalHandleMessage: ", ex);
} finally {
LOGGER.trace("handleFault - end");
}
}
#Override
public void handleMessage(Message message) throws Fault {
LOGGER.trace("handleMessage");
try {
if (onceOnly(message)) {
LOGGER.debug("handled message previously");
return;
}
internalHandleMessage(message);
} finally {
LOGGER.trace("handleMessage - end");
}
}
private class LogCallback implements CachedOutputStreamCallback {
private final Message message;
private final OutputStream origStream;
public LogCallback(final Message msg, final OutputStream os) {
this.message = msg;
this.origStream = os;
}
#Override
public void onFlush(CachedOutputStream cos) {
}
#Override
public void onClose(CachedOutputStream cos) {
StringBuilder requestBuilder = new StringBuilder();
String encoding = (String) message.get(Message.ENCODING);
try {
writePayload(requestBuilder, cos, encoding);
//requestBuilder - is your actuall body of the message.
} catch (IOException ex) {
LOGGER.trace("Unable to write output stream to StringBuilder:\n" + ex.toString());
}
try {
cos.lockOutputStream();
cos.resetOut(null, false);
} catch (Exception ex) {
LOGGER.info("Ignoring exception");
}
message.setContent(OutputStream.class, origStream);
}
}
private void internalHandleMessage(Message message) {
final OutputStream os = message.getContent(OutputStream.class);
final Writer writer = message.getContent(Writer.class);
if (os == null && writer == null) {
return;
}
if (os == null) {
message.setContent(Writer.class, writer);
} else {
final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(os);
message.setContent(OutputStream.class, newOut);
newOut.registerCallback(new LogCallback(message, os));
}
}
private static boolean onceOnly(Message message) {
if (message.getExchange().containsKey(SINGLE_KEY)) {
return true;
} else {
message.getExchange().put(SINGLE_KEY, Boolean.TRUE);
return false;
}
}
private static void writePayload(StringBuilder builder, CachedOutputStream cos, String encoding)
throws IOException {
if (StringUtils.isEmpty(encoding)) {
cos.writeCacheTo(builder, LIMIT);
} else {
cos.writeCacheTo(builder, encoding, LIMIT);
}
}
}
You will get the XML of the message in onClose method. Refer to this comment: //requestBuilder - is your actuall XML of the message.
I have been doing a RMI chat system on school and wanted some sort of file sharing with it. Have not done something like this before and have not been through this at school, but I wanted to try. Have done some searching on google and this
http://java.sun.com/developer/technicalArticles/RMI/rmi_corba/
was the best i found. Is this "technology" new so i can use it? Did not get it to work, but that can be my lack of Java knowledge.
Some tips why i don't get it to work?
There isn't a tremendous difference between sending messages back and forth and sending files. The answer depends largely on what your current code looks like. Do you have some code to share?
What does your current RMI interface look like? What does your architecture look like?
Do you have a server that clients connect to?
Do you have a method sendChat(String message)?
With respect to having sendChat(), you could probably add a sendFile( ... ). Then the question is just what you want to do for the parameters.
Do you want to send a java.io.File object? A byte[] (along with a String name, maybe a boolean flag to distinguish binary files)?
Seeing that this is your first time doing this, you might want to code the mundane parts yourself. However, tasks like obtaining bytes from a file are rather common annoyances. The Apache commons and Google guava libraries both provide methods to simplify the process. I suppose it depends on the learning goals you have on this project.
Yes. The clients connects to the server, and are able to chat in chatrooms.
Here is some of the code we have until now, except the file for connecting and communication with the database, and the GUI. Thanks for answering.
Interfaces:
Chatfront interface:
public interface ChatFront extends Remote {
boolean registerClient(Client client, String password) throws RemoteException;
void logMeOut(Client client) throws RemoteException;
void newChannelMessage(String toChannel, String fromUser, String message) throws RemoteException;
void newPrivateMessage(String fromUser, String toUser, String message) throws RemoteException;
String connectChannel(String username, String channel) throws RemoteException;
String disconnectChannel(String username, String channel) throws RemoteException;
boolean isUserRegistered(String username) throws RemoteException;
void errorMessage(String toUser, String message) throws RemoteException;
}
Clientinterface:
public interface Client extends Remote {
String findName() throws RemoteException;
void newPrivateMessage(String fromUser, String toUser, String message) throws RemoteException;
void newMessageChannel(String toChannel, String fromUser, String message) throws RemoteException;
void newSystemMessageChannel(String toChannel, String fromUser, String message) throws RemoteException;
void errorMessage(String toUser, String message) throws RemoteException;
}
Serverside:
class ChatServer {
public static void main(String[] args) throws Exception {
String objectname = "chatter";
LocateRegistry.createRegistry(1099);
ChatFront cf = new ChatFrontImpl();
Naming.rebind(objectname, cf);
javax.swing.JOptionPane.showMessageDialog(null, "Tjener kjører. Trykk OK for å avslutte tjeneren.");
Naming.unbind(objectname);
System.exit(0);
}
}
ChatFrontImpl.java
package server;
import Interfaces.ChatFront;
import Interfaces.Client;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
/**
*
* #author sindre
*/
class ChatFrontImpl extends UnicastRemoteObject implements ChatFront {
private UserDAC u = new UserDAC();
private Hashtable<String, ArrayList<String>> channels = new Hashtable<String, ArrayList<String>>();
private ArrayList<Client> clients = new ArrayList<Client>();
public ChatFrontImpl() throws RemoteException {
}
/* Registrerer en ny client */
#Override
public synchronized boolean registerClient(Client client, String password) throws RemoteException {
if(!u.logIn(client.findName(), password)){
System.out.println("feil username eller password");
return false;
}
if (!clients.contains(client)) {
try {
clients.add(client);
System.out.println("Na er " + client.findName() + " registrert.");
} catch (Exception e){
System.out.println("Feil oppstatt i registrerMeg(): " + e);
}
return true;
} else
return false;
}
/* Kobler en client til en kanal */
#Override
public String connectChannel(String username, String kanal) throws RemoteException{
if(isUserRegistered(username)){
if (!channels.containsKey(kanal)) {
String message = "Bruker " + username + " har ankommet kanalen";
channels.put(kanal, new ArrayList<String>());
channels.get(kanal).add(username);
notifyChannelSystem(kanal, "SYSTEM", message);
notifySelf(username, "Skriv /? for mulige kommandoer");
return("Kanal opprettet, og bruker satt i kanalen.");
}
else{
if(channels.get(kanal).contains(username)){
return ("Brukeren er allerede i kanalen.");
} else {
channels.get(kanal).add(username);
String message = "Bruker " + username + " har ankommet kanalen";
notifyChannelSystem(kanal, "SYSTEM", message);
return ("Kanal fantes allerede. Bruker satt i kanalen.");
}
}
}
return "";
}
/*Sjekker om brukeren ikke er blank.*/
#Override
public boolean isUserRegistered(String username){
if(username.equals("")){
return false;
}
return true;
}
/* Kobler en bruker fra en kanal */
#Override
public String disconnectChannel(String username, String channel) throws RemoteException{
if(isUserInChannelX(username, channel)){
channels.get(channel).remove(username);
String message = "Bruker " + username + " har forlatt kanalen.";
notifySelf(username, " Du har nå forlatt kanalen " + channel);
notifyChannelSystem(channel, "SYSTEM", message);
if(channels.get(channel).isEmpty()){
channels.remove(channel);
}
}
return ("Bruker har forlatt kanalen.");
}
/* Kobler en client fra clientlisten */
#Override
public synchronized void logMeOut(Client client) throws RemoteException {
boolean isfound = false;
int clientIndeks = 0;
while (clientIndeks < clients.size() && !isfound) {
Client denne = clients.get(clientIndeks);
if (denne.equals(client)) { // bruker equals() for a sammenlikne stubbobjektene
isfound = true;
clients.remove(clientIndeks);
System.out.println("Na er clienten " + client.findName() + " fjernet.");
} else clientIndeks++;
}
}
/* Sjekker om brukeren finnes i en gitt kanal */
public boolean isUserInChannelX(String bruker, String kanal){
if(channels.containsKey(kanal) && channels.get(kanal).contains(bruker)){
return true;
} else {
return false;
}
}
/* Kaller metoden varsleKanal()*/
#Override
public void newChannelMessage(String tilKanal, String fraBruker, String message) throws RemoteException{
if(isUserInChannelX(fraBruker, tilKanal)){
notifyChannel(tilKanal, fraBruker, message);
}
else{
}
}
/* Kaller metoden varsleEn() */
#Override
public void newPrivateMessage(String fra, String toUser, String message) throws RemoteException{
notifyUser(fra,toUser,message);
}
#Override
public void errorMessage(String toUser, String message) throws RemoteException{
notifySelf(toUser, message);
}
private void notifySelf(String toUser, String message) throws RemoteException{
for(Client k: clients){
if(k.findName().equals(toUser)){
k.errorMessage(toUser, message);
}
}
}
/* Bruker metoden nymessagePrivat() + ser om brukeren er tilkoblet*/
private void notifyUser(String fromUser, String toUser, String message) throws RemoteException{
boolean funnet = false;
for(Client k : clients){
if(k.findName().equals(toUser)){
k.newPrivateMessage(fromUser, toUser, message);
funnet = true;
}
}
if (!funnet) errorMessage(fromUser, "Ingen brukere ved dette navnet!");
}
/* Kjører metoden nymessageKanal() */
private void notifyChannel(String toChannel, String fromUser, String message) throws RemoteException{
if(channels.containsKey(toChannel) && isUserRegistered(fromUser)){
for(String k : channels.get(toChannel)){
for(Client cli : clients){
if(cli.findName().equals(k)){
cli.newMessageChannel(toChannel, fromUser, message);
}
}
}
}
else{
System.out.println("Brukeren er ikke registrert.");
}
}
private void notifyChannelSystem(String toChannel, String fromUser, String message) throws RemoteException{
if(channels.containsKey(toChannel) && isUserRegistered(fromUser)){
for(String k : channels.get(toChannel)){
for(Client kli : clients){
if(kli.findName().equals(k)){
kli.newMessageChannel(toChannel, fromUser, message);
}
}
}
}
else{
System.out.println("Brukeren er ikke registrert.");
}
}
}
Clientside:
GUILogic.java
package gui;
import Interfaces.ChatFront;
import Interfaces.Client;
import java.rmi.Naming;
import java.rmi.RemoteException;
import klient.ClientImpl;
/**
*
* #author sindre
*/
public class GUILogic {
GUI gui;
ChatFront cf;
public String username;
public String channel;
public String password;
public String message;
public GUILogic(GUI gui){
this.gui = gui;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/* Kobler GUI klienten opp mot serveren */
public void createCFConnection(String username, String password) throws Exception{
String objectname = "chatter";
String hostname = "localhost";
String url = "rmi://" + hostname + "/" + objectname;
cf = (ChatFront) Naming.lookup(url);
Client k = new ClientImpl(username, gui);
cf.registerClient(k, password);
}
public void connectChannel(String username, String channel) throws RemoteException{
cf.connectChannel(username, channel);
}
public void disconnectChannel(String username, String channel) throws RemoteException{
cf.disconnectChannel(username, channel);
}
public void newChannelMessage(String toChannel, String fromUser, String message) throws RemoteException{
cf.newChannelMessage(fromUser ,toChannel, message);
}
public void newPrivateMessage(String fromUser, String toUser, String message) throws RemoteException{
cf.newPrivateMessage(fromUser, toUser, message);
}
public void errorMessage(String toUser, String message) throws RemoteException{
cf.errorMessage(toUser, message);
}
/* Logger klienten av GUIen */
public boolean logOut(String username) throws RemoteException{
Client k = new ClientImpl(username, gui);
if(k.findName().equals("")){
return false;
} else {
cf.logMeOut(k);
System.out.println("user " + username + " logget ut.");
return true;
}
}
/* Analysermessage har funnet / i starten av messageen, og da blir denne metoden kjørt. */
public String commandWritten(String username, String channel, String message) throws RemoteException{
String[] result = message.split(" ", 3);
String channel1;
if((result[0].equalsIgnoreCase("/join") || (result[0].equalsIgnoreCase("/j")))){
channel1 = result[1];
setChannel(channel1);
connectChannel(username, channel1);
}
else if(result[0].equalsIgnoreCase("/leave") || (result[0].equalsIgnoreCase(("/l")))){
channel = result[1];
disconnectChannel(username, channel);
}
else if(result[0].equalsIgnoreCase("/whisper") || (result[0].equalsIgnoreCase(("/w")))){
for (int x=2; x<result.length; x++)
newPrivateMessage(username, result[1], result[x]);
}
else if(result[0].equalsIgnoreCase("/exit") || (result[0].equalsIgnoreCase(("/e")))){
System.exit(0);
}
else if(result[0].equalsIgnoreCase("/?")){
errorMessage(username, "Mulige kommandoer er:" + "\n" +
"/leave 'channel' eller /l" + "\n" +
"/whisper 'username' eller /w" + "\n" +
"/join 'channel' eller /j" + "\n" +
"/exit eller /e" + "\n");
}
else{
errorMessage(username, "Feil kommando! Skriv /? for mulige kommandoer");
}
return message;
}
/* Analyserer messageen som skrives inn i messagefeltet. Kommandoer starter med / */
public void analyzeMessage(String username, String channel, String message) throws RemoteException{
String text = getMessage().toLowerCase();
char command = '/';
for(int i = 0; i<1; i++){
char c = text.charAt(0);
if(c == command){
commandWritten(username, channel, text);
}
else {
newChannelMessage(username, channel, text);
}
}
}
}