id stringlengths 36 36 | text stringlengths 1 1.25M |
|---|---|
19ffbe37-9800-4b6e-888e-0a7085ea03e9 | private int processRequestToServer(String command)
{
int status = 0;
try
{
socketout.writeBytes(command + '\n');
socketout.flush();
System.out.println(socketin.readLine());
}catch(IOException e){
status = 1;
System.err.println(e);
}
return status;
} |
d181f3d0-e7a1-4cf4-b87d-eed358fedbaa | private void help()
{
System.out.println("To run client:\n");
System.out.println("run.sh/.jar -client <input file>\n");
} |
b6e3ed83-3704-4d6f-b862-2119768707fd | public int execute (String fileName)
{
int status = 0;
try
{
if(fileName != null)
{
File file = new File(fileName);
FileInputStream fis = null;
BufferedReader br = null;
bookReservationClient client = null;
char serverInstanceNo = fileName.charAt(6);
boolean connected = false;
try
{
fis = new FileInputStream(file);
String line = null;
int linecounter = 1;
int noOfServers = 0;
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
while ((line = br.readLine()) != null) {
//System.out.println(line);
if (linecounter == 1)
{
noOfServers = Integer.valueOf(line);
}
else if((linecounter > 1) && (linecounter <= (1+noOfServers)))
{
if(!connected)
{
if (line.contains(":"))
{
String[] parts = line.split(":");
if( startClient(parts[0], parts[1]) == 0)
{
//System.out.println("connected to " + line);
connected = true;
}
else
{
//System.out.println("Failed connecting to " + line);
connected = false;
}
}
else
{
//do nothing
//System.out.println("wrong format " + line);
}
}
else
{
//do nothing
//System.out.println("discarding " + line);
}
}
else
{
if(connected)
{
String clientId = "c" + serverInstanceNo;
if(line.contains(clientId))
{
String[] str;
str = line.split(" ");
if (str.length >= 3)
{
processRequestToServer(line);
//System.out.println("processing " + line);
}
else if (str.length == 2)
{
Thread.sleep(Integer.valueOf(str[1]));
}
}
else
{
//do nothing
//System.out.println("Discarding as not to be processed by this client " + line);
}
}
else
{
//do nothing
//System.out.println("No server found to process " + line);
}
}
linecounter++;
}
if(connected)
{
stopClient();
connected = false;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null)
br.close();
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
else
{
help();
}
}catch (Exception ioe){
help();
}
return status;
} |
a19b5529-044c-4780-b417-1e2d8d2c7928 | sAddress (String ip, String port) {
sip = ip;
sport = port;
} |
0a853a85-77a2-48a8-b223-d9f1e2fcc8cc | public ProcessClientRequest(Socket reqSocket)
{
aClient = reqSocket;
try
{
din = new BufferedReader(new InputStreamReader(aClient.getInputStream()));
dout = new DataOutputStream(aClient.getOutputStream());
}catch (IOException ioe){
System.err.println(ioe);
}
} |
0801c71f-6c4f-4993-b2b2-af77c47f71e9 | public void run()
{
boolean done = false;
try
{
if((din != null) && (dout != null))
{
//.out.println("new connection thread\n");
while (true) {
// System.out.println("processing requests\n");
if ((mykmsg != 0) && // if configured to snooze
(mytotmsg >= mykmsg)) {
mytotmsg = 0;
snoozeT(aClient); // it's time to snooze
//loadlib(); // restore point for book information
}
done = handlecmd(din, dout); // service client requests
if (done)
{
dout.close();
din.close();
aClient.close();
return;
}
}
}
}catch (IOException ioe){
//System.out.println("cleaning up processing thread\n");
System.err.println(ioe);
}
} |
4839d095-f931-4ab5-bbf5-a51e851ca752 | public bookServer (String a) {
fileName = a;
} |
a81c8c6a-eae5-4a1c-849c-56cd931c1f92 | @Override
public void run () {
initconfig(); // initialize from config file
loadlib();
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
try
{
// create socket and listen
myip = sa[mypid].sip;
myport = sa[mypid].sport;
ServerSocket listner = new ServerSocket(Integer.parseInt(myport),
NBACKLOG, InetAddress.getByName(myip));
while (true)
{
//System.out.println("Waiting for connections:\n");
Socket aClient = listner.accept();
ProcessClientRequest request = new ProcessClientRequest(aClient);
executor.execute(request);
}
}catch (IOException ioe){
executor.shutdown();
System.err.println(ioe);
}
} |
ea483c62-17ee-46fa-849a-e5a2b0f459d2 | public void initconfig() {
BufferedReader bin;
boolean foundcmd;
String[] str;
String cfile;
cfile = fileName;
mytotmsg = 0;
// determine self process id
mypid = Integer.parseInt(cfile.substring("Server".length(),cfile.indexOf(".")));
try {
bin = new BufferedReader(new FileReader(cfile));
rline = bin.readLine();
str = rline.split(" ");
numservers = Integer.parseInt(str[0]);
numBooks = Integer.parseInt(str[1]);
sa = new sAddress[numservers+1];
lm = new lamportMutex();
// get list of server addresses
for (int i=1; i<=numservers; i++) {
rline = bin.readLine();
str = rline.split(":");
sa[i] = new sAddress (str[0], str[1]);
}
// read rest of the file & command for this server
rline = bin.readLine();
foundcmd = false;
while ((rline != null) && !foundcmd) {
str = rline.split(" ");
if (str[0].equals("s"+Integer.toString(mypid)) &&
(str.length >= 2)) {
foundcmd = true;
mykmsg = Integer.parseInt(str[1]);
myunrespt = Integer.parseInt(str[2]);
}
rline = bin.readLine();
}
if (!foundcmd) { // no command for this server
mykmsg = 0;
myunrespt = 0;
}
} catch (java.io.IOException e) {
System.out.println(e);
}
} |
00f38d02-1743-4b58-8deb-1c0e1fdae49c | public void loadlib () {
// sync restore point
Socket aserver = null;
BufferedReader din;
DataOutputStream dout;
boolean foundS;
int i;
bl = new bookLibrary(numBooks);
// look for a running server to get library information
foundS = false;
i = 1;
while (i<=numservers && !foundS) {
try
{
aserver = new Socket(sa[i].sip, Integer.parseInt(sa[i].sport));
foundS = true; // successfully connected to a server
} catch (java.io.IOException ex) {
foundS = false;
}
i++;
}
try {
if (foundS && (aserver != null)) { // found a server
din = new BufferedReader (new InputStreamReader(aserver.getInputStream()));
dout = new DataOutputStream(aserver.getOutputStream());
bl.brsync(din, dout);
din.close();
dout.close();
aserver.close();
} else {
// do nothing, start with an empty slate
}
} catch (java.io.IOException ex) {
System.out.println(ex);
}
} |
d9588321-00dd-4cb7-b75b-0cf35252bd45 | synchronized public boolean handlecmd (BufferedReader din, DataOutputStream dout) {
String[] str;
int ret;
String getline = null;
boolean connectionClosed = false;
try {
getline = din.readLine();
if(getline != null)
{
//System.out.println("handlecmd: " + getline);
str = getline.split(" ");
if (str.length >=2) {
if (str[2].compareTo("reserve") == 0)
{
lm.requestCS(); // lamport mutex
ret = bl.breserve(str[0], str[1]);
lm.releaseCS();
if (ret == 1)
dout.writeBytes(str[0] + " " + str[1] + '\n');
else
dout.writeBytes("fail " + str[0] + " " + str[1] + '\n');
dout.flush();
mytotmsg++;
}
else if (str[2].compareTo("return") == 0)
{
lm.requestCS(); // lamport mutex
ret = bl.breturn(str[0], str[1]);
lm.releaseCS();
if (ret == 1)
dout.writeBytes("free " + str[0] + " " + str[1] + '\n');
else
dout.writeBytes("fail " + str[0] + " " + str[1] + '\n');
dout.flush();
mytotmsg++;
}
else if (str[2].compareTo("sync") == 0)
{
bl.bwsync(dout);
mytotmsg++;
}
else if (str[2].compareTo("exit") == 0)
{
//System.out.println("connection closed 3\n");
connectionClosed = true;
}
else
{
// invalid command, dont send response to client
}
} else {
// invalid command, dont send response to client
}
}
} catch (java.io.IOException e) {
connectionClosed = true;
System.out.println(e);
} finally{
return connectionClosed;
}
} |
5faacb7b-f8cb-48af-a0b7-49d8a5f5eb67 | synchronized public void snoozeT (Socket clientSocket) {
boolean done;
long itime, ftime;
done = false;
itime = System.currentTimeMillis();
ftime = itime;
while (!done) {
try {
//System.out.println("snoozing:\n");
Thread.sleep(myunrespt);
} catch (InterruptedException e) {
// do nothing
}
// did we snooze enough?
ftime = System.currentTimeMillis();
if ((ftime-itime) >= myunrespt) done = true;
}
} |
6266667b-06db-474e-a5cd-050c418b7b76 | public void lamportMutex() {
// to be implemented
} |
d0b8920b-ca24-46ce-85b5-60ad3993582f | public void requestCS() {
// to be implemented
} |
c71a2ba7-6530-4fd2-8add-e60bbcdd06cc | public void releaseCS() {
// to be implemented
} |
bdd61812-a40f-485a-bdc8-2db39eaaed04 | public Payment(){
} |
0d197fca-12d1-408a-8b3c-9a21d674cbb4 | public Payment (String id, String payType, String amount){
this.id = id;
this.setPayType(payType);
this.setAmount(amount);
} |
e03de6aa-d9c0-4ab2-90f9-d5a11766b20e | public Payment (String id, String payType, String amount, String cardDetails){
this.id = id;
this.setPayType(payType);
this.setAmount(amount);
this.setCardDetails(cardDetails);
} |
a6daca8a-6382-485d-bbd1-72c02ec2ed0b | public String getId() {
return id;
} |
990ca8d8-56a0-43b0-82b5-01fd999dbb6f | public void setId(String id) {
this.id = id;
} |
d54e0581-f6c8-46c9-8710-03c3940f867f | public String getDetail() {
return detail;
} |
747026b1-ace7-4b5d-b342-c4d7db52f96d | public void setDetail(String detail) {
this.detail = detail;
} |
5de1fd47-d424-4ec0-ab71-cc900599494f | public String getPayType() {
return payType;
} |
b8a65fe8-dcb8-47a8-8d37-6b9085bd35cb | public void setPayType(String payType) {
this.payType = payType;
} |
d5538e70-8c0e-4e74-8d61-b6baf5865a8b | public String getAmount() {
return amount;
} |
30ea7752-a990-4190-8f49-e53f3d2a25dc | public void setAmount(String amount) {
this.amount = amount;
} |
2e35e75e-f352-4c63-84de-c57ee7946e00 | public String getCardDetails() {
return cardDetails;
} |
e9b2970f-38da-46fa-bbd0-7b30f2c0c64e | public void setCardDetails(String cardDetails) {
this.cardDetails = cardDetails;
} |
251dfc09-3198-4ab1-b2a1-ba9321e171af | public Order(){
} |
7e07faba-1ff9-4f7a-bf36-03b5d79d44a1 | public Order (String id, String coffeeType, String cost, String additions){
this.id = id;
this.setCoffeeType(coffeeType);
this.setCost(cost);
this.setAdditions(additions);
} |
c74b9b86-5886-416f-96e9-8d220b0ac4c4 | public Order (String id, String coffeeType, String cost){
this.id = id;
this.setCoffeeType(coffeeType);
this.setCost(cost);
} |
6527efe9-dd2c-42bc-ab39-6918eb733560 | public String getId() {
return id;
} |
c09b8364-d3ee-4e84-8af8-681e04c99ff7 | public void setId(String id) {
this.id = id;
} |
ff228341-7641-42bf-9301-75244929f27b | public String getCoffeeType() {
return coffeeType;
} |
e44a22e1-090b-46fa-92f5-4d264ed3e999 | public void setCoffeeType(String coffeeType) {
this.coffeeType = coffeeType;
} |
d60fc6b6-8cac-4ba0-a7d4-52fb18173346 | public String getCost() {
return cost;
} |
0b429c3b-83dc-44a0-bc5f-fb9196c136ac | public void setCost(String cost) {
this.cost = cost;
} |
bc3f1ed4-0b83-4e10-90a3-5e830a32b7b7 | public String getAdditions() {
return additions;
} |
7151541f-546e-462a-b584-bc9297e36655 | public void setAdditions(String additions) {
this.additions = additions;
} |
c24da83b-ae41-4e28-b668-63f28f35276d | public String getStatus() {
return status;
} |
f197a1ec-3e4b-4acf-b5b5-6225fdb97599 | public void setStatus(String status) {
this.status = status;
} |
f99d2212-11a7-4028-8cae-4b4eb8246d36 | public String getReleased() {
return released;
} |
5359cdac-b594-4fb8-960b-3613fe39e8d3 | public void setReleased(String released) {
this.released = released;
} |
ae02283f-675a-4757-80e7-e02faa9eb67e | public PaymentDao() {
log.info("Trying to create a connection with the database");
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
log.info("Connection with the database created successfuly");
//not created yet
//Payment p = new Payment("3", "card", "3.20");
//p.setCardDetails("9874654321");
//contentStore.put(p.getId(), p);
} |
0abbb294-d7f4-4a28-aa43-f0c51fe6cb8b | public void addPayment(Payment pay) {
Session session = sessionFactory.openSession();
session.beginTransaction();
//parameter checks
session.save(pay);
session.getTransaction().commit();
session.close();
log.info("Created order with id: " + pay.getId());
} |
0bc0a8a9-1632-4572-a6c6-8c936778d97e | public Payment getPaymentById(String id) {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Payment where id=:id");
query.setParameter("id", id);
@SuppressWarnings("unchecked")
List<Payment> pays = query.list();
session.close();
if(pays.size() > 0)
return (Payment) pays.get(0);
else
return null;
} |
360e64e3-070d-431c-a2f1-6ea6729d8911 | public List<Payment> getAllPayments() {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Payment");
List<Payment> paymentList = new ArrayList<Payment>();
@SuppressWarnings("unchecked")
List<Payment> allPayments = query.list();
session.close();
for (int i = 0; i < allPayments.size(); i++) {
Payment order = (Payment) allPayments.get(i);
paymentList.add(order);
}
return paymentList;
} |
f726c0a6-90fb-4d5a-b631-518784edb1c5 | public void deletePayment(Payment p) {
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
session.delete(p);
session.getTransaction().commit();
} catch (IllegalArgumentException ie) {
ie.printStackTrace();
}
session.close();
} |
666c66b3-3af3-4194-beaa-604396c78c69 | public void updatePayment(Payment newPayment) {
Session session = sessionFactory.openSession();
session.beginTransaction();
//parameter checks
session.saveOrUpdate(newPayment);
session.getTransaction().commit();
session.close();
log.info("Updated payment with id: " + newPayment.getId());
log.info(newPayment.getCardDetails());
} |
0c79df94-e19d-4986-af82-f6cb3463541c | protected void finalize() throws Throwable {
super.finalize();
sessionFactory.close();
} |
e77154b1-272d-4b9f-b8fd-1c938e8ba080 | public OrderDao() {
log.info("Trying to create a connection with the database");
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
log.info("Connection with the database created successfuly");
} |
28679ea2-8849-40e5-8e63-1e840cf49d5c | public void addOrder(Order order) {
Session session = sessionFactory.openSession();
session.beginTransaction();
//parameter checks
session.save(order);
session.getTransaction().commit();
session.close();
log.info("Created order with id: " + order.getId());
} |
1870b3bb-f3f8-4a9a-80c5-f3c2db1c1c89 | public void updateOrder(Order newOrder) {
Session session = sessionFactory.openSession();
session.beginTransaction();
//parameter checks
session.update(newOrder);
session.getTransaction().commit();
session.close();
log.info("Updated order with id: " + newOrder.getId());
} |
707892a6-0f0f-4c60-829e-0efa6cd95f1e | public Order getOrderById(String id) {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Order where id=:id");
query.setParameter("id", id);
@SuppressWarnings("unchecked")
List<Order> order = query.list();
session.close();
if(order.size() > 0) {
return order.get(0);
}
else
return null;
} |
1e8b95cf-4b87-47da-9c62-c57c7e933995 | public List<Order> getAllOrders() {
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Order");
List<Order> orderList = new ArrayList<Order>();
@SuppressWarnings("unchecked")
List<Order> allOrders = query.list();
session.close();
for (int i = 0; i < allOrders.size(); i++) {
Order order = (Order) allOrders.get(i);
orderList.add(order);
}
return orderList;
} |
25373ef5-24c6-4bd4-88a2-c9ef16d73725 | public void deleteOrder(Order o) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.delete(o);
session.getTransaction().commit();
session.close();
} |
fc082f5b-ad4c-4583-a714-b6e673222f46 | protected void finalize() throws Throwable {
super.finalize();
while (!sessionFactory.isClosed()) {
sessionFactory.close();
}
} |
d3b97c3c-f4a6-4e3e-9d2a-69874430fd6c | @GET
@Produces(MediaType.TEXT_XML)
public List<Order> getOrdersBrowser(
@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)){
response.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
OrderDao ord = new OrderDao();
return ord.getAllOrders();
} |
8cb21465-72a0-438d-bb4b-fe73fe78eca7 | @GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Order> getOrders(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)){
response.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
OrderDao ord = new OrderDao();
return ord.getAllOrders();
} |
13684a56-afa4-4595-a744-880f5c3f9728 | @GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String getCount(@HeaderParam("Auth") String auth) {
if(auth == null || !auth.equals(AUTH_KEY))
return "Unauthorized";
OrderDao ord = new OrderDao();
int count = ord.getAllOrders().size();
return String.valueOf(count);
} |
601308ae-9c75-47c4-ab87-b171ee946095 | @POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String newOrder(
@FormParam("id") String id,
@FormParam("coffeetype") String cType,
@FormParam("cost") String cost,
@FormParam("additions") String additions,
@Context HttpServletResponse servletResponse,
@HeaderParam("Auth") String auth
) throws IOException {
if(auth == null || !auth.equals(AUTH_KEY)){
servletResponse.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<html>Forbidden</html>")
.header("authorised", "false").build());
} else {
Order o;
if (additions != null) {
o = new Order(id, cType, cost, additions);
} else {
o = new Order(id, cType, cost);
}
OrderDao ord = new OrderDao();
ord.addOrder(o);
// Redirect to some HTML page
// You need to create this file under WEB-INF
servletResponse.setHeader("cost", cost);
servletResponse.setHeader("uri", "/orders/" + id);
servletResponse.setHeader("authorised", "true");
// TODO gives 204 no content error, needs to spit out some html
//servletResponse.sendRedirect("../create_order.html");
}
return "done";
} |
4e171ca0-eb98-487c-8429-64e8fff911a5 | @Path("{order}")
public OrderResource getOrder(
@PathParam("order") String id) {
return new OrderResource(uriInfo, request, id);
} |
d63ced9d-76b4-4671-9cb6-7bb8e9ccf96a | @OPTIONS
public Response optionsReq() {
String accConAllMet = "GET, POST, OPTIONS";
ResponseBuilder rb = Response.ok().header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", accConAllMet);
return rb.build();
} |
dcd49df9-c982-4575-b390-7085ca6b4a51 | public OrderResource(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
} |
6737642a-5ed8-4d7f-83e6-df133f6ba4e3 | @GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Order getOrder(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)) {
throw new WebApplicationException(Response
.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
//return new Order();
}
OrderDao ord = new OrderDao();
Order o = ord.getOrderById(id);
if(o==null) {
throw new WebApplicationException(Response
.status(Response.Status.NOT_FOUND.getStatusCode())
.entity("Not Found").build());
} else {
return o;
}
} |
55663ab0-ba15-48bb-ada8-431b85dffe0c | @GET
@Produces(MediaType.TEXT_XML)
public Order getOrderHTML(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)) {
throw new WebApplicationException(Response
.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
OrderDao ord = new OrderDao();
Order o = ord.getOrderById(id);
if(o==null) {
//throw new RuntimeException("GET: Order with" + id + " not found");
throw new WebApplicationException(Response
.status(Response.Status.BAD_REQUEST.getStatusCode())
.entity("Bad Request").build());
} else {
response.setStatus(Response.Status.CREATED.getStatusCode());
return o;
}
} |
48db9480-f61a-4072-bf41-f0806ee11e43 | @DELETE
public String deleteOrder(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)) {
throw new WebApplicationException(Response
.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
OrderDao ord = new OrderDao();
Order o = ord.getOrderById(id);
if (o!=null) {
ord.deleteOrder(o);
return "200 OK";
} else {
new RuntimeException("DELETE: Order with " + id + " not found").printStackTrace();
throw new WebApplicationException(Response
.status(Response.Status.NOT_FOUND.getStatusCode())
.entity("NOT FOUND").build());
}
} |
10ff9096-91bd-41fb-b64f-b8f00f1eabfa | @PUT
@Consumes(MediaType.APPLICATION_XML)
public String putOrder(JAXBElement<Order> o,
@HeaderParam("Auth") String auth,
@Context HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)) {
throw new WebApplicationException(Response.status(403)
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
Order newO = o.getValue();
Response r = putAndGetResponse(newO);
if (r.getStatus() == 201) {
//return newO;
return "newO";
} else {
throw new WebApplicationException(Response
.status(Response.Status.BAD_REQUEST.getStatusCode())
.entity("Bad Request").build());
//throw new RuntimeException("UPDATE: Error " + r.getStatus());
}
} |
913a69d0-52dc-4045-835c-e789fb443e5e | private Response putAndGetResponse(Order newOrder) {
Response res;
OrderDao ord = new OrderDao();
if(ord.getOrderById(newOrder.getId()) == null) {
res = Response.noContent().build();
} else {
res = Response.created(uriInfo.getAbsolutePath()).build();
ord.updateOrder(newOrder);
}
return res;
} |
8795aebb-d2bd-4e1f-96ea-7a6abf2d2e1a | @OPTIONS
public Response optionsOrderReq() {
OrderDao ord = new OrderDao();
String status = ord.getOrderById(id).getStatus();
String accConAllMet = "";
if (status == null) {
accConAllMet = "GET, PUT, DELETE, OPTIONS";
} else {
accConAllMet = "GET, OPTIONS";
}
ResponseBuilder rb = Response.ok().header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", accConAllMet);
return rb.build();
} |
e7bb97be-a625-49b4-8aa2-25e03558c68a | @GET
@Produces(MediaType.TEXT_XML)
public List<Payment> getPaymentsBrowser( @HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)){
response.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
return payDao.getAllPayments();
} |
6606548d-6cbd-4984-ae66-438af6be9535 | @GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public List<Payment> getPayments(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)){
response.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
return payDao.getAllPayments();
} |
9566baad-3ddb-49ac-91b6-762ddd56524b | @GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String getCount(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)){
response.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("Forbidden")
.header("authorised", "false").build());
}
return String.valueOf(payDao.getAllPayments().size());
} |
e09dcd9d-b369-4129-a52b-031843a776c9 | @Path("{payment}")
public PaymentResource getPayment(
@PathParam("payment") String id) {
return new PaymentResource(uriInfo, request, id);
} |
27a0f163-4c8b-4d1f-afc0-2c40c9523bd2 | @OPTIONS
public Response optionsReq() {
String accConAllMet = "GET, OPTIONS";
ResponseBuilder rb = Response.ok().header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", accConAllMet);
return rb.build();
} |
2936bc4e-478d-47da-996b-92a4ea108638 | public PaymentResource(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
this.payDao = new PaymentDao();
} |
764dae58-0fad-409f-9c9d-d16789e9beb3 | @GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Payment getPayment(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)){
response.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
Payment p = payDao.getPaymentById(id);
if(p==null)
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST.getStatusCode())
.entity("Bad Request").build());
return p;
} |
7bb82de8-19b7-4288-a10c-a5a127cafe46 | @GET
@Produces(MediaType.TEXT_XML)
public Payment getPaymentHTML(@HeaderParam("Auth") String auth,
@Context final HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)){
response.setHeader("authorised", "false");
throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN.getStatusCode())
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
Payment p = payDao.getPaymentById(id);
if(p==null)
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST.getStatusCode())
.entity("Bad Request").build());
return p;
} |
265afc10-4538-4950-b866-637dd2c852a4 | @PUT
@Consumes(MediaType.APPLICATION_XML)
public Response putOrder(JAXBElement<Payment> p,
@HeaderParam("Auth") String auth,
@Context HttpServletResponse response) {
if(auth == null || !auth.equals(AUTH_KEY)) {
throw new WebApplicationException(Response.status(403)
.entity("<error>Forbidden</error>")
.header("authorised", "false").build());
}
Payment newP = p.getValue();
Response r = putAndGetResponse(newP);
if (r.getStatus() == 201) {
return Response.created(uriInfo.getAbsolutePath()).entity(newP).build();
} else {
throw new WebApplicationException(Response
.status(Response.Status.BAD_REQUEST.getStatusCode())
.entity("Bad Request").build());
}
} |
407e83f0-dac6-4272-9dae-9ece83a529dc | private Response putAndGetResponse(Payment newPayment) {
Response res;
PaymentDao pay = new PaymentDao();
res = Response.created(uriInfo.getAbsolutePath()).build();
pay.updatePayment(newPayment);
return res;
} |
a6835fb7-6590-46e1-bac4-f8791808044b | @OPTIONS
public Response optionsReq() {
String accConAllMet = "GET, PUT, OPTIONS";
ResponseBuilder rb = Response.ok().header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", accConAllMet);
return rb.build();
} |
9cc8a862-2c95-4f01-81e6-6ec9d2c5f4e0 | public MyUtils() {} |
a7d9776e-fdb2-402b-bdc0-5263fde4736b | public static String someManipulation(String s) {
return s;
} |
6ba8a982-3962-4bac-946a-d4da37075f55 | public static boolean isNotBlank(String s) {
System.out.println("MyUtils#isNotBlank");
return true;
} |
9badb143-99cd-41ab-a271-e1b13fdfd158 | public MyUtilsExtension() {super();} |
0f40f892-eb17-4609-8abf-620e98400289 | public static String doSomething(String s) {
return s;
} |
0b698281-2cc0-40a3-a0cd-d2da0d982130 | @Test
public void test() {
assertEquals("Should be able to call first-class static method.",
TEST_VALUE, MyUtilsExtension.doSomething(TEST_VALUE));
assertEquals("Would like to be able to call super static method from inherited class",
TEST_VALUE, MyUtilsExtension.doSomething(TEST_VALUE));
assertTrue("MyUtils override says this is true.", MyUtils.isNotBlank(""));
} |
3d9518b4-a316-4fe0-b376-f34c05c74f4f | @Test
public void testSomething() {
} |
479263c4-0949-4b25-a670-cfcdff7a4abd | public ActionClick( int recordingID, Date index, String elementID )
{
super( recordingID, index );
m_elementID = elementID;
} |
6bd3819f-7cb2-4568-aea9-4a251d86da03 | public String getElementID()
{
return m_elementID;
} |
ecf20b4f-1d1c-4c5a-b97a-db2ec0bdd62e | public MySqlConnector()
{
Connect();
} |
a7cdb1a3-8e14-40a1-b202-2bb74da797e0 | public void Connect()
{
PoolProperties p = new PoolProperties();
p.setUrl( "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + database );
p.setDriverClassName( "com.mysql.jdbc.Driver" );
p.setUsername( dbUser );
p.setPassword( dbPassword );
p.setValidationQuery( "SELECT 1" );
p.setValidationInterval( 30000 );
p.setTimeBetweenEvictionRunsMillis( 2000 );
p.setMaxActive( 100 );
p.setInitialSize( 10 );
p.setMaxWait( 10000 );
p.setRemoveAbandonedTimeout( 60 );
p.setMinEvictableIdleTimeMillis( 1100000 );
p.setMinIdle( 10 );
p.setMaxIdle( 50 );
p.setJmxEnabled( true );
p.setLogAbandoned( true );
p.setRemoveAbandoned( true );
p.setTestOnBorrow( true );
p.setTestWhileIdle( true );
p.setTestOnReturn( false );
p.setAbandonWhenPercentageFull( 75 );
p.setJdbcInterceptors( "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" + "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" );
datasource = new DataSource();
datasource.setPoolProperties( p );
} |
16ee5af1-b00d-48e8-a247-47b43f1428eb | public int CreateRecording( String query, String name )
{
PreparedStatement ps;
try
{
conn = datasource.getConnection();
ps = conn.prepareStatement( query );
ps.setString( 1, name );
ps.executeUpdate();
ResultSet generatedKeys = ps.getGeneratedKeys();
if ( generatedKeys != null && generatedKeys.next() )
{
int newUserId = 0;
newUserId = generatedKeys.getInt( 1 );
return newUserId;
}
else
{
return -1;
}
}
catch ( SQLException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
}
} |
fd63c0ec-4307-4589-bd41-71b791c3a863 | public SqlWrapper()
{
mySql = new MySqlConnector();
} |
7e8ea2dd-b33c-45c6-9858-0ce690dbbfac | public String CreateRecording( String name )
{
int ID = mySql.CreateRecording( m_insertRecordingQuery, name );
JSONObject obj = new JSONObject();
obj.put( Commands.KEY_COMMAND, Commands.COMMAND_CREATE_RECORDING );
obj.put( Commands.KEY_RECORDING_ID, ID );
obj.put( Commands.KEY_NAME, name );
StringWriter out = new StringWriter();
try
{
obj.writeJSONString( out );
}
catch ( IOException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return out.toString();
} |
6dbd0c35-f129-45a6-ac63-a962366aa025 | public Main()
{
super();
m_sql = new SqlWrapper();
} |
c1904de5-bfb3-4e1c-83d9-6123b79f0431 | protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
} |
32e64422-2dbd-4c0d-ac2c-cda878a16754 | protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
try
{
String commandId;
JsonObject obj = new JsonObject();
// User real data from request
if ( !DEBUG_MODE )
{
String requestData = request.getParameter( Commands.KEY_DATA );
JsonParser parser = new JsonParser();
obj = ( JsonObject )parser.parse( requestData );
commandId = obj.get( Commands.KEY_COMMAND ).toString();
}
// Use debug data
else
{
/* Debug create recording */
obj.addProperty( Commands.KEY_COMMAND, Commands.COMMAND_CREATE_RECORDING );
commandId = obj.get( Commands.KEY_COMMAND ).toString();
}
// Check which command was received
//if ( commandId.equals( Commands.COMMAND_CREATE_RECORDING ) )
//{
CreateEmptyRecording( response, obj );
//}
//else if ( commandId.equals( Commands.COMMAND_SAVE_RECORDING ) )
//{
SaveRecording( response, obj );
//}
}
catch ( Exception e )
{
// General server exception
return;
}
} |
d71c8322-657e-41f8-9f7e-b7fe5204d46d | private void CreateEmptyRecording( HttpServletResponse response, JsonObject json )
{
String name = json.get( Commands.KEY_NAME ).toString();
String result = m_sql.CreateRecording( name );
try
{
response.getWriter().write( result );
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
6968ad73-9e19-44d2-bbf7-e20c7ee7968c | private void SaveRecording( HttpServletResponse response, JsonObject json )
{
String name = json.get( Commands.KEY_NAME ).toString();
String ID = json.get( Commands.KEY_RECORDING_ID ).toString();
String result = "";
if ( ID == null || ID == "" )
{
// New recording, first create entry in DB
result = m_sql.CreateRecording( name );
}
// Parse commands
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.