I am new in Play Framework and need some advice.
In my project I send AJAX request but unfortunatly Play Framework raise error which you can see below. From error message you can notice that problem most likely in controller. Where was my mistake? How to fix this error?
[error] application -
! #79mg8k016 - Internal server error, for (GET) [/] ->
play.api.UnexpectedException: Unexpected exception[CreationException: Unable to create injector, see the following errors:
1) No implementation for play.api.db.Database was bound.
while locating play.api.db.Database
for the 1st parameter of controllers.GetValuesController.<init>(GetValuesController.scala:14)
while locating controllers.GetValuesController
for the 4th parameter of router.Routes.<init>(Routes.scala:33)
at play.api.inject.RoutesProvider$.bindingsFromConfiguration(BuiltinModule.scala:121):
Binding(class router.Routes to self) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)
1 error]
at play.core.server.DevServerStart$$anon$1.reload(DevServerStart.scala:186)
at play.core.server.DevServerStart$$anon$1.get(DevServerStart.scala:124)
at play.core.server.AkkaHttpServer.handleRequest(AkkaHttpServer.scala:241)
at play.core.server.AkkaHttpServer.$anonfun$createServerBinding$1(AkkaHttpServer.scala:138)
at akka.stream.impl.fusing.MapAsyncUnordered$$anon$26.onPush(Ops.scala:1304)
at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:519)
at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:482)
at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:378)
at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:588)
at akka.stream.impl.fusing.GraphInterpreterShell$AsyncInput.execute(ActorGraphInterpreter.scala:472)
Caused by: com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for play.api.db.Database was bound.
while locating play.api.db.Database
for the 1st parameter of controllers.GetValuesController.<init>(GetValuesController.scala:14)
while locating controllers.GetValuesController
for the 4th parameter of router.Routes.<init>(Routes.scala:33)
at play.api.inject.RoutesProvider$.bindingsFromConfiguration(BuiltinModule.scala:121):
Binding(class router.Routes to self) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)
It seems like something wrong in controller. Where is my mistake, how to fix it?
I use:
JDK 1.8.0_181
SBT 0.13.5
Scala 2.12
Play Framework 2.6.20
routes:
GET /get_values controllers.GetValuesController.get_data_from_db(start_date_time:String, end_date_time:String, city_name:String)
GetValuesController.scala:
package controllers
import javax.inject._
import akka.actor.ActorSystem
import play.api.Configuration
import play.api.mvc.{AbstractController, ControllerComponents}
import play.api.libs.ws._
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future, Promise}
import services._
import play.api.db.Database
class GetValuesController#Inject()(db: Database, conf: Configuration, ws: WSClient, cc: ControllerComponents, actorSystem: ActorSystem)(implicit exec: ExecutionContext) extends AbstractController(cc) {
def get_data_from_db(start_date_time: String, end_date_time: String, city_name: String) = Action.async {
getValue(1.second, start_date_time: String, end_date_time: String, city_name: String).map {
message => Ok(message)
}
}
private def getValue(delayTime: FiniteDuration, start_date_time: String, end_date_time: String, city_name: String): Future[String] = {
val promise: Promise[String] = Promise[String]()
val service: GetValuesService = new GetValuesService(db)
actorSystem.scheduler.scheduleOnce(delayTime) {
promise.success(service.get_values(start_date_time, end_date_time, city_name))
}(actorSystem.dispatcher)
promise.future
}
}
GetValuesService.scala:
package services
import play.api.db.Database
import play.api.libs.json._
class GetYoutubeSpeedValuesService(db: Database) {
def get_youtube_speed_values(start_date_time: String, end_date_time: String, city_name: String): String ={
val SQL_STATEMENT = "SELECT " +
"table_name.\"Stamper\" AS DATE_TIME, " +
"table_name.\"CITY\" AS CITY, " +
"MAX(table_name.avg) AS MAX_SPEED " +
"FROM table_name" +
"WHERE table_name.\"CITY\"='" + city_name + "' " +
"AND (table_name.\"Stamper\" BETWEEN '" + start_date_time + "' AND '" + end_date_time + "') " +
"GROUP BY table_name.\"Stamper\", table_name.\"CITY\";"
val connection = db.getConnection()
var json_array = Json.arr()
try {
val query = connection.createStatement.executeQuery(SQL_STATEMENT)
while (query.next()) {
val json_object = Json.obj(
"DATE_TIME" -> query.getString(1),
"CITY" -> query.getString(2),
"MAX_SPEED" -> query.getString(3)
)
json_array +:= json_object
}
} finally {
connection.close()
}
println(json_array)
json_array.toString()
}
}
application.conf:
db.postgres.driver=org.postgresql.Driver
db.postgres.url="jdbc:postgresql://host:port/database_name"
db.postgres.username = "username"
db.postgres.password = "password"
Javascript:
$.ajax({
type: "POST",
url: "http://localhost:9000/get_values",
data: {
start_date_time: '2018-10-01 00:00:00',
end_date_time: '2018-10-31 23:00:00',
city_name: 'London'
},
success: function (result) {
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("jqXHR: " + jqXHR);
console.log("textStatus: " + textStatus);
console.log("errorThrown: " + errorThrown);
}
});
ERROR:
Action Not Found
For request 'POST /get_values'
In the same time controller works now correctly! If I call lets say such url: http://localhost:9000/get_values?start_date_time=2018-10-01%2000:00:00&end_date_time=2018-10-31%2023:00:00&city_name=London it return me JSON data.
Well, finally we found the problem. The problem was in application.conf file. In my case I used next database configuration:
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://host:port/database_name"
db.default.username = "username"
db.default.password = "password"
Also in AJAX code I remove this part: type: "POST"
Related
I would like to understand why a variable of type com.ibm.jms.JMSTextMessage is printed with truncated content and ellipses (...) when converted to string.
I have this code in a JSR223 Sampler in JMeter:
import com.ibm.msg.client.jms.JmsConnectionFactory
import com.ibm.msg.client.jms.JmsFactoryFactory
import com.ibm.msg.client.wmq.WMQConstants
import javax.jms.Session
import javax.jms.TextMessage
def hostName = "127.0.0.1"
def hostPort = 1414
def channelName = "DEV.APP.SVRCONN"
def queueManagerName = "QM1"
def queueName = "DEV.QUEUE.1"
def ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER)
def cf = ff.createConnectionFactory()
cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, hostName)
cf.setIntProperty(WMQConstants.WMQ_PORT, hostPort)
cf.setStringProperty(WMQConstants.WMQ_CHANNEL, channelName)
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT)
def connInboundQueue = cf.createConnection("user", "password")
def sessInboundQueue = connInboundQueue.createSession(false, Session.AUTO_ACKNOWLEDGE)
def payload = "AAA:+.? '\n" +
"ABC+ABCD:1+ABCDEFG:ZZ+ABCDEF:ZZ+123456:2042+12345678901++ABCD'\n" +
"DEF+ABCD+LH+FVKJUB+20000:2042+Y1234567+UN+D:21B'\n" +
"GHI+1+ABCD:D:11A:AA:ABCD+ABCD12345678901123ABC123456'\n" +
"JKL+745'\n" +
"HHH+TN:IIAA891011213531235BNM422244:::001'\n" +
"CCC+NT+++ABCDEFGHIJKLMNOPQRS'\n" +
"STU+00123456789012:UF+0000000000:GY'\n" +
"VXY+50+MI1234+++MI'\n" +
"AAA+235+ABC'\n" +
"BBB+200:3202062000:301'\n" +
"FFF+90+USA'\n" +
"BBB+232:2101051135:201'\n" +
"CCC+FF+++AaBaBa001:TEST1'\n" +
"DDD+3++G'\n" +
"EEE+329:711013'\n" +
"FFF+178+XXX'\n" +
"FFF+179+YYY'\n" +
"GGG+2+ZZZ'\n" +
"HHH+BXG:ABCDEF'\n" +
"HHH+ABC:12AB3E01234E8UD8'\n" +
"III+P:110:111+100000001'\n" +
"EEE+36:281105'\n" +
"FFF+91+ASD'\n" +
"VVV+50:2'\n" +
"XXX+0011+1'\n" +
"YYY+1+U0123456'\n" +
"ZZZ+1+U1234560002'\n"
TextMessage msg = sessInboundQueue.createTextMessage()
msg.setText(payload)
log.info(msg.toString())
log.info(msg.getClass().toString())
log.info(msg.getText())
I would like to understand why log.info(msg.toString()) does not print the whole text content and show ellipses after some point (...)
If I do log.info(msg.getText()), I can see the whole text message.
Here is the print outcome in jmeter's console:
2021-10-31 22:05:25,491 INFO o.a.j.p.j.s.J.JSR223 Sampler - Producer - Inbound Queue:
JMSMessage class: jms_text
JMSType: null
JMSDeliveryMode: 2
JMSDeliveryDelay: 0
JMSDeliveryTime: 1635710725481
JMSExpiration: 0
JMSPriority: 4
JMSMessageID: ID:414d5120514d312020202020202020201f537d6101c31040
JMSTimestamp: 1635710725481
JMSCorrelationID: 1757416553
JMSDestination: queue:///DEV.QUEUE.1
JMSReplyTo: null
JMSRedelivered: false
JMSXAppID: 4.1\bin\ApacheJMeter.jar
JMSXDeliveryCount: 0
JMSXUserID: mquser1
JMS_IBM_PutApplType: 28
JMS_IBM_PutDate: 20211031
JMS_IBM_PutTime: 20052548
AAA:+.? '
ABC+ABCD:1+ABCDEFG:ZZ+ABCDEF:ZZ+123456:2042+12345678901++ABCD'
DEF+ABCD+LH+FVKJUB+20000:20 ...
2021-10-31 22:05:25,491 INFO o.a.j.p.j.s.J.JSR223 Sampler - Producer - Inbound Queue: class com.ibm.jms.JMSTextMessage
2021-10-31 22:05:25,491 INFO o.a.j.p.j.s.J.JSR223 Sampler - Producer - Inbound Queue: AAA:+.? '
ABC+ABCD:1+ABCDEFG:ZZ+ABCDEF:ZZ+123456:2042+12345678901++ABCD'
DEF+ABCD+LH+FVKJUB+20000:2042+Y1234567+UN+D:21B'
GHI+1+ABCD:D:11A:AA:ABCD+ABCD12345678901123ABC123456'
JKL+745'
HHH+TN:IIAA891011213531235BNM422244:::001'
CCC+NT+++ABCDEFGHIJKLMNOPQRS'
STU+00123456789012:UF+0000000000:GY'
VXY+50+MI1234+++MI'
AAA+235+ABC'
BBB+200:3202062000:301'
FFF+90+USA'
BBB+232:2101051135:201'
CCC+FF+++AaBaBa001:TEST1'
DDD+3++G'
EEE+329:711013'
FFF+178+XXX'
FFF+179+YYY'
GGG+2+ZZZ'
HHH+BXG:ABCDEF'
HHH+ABC:12AB3E01234E8UD8'
III+P:110:111+100000001'
EEE+36:281105'
FFF+91+ASD'
VVV+50:2'
XXX+0011+1'
YYY+1+U0123456'
ZZZ+1+U1234560002'
According to the IBM documentation com.ibm.jms.JMSTextMessage inherits the toString() implementation from com.ibm.jms.JMSMessage and the JavaDoc for that method says:
Gets a String containing a formatted version of the message header.
My guess is that the body is cut off simply because toString() is really just meant to give you the header. However, only IBM would know for sure why it works that way. To be clear, there is no guarantee that toString() will (or should) return the entire body of the message.
If you really want to inspect the body of the text message you should invoke getText(). This method is required to return the body of the text-message according to the JMS JavaDoc as well as IBM's own JavaDoc. Both state:
Gets the String containing this message's data. The default value is null.
Im currently using Grails 4 for a RESTfull App.
Have the following controller, a custom one that throws a json response:
package nslbv_siu
import grails.rest.*
import grails.converters.*
class LoginController
{
static allowedMethods = [ login:'POST' ]
static responseFormats = [ 'json', 'xml' ]
static defaultAction = "login"
def login()
{
if( params.user == '' )
{
render "{ 'succes':false, 'error':'Ingrese su usuario.' }"
}
if( params.pass == '' )
{
render "{ 'success':false, 'error':'Ingrese su contraseña.' }"
}
def attempted_user = User.queryUserByUsernameAndActive( params.user, true )
if( attempted_user )
{
if ( attempted_user.pass == params.pass.md5() )
{
render "{ 'success':true, 'error':'', " +
"'user':'" + attempted_user.user + "', " +
"'mail':'" + attempted_user.dni + "', " +
"'apenom':'" + attempted_user.apenom + "', " +
"'profile_pic':'" + attempted_user.profile_pic + "' }"
}
else
{
render "{ 'success':false, 'error':'Usuario o Contraseña incorrectos' }"
}
}
else
{
render "{ 'success':false, 'error':'Usuario o Contraseña incorrectos' }"
}
}
User queryUserByUsernameAndActive(String username, Boolean active)
{
User.all.find
{
it.user == username && it.active == active
}
}
}
Need to call http://localhost:8080/login?user=myuser&pass=mypass
But throws 404 not found, dont know why!, must I use another convention to make my routes be published?
My mappings:
package nslbv_siu
class UrlMappings {
static mappings =
{
delete "/$controller/$id(.$format)?"(action:"delete")
get "/$controller(.$format)?"(action:"index")
get "/$controller/$id(.$format)?"(action:"show")
post "/$controller(.$format)?"(action:"save")
put "/$controller/$id(.$format)?"(action:"update")
patch "/$controller/$id(.$format)?"(action:"patch")
"/"(controller: 'application', action:'index')
"500"(view: '/error')
"404"(view: '/notFound')
"/login"(controller: "LoginController", action: "login") -->does not seem to work
}
}
I dont understand why it does not work!, am I doing something wrong?
grails url-mappings-report throws the following
Dynamic Mappings
| * | ERROR: 404 | View: /notFound |
| * | ERROR: 500 | View: /error |
Controller: LoginController
| POST | /login | Action: login |
Controller: application
| * | / | Action: index |
It was:
"/login"(controller: "login", action: "login")
instead of
"/login"(controller: "LoginController", action: "login")
I using io.fabric8.kubernetes-client, version 4.1.1. I'm trying to load the yaml using io.fabric library.
---
apiVersion: "velero.io/v1"
kind: "BackupStorageLocation"
spec:
providerType: "aws"
objectStorage:
bucket: "test"
config:
region: "us-west-1"
metadata:
annotations: {}
name: "default"
namespace: "velero"
labels: {}
String content = "---\n" +
"apiVersion: \"velero.io/v1\"\n" +
"kind: \"BackupStorageLocation\"\n" +
"spec:\n" +
" providerType: \"aws\"\n" +
" objectStorage:\n" +
" bucket: \"test\"\n" +
" config:\n" +
" region: \"us-west-1\"\n" +
"metadata:\n" +
" annotations: {}\n" +
" name: \"default\"\n" +
" namespace: \"velero\"\n" +
" labels: {}\n" +
"";
List<HasMetadata> list = client.load(new ByteArrayInputStream(content.trim().getBytes())).createOrReplace();
Getting the following exception:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No resource type found for:velero.io/v1#BackupStorageLocation
at [Source: (BufferedInputStream); line: 14, column: 13]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:271)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:1718)
at io.fabric8.kubernetes.internal.KubernetesDeserializer.deserialize(KubernetesDeserializer.java:78)
at io.fabric8.kubernetes.internal.KubernetesDeserializer.deserialize(KubernetesDeserializer.java:32)
at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1611)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1188)
at io.fabric8.kubernetes.client.utils.Serialization.unmarshal(Serialization.java:129)
Support for creating custom resources has been added in Kubernetes client recently. You could load Custom Resource Definitions but in order to provide use custom resources you needed to provide model for that custom resource, see old CrdExample. But it has now been made less typed(without providing any custom resource model(Pojos) to client. You can now create custom resources like this(I'm on 4.2.2 bdw):
For a custom resource definition named animal:
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: animals.jungle.example.com
spec:
group: jungle.example.com
versions:
- name: v1
served: true
storage: true
scope: Namespaced
names:
plural: animals
singular: animals
kind: Animal
shortNames:
- al
In order to create custom resources you need to provide CustomResourceDefinitionContext to client. The below example shows creation via InputStream or raw string. For more details, see this.
CustomResourceDefinitionContext customResourceDefinitionContext = new CustomResourceDefinitionContext.Builder()
.withName("animals.jungle.example.com")
.withGroup("jungle.example.com")
.withVersion("v1")
.withPlural("animals")
.withScope("Namespaced")
.build();
// Create via file
Map<String, Object> object = client.customResource(customResourceDefinitionContext).create(currentNamespace, getClass().getResourceAsStream("/test-rawcustomresource.yml"));
// Create via raw json/yaml
String rawJsonCustomResourceObj = "{\"apiVersion\":\"jungle.example.com/v1\"," +
"\"kind\":\"Animal\",\"metadata\": {\"name\": \"walrus\"}," +
"\"spec\": {\"image\": \"my-awesome-walrus-image\"}}";
object = client.customResource(customResourceDefinitionContext).create(currentNamespace, rawJsonCustomResourceObj);
I am trying to connect to Cloud SQL ( Mysql ) using my java code. I am getting the below error -
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create socket factory 'com.google.cloud.sql.mysql.SocketFactory' due to underlying exception:
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: com.google.cloud.sql.mysql.SocketFactory
Here is my code -
package utils
import java.sql.DriverManager
import java.sql.Connection
import scala.collection.mutable.ListBuffer
import entity.AnalyticFieldEntity
import compute.driver.AnalyticTools
import entity.ErrorHandlingEntity
object ScalaDbConnect {
def getAnalyticBatchMap(toolId : Int, paramMap: Map[String, String]): Map[String, Int] = {
val methodName = "getAnalyticBatchMap"
val errorMode = paramMap.get("mode")+"("+paramMap.get("analyticSource")+")"
val dbTuple = DbPropertiesReader.getDbProperties()
val databaseName = dbTuple._3
val instanceConnectionName = dbTuple._4
val username= dbTuple._1
val password= dbTuple._2
var connection: Connection = null
val analyticMap = collection.mutable.Map.empty[String, Int]
try {
//[START doc-example]
val jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory", databaseName, instanceConnectionName);
println(jdbcUrl);
//Class.forName("com.mysql.jdbc.GoogleDriver");
val connection = DriverManager.getConnection(jdbcUrl, username, password);
println(connection);
//[END doc-example]
try
{
val statement = connection.createStatement()
val resultSet = statement.executeQuery("SELECT omnitureColumnHeader.columnHeaderId, case when analyticFieldMap.isTag = 1 then concat(\"tag_\",analyticFieldMap.entityField) else " +
"analyticFieldMap.entityField end as entityField FROM omnitureColumnHeader INNER JOIN analyticFieldMap ON " +
"analyticFieldMap.analyticFieldBatch=omnitureColumnHeader.columnHeaderValue where analyticFieldMap.toolId = " + toolId);
System.out.println("resultSet: 2" + statement);
System.out.println("statement: 2" + resultSet);
while (resultSet.next()) {
System.out.println("inside the content loop: 2");
analyticMap += resultSet.getString("entityField") -> resultSet.getInt("columnHeaderId")
}
System.out.println("analyticMap: 2" + analyticMap);
}
catch
{
case _: Throwable => println("Got some other kind of exception")
}
} catch {
case e: Exception =>
val errorHandlingEntity = new ErrorHandlingEntity()
errorHandlingEntity.Mode=errorMode
errorHandlingEntity.Tool=paramMap.get("tool").toString()
errorHandlingEntity.Message="DB Connection Issue"
errorHandlingEntity.Trace=e.printStackTrace().toString()
errorHandlingEntity.Source = "Spark"
errorHandlingEntity.YarnAppId=paramMap.get("appID").toString()
errorHandlingEntity.MethodName=methodName
errorHandlingEntity.ReThrow = true
errorHandlingEntity.CurrentException=e
ErrorHandlingFramework.HandleException(errorHandlingEntity)
}
connection.close()
analyticMap.toMap
}
}
I have added the below details in my POM.XML
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.3</version>
</dependency>
Here is the complete POM.XML - https://pastebin.com/jvxSBZMX
I am trying to connect to Google Cloud SQL using my scala code and i am using the JAVA API(S).
The issue i am facing indicates, i am not able to access the correct class for the connection.
Any help would be appreciated.
Looking forward for the solution.
Thanks,
The issue is with how google cloud runs the maven Build.
It is not able to read the classes from the build so i passed those JAR Files with the extention --JARS .
This solves my issue.
package modifiedlines;
import edu.nyu.cs.javagit.api.DotGit;
import edu.nyu.cs.javagit.api.JavaGitConfiguration;
import edu.nyu.cs.javagit.api.JavaGitException;
import edu.nyu.cs.javagit.api.WorkingTree;
import edu.nyu.cs.javagit.api.commands.GitLogResponse;
import edu.nyu.cs.javagit.api.commands.GitStatus;
import edu.nyu.cs.javagit.api.commands.GitStatusOptions;
import edu.nyu.cs.javagit.api.commands.GitStatusResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
*
* #
author aryan000
*/
public class UseGit {
private static File repositoryDirectory;
private static DotGit dotGit;
public static void main(String s[]) throws JavaGitException, IOException
{
File f = new File("C:\\Program Files\\Git\\bin\\git.exe");
if(!f.exists())
{
System.out.println("does not exist");
}
else
System.out.println("exists at " + f.getPath());
JavaGitConfiguration.setGitPath("C:\\Program Files\\Git\\bin");
System.out.println("Git version : " + JavaGitConfiguration.getGitVersion());
// repositoryDirectory = new File("/home/aryan000/Desktop/retrofit");
repositoryDirectory = new File("/home/aryan000/Desktop/changeprone/changeprone");
System.out.println("Git Repository Location : " + repositoryDirectory.getAbsolutePath());
//get the instance of the dotGit Object
dotGit = DotGit.getInstance(repositoryDirectory);
// System.out.println("checking what i have got ");
// GitLogResponse.CommitFile com ;
// com = (GitLogResponse.CommitFile) dotGit.getLog();
//
// System.out.println(com);
WorkingTree wt = dotGit.getWorkingTree();
File workingTreePath = wt.getPath();
GitStatus gitStatus = new GitStatus();
GitStatusResponse status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
File anotherFileDir = new File("/home/aryan000/Desktop/retrofit/test.txt");
GitStatusOptions options = new GitStatusOptions();
options.setOptOnly(true);
status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
System.out.println("----- Print log to see our commit -----");
for (GitLogResponse.Commit c : dotGit.getLog()) {
System.out.println("commit id is : " + c.getSha());
System.out.println(" commit message is : " + c.getMessage());
System.out.println(" author of the commit is : " + c.getAuthor());
System.out.println(" date modified is : " + c.getDateString());
System.out.println(" number of files changed is : " + c.getFiles());
List<GitLogResponse.CommitFile> store = c.getFiles();
if(store!=null)
System.out.println("the number of files changed is : " + store.size());
System.out.println("list of files changed is : " + c.getFilesChanged());
System.out.println("total number of additions : " + c.getLinesDeleted());
System.out.println("total number of merger : " + c.getMergeDetails());
}
// for(GitLogResponse.CommitFile c : dotGit.getLog())
}
}
Output is shown as :
Exception in thread "main" edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified. { path=[C:\Program Files\Git\bin] }
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:220)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:247)
at modifiedlines.UseGit.main(UseGit.java:40)
Caused by: edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified.
at edu.nyu.cs.javagit.api.JavaGitConfiguration.determineGitVersion(JavaGitConfiguration.java:81)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:217)
... 2 more
Java Result: 1
My query is how to find git logs and the files changed due to a particular commit using a Java Program.
Can any 1 help me in this.
Please See : This code is working fine in Ubuntu i.e. no Path problem still I am unable to get the files changed during a commit. It is give me a List as a null.
This bug was opened a long time ago and just fixed it. Please give it a try , use master branch please, and let me know if it works for you.