How To Use I18N Messages In A Grails Plugin - plugins

I've added a new exception to my plugin:
class UnzipException extends RuntimeException {
String message
String defaultMessage
String fileName
}
. . .
else {
throw new UnzipException(
message:"grailsant.unzipexception.badfile",
defaultMessage: "Invalid zip file: ${zipFile}",
fileName: zipFile)
}
...
And in the plugin's messages.properties I have:
grailsant.unzipexception.badfile=Invalid zip file: {0}
Two questions:
How do I get {0} filled in with fileName?
Can an application override the grailsant.unzipexception.badfile message?

(1) It seems like this has to be done by app:
try {
. . .
} catch (org.grails.plugins.grailsant.UnzipException e) {
flash.message = e.message
flash.args = [e.fileName]
flash.defaultMessage = e.defaultMessage
}
(2) Yep, if the message.properties in the app has the same key as the plugin, the app's values will be used.

Related

Not able to remove folder name inspite of delting all files inside it in spark

I am deleting output folders before running my spark job .
Sometime it deletes it but sometime it delete all the files inside it but top level folder still remains .
I have sub folders kind of structure .
This is how i am deleting the folders .
def DeleteDescrFolder(fs: org.apache.hadoop.fs.FileSystem, descrFileURL: String) = {
val bDescr = fs.exists(new Path(descrFileURL))
if (true.equals(bDescr)) {
val outputFile = fs.globStatus(new Path(descrFileURL))
for (DeleteFilePath <- outputFile) {
fs.delete(DeleteFilePath.getPath)
}
println("Descr File is delete from " + descrFileURL)
} else {
println(descrFileURL + "Decsr Does not Exist")
}
}
How can i remove folder name also ?
You are deleting the files inside the folder specified. Try the following code which will delete the folder as well
def DeleteDescrFolder(fs: org.apache.hadoop.fs.FileSystem, descrFileURL: String) = {
if (fs.exists(new Path(descrFileURL))) {
try{
fs.delete(new Path(descrFileURL),true)
println("Descr folder is deleted " + descrFileURL)
}catch{case e: Exception =>
print("exeption "+e)
}
} else {
println(descrFileURL + "Decsr Does not Exist")
}
}

Google Web Toolkit - XSRF Protected Services : Invalid RPC Token

I've implemented XSRF Protected Services in GWT project. I'm using GWT 2.6.0 release. When I try to load my app in a browser I get a very strange exception as follows:
Uncaught com.google.gwt.user.client.rpc.RpcTokenException: Invalid RPC token (Invalid RpcToken type: expected 'com.google.gwt.user.client.rpc.XsrfToken' but got 'class com.google.gwt.user.client.rpc.XsrfToken')
I've searched my classpath and I only have one XsrfToken class provided by gwt-servlet.jar located inside my WAR file. I downloaded 2.6 code from GIT and I see the code that is throwing the exception is provided by ProxyCreator.java in the method generateCheckRpcTokenTypeOverride.
Does anyone have any idea as to why this exception would be thrown. The error indicates to me at least that it should pass given that what is expected is what it has.
I'm pasting the method in for completeness:
protected void generateCheckRpcTokenTypeOverride(SourceWriter srcWriter, TypeOracle typeOracle,
SerializableTypeOracle typesSentFromBrowser) {
JClassType rpcTokenType = typeOracle.findType(RpcToken.class.getName());
JClassType[] rpcTokenSubtypes = rpcTokenType.getSubtypes();
String rpcTokenImplementation = "";
for (JClassType rpcTokenSubtype : rpcTokenSubtypes) {
if (typesSentFromBrowser.isSerializable(rpcTokenSubtype)) {
if (rpcTokenImplementation.length() > 0) {
// >1 implematation of RpcToken, bail
rpcTokenImplementation = "";
break;
} else {
rpcTokenImplementation = rpcTokenSubtype.getQualifiedSourceName();
}
}
}
if (rpcTokenImplementation.length() > 0) {
srcWriter.println("#Override");
srcWriter.println("protected void checkRpcTokenType(RpcToken token) {");
srcWriter.indent();
srcWriter.println("if (!(token instanceof " + rpcTokenImplementation + ")) {");
srcWriter.indent();
srcWriter.println("throw new RpcTokenException(\"Invalid RpcToken type: " + "expected '"
+ rpcTokenImplementation + "' but got '\" + " + "token.getClass() + \"'\");");
srcWriter.outdent();
srcWriter.println("}");
srcWriter.outdent();
srcWriter.println("}");
}
}
Thanks very much in advance.

Can't upload file to Google Drive from service account

I am trying to upload a file to google drive using google service account.
Driver Service
public static Drive getDriveService(String secretKeyFile) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(secretKeyFile))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).setApplicationName("appl name").build();
return service;
}
Insert File
private static File insertFile(Drive service, String title, String description,String mimeType, String filename) {
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
Main Method
Drive service=null;
try {
String secretFile= "somedigit-privatekey.p12";
service = getDriveService(secretFile);
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
File insertFile = insertFile(service, "test title", "File description", "text/plain", "c:\\test.txt");
List list = service.files().list();
System.out.println("Files Id : "+insertFile.getId());
System.out.println("Count Files : "+list.size());
Now, my questions is :
How and where can i check that file was uploaded?
Why it returns the file ID but list.size() is zero.
It returns the download link also but when i paste that link in
browser it doesn't download any file.
You are creating a listing request but not executing it. Use execute method to make the request:
service.files().list().execute();
If you paste the download link into the browser, it will respond with 401, because your download request should also contain a valid Authorization header. Use the following snippet to download the file programmatically.
HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
InputStream stream = resp.getContent();
stream is an input stream for the file content.
Or add an Authorization: Bearer <access token> to the request you're making elsewhere.

Gradle plugin copy file from plugin jar

I'm creating my first gradle plugin. I'm trying to copy a file from the distribution jar into a directory I've created at the project. Although the file exists inside the jar, I can't copy it to the directory.
This is my task code:
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
class InitTask extends DefaultTask {
File baseDir;
private void copyEnvironment(File environments) {
String resource = getClass().getResource("/environments/development.properties").getFile();
File input = new File(resource);
File output = new File(environments, "development.properties");
try {
copyFile(input, output);
}
catch (IOException e) {
e.printStackTrace();
}
}
void copyFile(File sourceFile, File destFile) {
destFile << sourceFile.text
}
#TaskAction
void createDirectories() {
logger.info "Creating directory."
File environments = new File(baseDir, "environments");
File scripts = new File(baseDir, "scripts");
File drivers = new File(baseDir, "drivers");
[environments, scripts, drivers].each {
it.mkdirs();
}
copyEnvironment(environments);
logger.info "Directory created at '${baseDir.absolutePath}'."
}
}
And this is the error I'm getting:
:init
java.io.FileNotFoundException: file:/path-to-jar/MyJar.jar!/environments/development.properties (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at groovy.util.CharsetToolkit.<init>(CharsetToolkit.java:69)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.newReader(DefaultGroovyMethods.java:15706)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.getText(DefaultGroovyMethods.java:14754)
at org.codehaus.groovy.runtime.dgm$352.doMethodInvoke(Unknown Source)
at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.doMethodInvoke(GeneratedMetaMethod.java:70)
at groovy.lang.MetaClassImpl$GetBeanMethodMetaProperty.getProperty(MetaClassImpl.java:3465)
at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:61)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at br.com.smartcoders.migration.tasks.InitTask.copyFile(InitTask.groovy:29)
Just to emphasize, the development.properties is inside the environments directory inside the MyJar.jar
getClass().getResource() returns a URL. To access that URL, you'll have to read it directly (e.g. with url.text) rather than first converting it to a String/File. Or you can use getClass().getResourceAsStream().text, which is probably more accurate. In both cases you can optionally specify the file encoding.
Kotlin DSL answer!
For cases like this it is good to have extensions:
fun Any.getResource(filename: String): File? {
val input = this::class.java.classLoader.getResourceAsStream(filename) ?: return null
val tempFile = File.createTempFile(
filename.substringBeforeLast('.'),
"." + filename.substringAfterLast('.')
)
tempFile.deleteOnExit()
tempFile.writer().use { output ->
input.bufferedReader().use { input ->
output.write(input.readText())
}
}
return tempFile
}

Symfony2 + DoctrineMongoDBBundle Configuration

I am trying to connect Symfony 2 with MongoDB in such way:
Register DoctrineMongoDBBundle in AppKernel::registerBundles
method
Set 'doctrine_mongo_db' configuration (see below config.yml)
Get 'doctrine.odm.mongodb.document_manager' from container in
HelloController action
And when I am trying to run the application MongoConnectionException is thrown.
Can anyone help me to solve this problem?
AppKernel.php
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\DoctrineMongoDBBundle\DoctrineMongoDBBundle(),
new Sensio\HelloBundle\HelloBundle()
);
return $bundles;
}
config.yml
framework:
charset: UTF-8
router: { resource: "%kernel.root_dir%/config/routing.yml" }
templating: { engines: ['twig'] }
## Doctrine Configuration
doctrine_mongo_db:
server: mongodb://root:root#192.168.0.111:27017
default_database: test
options: { connect: true }
mappings:
HelloBundle: { type: annotation, dir: Document }
# Twig Configuration
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
HelloController.php
/* #var $dm \Doctrine\ODM\MongoDB\DocumentManager */
$dm = $this->get('doctrine.odm.mongodb.document_manager');
Exception (line 96)
connecting to failed: Transport endpoint is not connected
in ~/vendor/doctrine-mongodb/lib/Doctrine/MongoDB/Connection.php line 96 ยป
93. if ($this->server) {
94. $this->mongo = new \Mongo($this->server, $this->options);
95. } else {
96. $this->mongo = new \Mongo();
97. }
The problem is in DoctrineMongoDBBundle configuration loading. The fix (https://github.com/fabpot/symfony/pull/740) should be merged soon.
For now you can use fixed method below.
public function load(array $configs, ContainerBuilder $container)
{
$mergedConfig = array();
foreach ($configs as $config) {
$mergedConfig = array_merge_recursive($mergedConfig, $config);
}
$this->doMongodbLoad($mergedConfig, $container);
}